C語言實現(xiàn)簡單彈跳球游戲
更新時間:2020年03月04日 10:07:52 作者:I hate you
這篇文章主要為大家詳細介紹了C語言實現(xiàn)簡單彈跳球游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了C語言實現(xiàn)彈跳球游戲的具體代碼,供大家參考,具體內(nèi)容如下
#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;
//讓球循環(huán)來回的跳動
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; //改變正負數(shù),則為改變方向
}
if( y == lift || y == right) //如果球的x坐標碰到了最zuo端-1,向下運動。碰到最you端20則,向上運動。
{
velocity_y =-velocity_y; //改變正負數(shù),則為改變方向
}
//每次清屏后,進行繪0。
printf("0 \n");
}
system("pause");
}
該段落為球彈跳的基本邏輯,可以進行直接粘貼復(fù)制。編譯運行即可看到效果。
代碼已經(jīng)寫好注釋。
再為大家一段簡單的控制臺彈跳小球?qū)崿F(xiàn)代碼,感謝原作者的分享:
#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() // 數(shù)據(jù)初始化
{
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() // 與用戶輸入無關(guān)的更新
{
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); //調(diào)低小球速度
}
int main()
{
system("color 2f"); //改變控制臺顏色
startup(); // 數(shù)據(jù)初始化
while (1) // 游戲循環(huán)執(zhí)行
{
gotoxy(0,0); // 清屏
show(); // 顯示畫面
automation(); // 與用戶輸入無關(guān)的更新
}
return 0;
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C++可變參數(shù)函數(shù)的實現(xiàn)方法示例
這篇文章主要給大家介紹了關(guān)于C++可變參數(shù)函數(shù)的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
C++替換棧中和.data中的cookie實現(xiàn)步驟詳解
這篇文章主要介紹了C++替換棧中和.data中的cookie實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-10-10
C字符串函數(shù)對應(yīng)的C++ string操作詳解
在本篇文章里小編給大家整理的是一篇關(guān)于C字符串函數(shù)對應(yīng)的C++ string操作知識點內(nèi)容,有興趣的朋友們學(xué)習(xí)下。2020-01-01

