弹球游戏 学习
代码转自知乎一个用C写一些小游戏:
https://zhuanlan.zhihu.com/p/24633092
实现小球的下落:
#include <stdio.h> #include <stdlib.h> int main(void) { int i,n; int x; int y=10; for (x=1;x<=10;x++) //这里每次用到一个清屏函数 { system("cls"); //清屏 for (i=0;i<x;i++) printf("\n"); for (n=0;n<y;n++)//将y改为x则可以实现倾斜下落 printf(" "); printf("o\n"); } return 0; }
实现了在一个范围内小球的上下左右跳动:
#include <stdio.h> #include <stdlib.h> int main(void) { int i,j; int x=0; int y=0; int velocity_x=1; int velocity_y=1; const int top=0; const int bottom=20; const int right=0; const int left=30; while(1) { x+=velocity_x; y+=velocity_y; system("cls");//clean the screen for (i=0;i<x;i++) printf("\n"); for (j=0;j<y;j++) printf(" "); printf("o\n"); if (x==bottom||x==top) velocity_x=-velocity_x;//if bump on the wall,ball bounce back if (y==right||y==left) velocity_y=-velocity_y; }
return 0; }
代码变更的主要是加了y的“速度”(位移)和边界进入,使得y方向不再是固定的一个数值,而是跟x方向一样实现了上下左右跳动。