弹砖块游戏
c語言實現彈磚塊游戲
利用板子使球不落到地上并且砸到磚塊上
windows平臺實現
代碼如下:
game.h:
#pragma once #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <conio.h>void HideCursor(); void gotoxy(int x, int y); void DataInit(); void Show(); void UpdateWithoutInput(); void UpdateWithInput();test.cpp:
#include "game.h"int high; int width; int ball_v_x; int ball_v_y; int ball_x; int ball_y; int bricks_x; int bricks_y; int board_x; int board_y; int board_r; int score;int main() {DataInit(); //數據初始化while (1){Show(); //顯示畫面UpdateWithoutInput(); //與用戶無關的數據更新UpdateWithInput(); //與用戶有關的數據更新}return 0; }game.cpp:
#include "game.h"extern int high; extern int width; extern int ball_v_x; extern int ball_v_y; extern int ball_x; extern int ball_y; extern int bricks_x; extern int bricks_y; extern int board_x; extern int board_y; extern int board_r; extern int score;void DataInit() {high = 20;width = 30;ball_x = 1;ball_y = width / 2;ball_v_x = 1;ball_v_y = 1;board_x = high - 1;board_y = width / 2;board_r = 5;bricks_x = 0;bricks_y = width / 2;score = 0;HideCursor(); }void Show() {gotoxy(0, 0);int i, j;for (i = 0; i <= high; i++){for (j = 0; j <= width; j++){if (j >= board_y - board_r && j <= board_y + board_r && i == board_x)printf("#");else if (i == bricks_x && j == bricks_y)printf("$");else if (i == ball_x && j == ball_y)printf("o");else if (i == high)printf("_");else if (j == width)printf("|");elseprintf(" ");}printf("\n");}printf("SCORE: %d\n", score);Sleep(100); }void UpdateWithoutInput() {if (ball_x <= 0 || ((ball_x == board_x - 1) && (ball_y >= board_y - board_r && ball_y <= board_y + board_r)))ball_v_x *= -1;if (ball_x > high){printf("wasted!!!\n");exit(-1);}ball_x += ball_v_x;if (ball_y >= width || ball_y <= 0)ball_v_y *= -1;ball_y += ball_v_y;if (ball_x == bricks_x && ball_y == bricks_y){score++;bricks_x = 0;bricks_y = rand();} }void UpdateWithInput() {char input;if (_kbhit()){input = _getch();if (input == 'a' && board_y > 1)board_y--;if (input == 'd' && board_y < width - 1)board_y++;} }fix.cpp:
用于修復閃屏的問題,goto函數可以用cls替代,但是會閃屏,本質上都是用來清理屏幕的
總結
- 上一篇: GeForce Desktop Prod
- 下一篇: 日文输入方法