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