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("|"); else printf(" "); } 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++; } }
#include "game.h" void HideCursor() {
CONSOLE_CURSOR_INFO cursor_info = {
1,0 }; SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info); } void gotoxy(int x, int y) {
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); COORD pos; pos.X = x; pos.Y = y; SetConsoleCursorPosition(handle, pos); }