本文實例為大家分享了C語言實現彈跳球游戲的具體代碼,供大家參考,具體內容如下
#include <stdio.h>
#include <stdlib.h>
int main()
{
// 球的坐標
int pos_x,pos_y;
//球坐標的變化
int x =0;
int y = 5;
// 定義一個球的速度
int velocity_x=1;
int velocity_y=1;
//定義一個球運動的范圍
int top=0;
int botton=20;
int lift=0;
int right=20;
//讓球循環來回的跳動
while(1)
{
//x軸的速度變化
x = x + velocity_x;
y = y +velocity_y;
//清屏,用于每次繪圖,清除上一次球的位置。
system("cls");
for (pos_x=0 ; pos_x < x; pos_x ++)
{
// y軸每行畫換行符。
printf("\n");
}
for ( pos_y =0; pos_y <y; pos_y ++)
{
// x軸進行空格即可
printf(" ");
}
//利用速度velocity來控制球移動的方向
if( x == top || x == botton) //如果球的x坐標碰到了最頂端-1,向下運動。碰到最低端20則,向上運動。
{
velocity_x =-velocity_x; //改變正負數,則為改變方向
}
if( y == lift || y == right) //如果球的x坐標碰到了最zuo端-1,向下運動。碰到最you端20則,向上運動。
{
velocity_y =-velocity_y; //改變正負數,則為改變方向
}
//每次清屏后,進行繪0。
printf("0 \n");
}
system("pause");
}
該段落為球彈跳的基本邏輯,可以進行直接粘貼復制。編譯運行即可看到效果。
代碼已經寫好注釋。
再為大家一段簡單的控制臺彈跳小球實現代碼,感謝原作者的分享:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
// 全局變量
int x,y; //小球坐標
int velocity_x,velocity_y ; //速度
int left,right,top,bottom; //邊界
void gotoxy(int x,int y) //光標移動到(x,y)位置
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle,pos);
}
void HideCursor() // 用于隱藏光標
{
CONSOLE_CURSOR_INFO cursor_info = {1, 0}; // 第二個值為0表示隱藏光標
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void startup() // 數據初始化
{
x = 1;
y = 5;
velocity_x = 1; //速度方向
velocity_y = 1;
left = 0;
right = 30;
top = 0;
bottom = 15;
HideCursor(); // 隱藏光標
}
void show() // 顯示畫面
{
int i,j;
for (i=0;i<=bottom;i++)
{
for (j=0;j<=right;j++)
{
if((i==x) && (j==y))
{
printf("o"); //打印小球
}
else if ((i==0)||(i==bottom)||(j==0)||(j==right)) //打印邊界
{
printf("#");
}
else printf(" ");
}
printf("\n");
}
}
void automation() // 與用戶輸入無關的更新
{
x = x + velocity_x;
y = y + velocity_y;
if ((x==top)||(x==bottom))
{
velocity_x = -velocity_x;
printf("\a");
}
else if ((y==left)||(y==right))
{
velocity_y = -velocity_y;
printf("\a");
}
Sleep(100); //調低小球速度
}
int main()
{
system("color 2f"); //改變控制臺顏色
startup(); // 數據初始化
while (1) // 游戲循環執行
{
gotoxy(0,0); // 清屏
show(); // 顯示畫面
automation(); // 與用戶輸入無關的更新
}
return 0;
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。