学习B站 https://www.bilibili.com/video/av34118200?p=17
#include<stdio.h> #include<stdlib.h> #include<conio.h> #include<windows.h> int high, width;//windows int ball_x, ball_y; // ball position int ball_vx, ball_vy; // ball speed int position_x, position_y; //center of board int radius; //radius of board int left, right; // boundary of board int ball_number; //score void HideCursor() { // if cursor CONSOLE_CURSOR_INFO cursor_info= {1,0}; //second value is 0 mean hide cursor SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info); } void gotoxy(int x, int y) { // move mouse to x,y position, similer clear screen HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); COORD pos; pos.X = x; pos.Y = y; SetConsoleCursorPosition(handle, pos); } void startup() { // init data high = 18; width = 25; ball_x = 1; ball_y = width / 2; ball_vx = 1; ball_vy = 1; position_x = high-1; position_y = width/2; radius = 5; left = position_y-radius; right = position_y+radius; ball_number = 0; HideCursor(); } void show() { // show windows gotoxy(0,0); //move mouse to 0,0 origin point, and redraw screen int i, j; // system("cls"); //clear screen for(i=0; i<=high; i++) { for(j=0; j<=width; j++) { if(i==ball_x && j==ball_y) printf("o"); //show ball * else if(i==high) printf("-"); else if(j==width) printf("|"); else if((i==position_x)&&(j>=left)&&(j<=right)) printf("*"); else printf(" "); //show nothing } printf(" "); } printf("ball_number:%d",ball_number); } void updateWithoutInput() { if(ball_x==position_x) { if((ball_y>=left)&&(ball_y<=right)) { ball_number++; ball_vy = -ball_vy; } else exit(0); } //update ball's position ball_x = ball_x + ball_vx; ball_y = ball_y + ball_vy; //meet boundard if(ball_x==0 || ball_x==high-1) ball_vx = -ball_vx; if(ball_y==0 || ball_y==width-1) ball_vy = -ball_vy; // Sleep(50); } void updateWithInput() { char input; if(kbhit()) { //runing while user push keyboard input = getch(); if(input == 'a') { position_y--; //move left left = position_y-radius; right = position_y+radius; } if(input == 'd') { position_y++; //move right left = position_y-radius; right = position_y+radius; } } } int main() { startup(); // init data while(1) { // game loop run show(); // show windows updateWithoutInput(); //update don't need user updateWithInput(); //update need user } return 0; }