1. 程式人生 > 程式設計 >C語言實現簡單彈跳球遊戲

C語言實現簡單彈跳球遊戲

本文例項為大家分享了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;
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。