弹力球c语言代码运行,弹力球游戏c语言代码
时间: 2023-09-27 13:06:42 浏览: 343
以下是一个简单的弹力球游戏的C语言代码,你可以在C语言编译器上运行它:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
#define PADDLE_WIDTH 10
#define PADDLE_HEIGHT 1
#define BALL_SYMBOL 'O'
#define PADDLE_SYMBOL '-'
#define BRICK_SYMBOL '#'
#define WALL_SYMBOL '|'
#define GAME_WIDTH 60
#define GAME_HEIGHT 30
#define MAX_BRICKS 100
#define MAX_LEVELS 3
int paddle_position = GAME_WIDTH / 2 - PADDLE_WIDTH / 2;
int ball_x = GAME_WIDTH / 2;
int ball_y = GAME_HEIGHT - 2;
int ball_speed_x = 1;
int ball_speed_y = -1;
int bricks[MAX_BRICKS][2];
int num_bricks = 0;
int level = 1;
int score = 0;
void gotoxy(int x, int y) {
COORD pos = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void clear_screen() {
system("cls");
}
void draw_paddle() {
int i, j;
for (i = 0; i < PADDLE_HEIGHT; i++) {
for (j = 0; j < PADDLE_WIDTH; j++) {
gotoxy(paddle_position + j, GAME_HEIGHT - 1 - i);
printf("%c", PADDLE_SYMBOL);
}
}
}
void draw_ball() {
gotoxy(ball_x, ball_y);
printf("%c", BALL_SYMBOL);
}
void draw_wall() {
int i, j;
for (i = 0; i < GAME_HEIGHT; i++) {
gotoxy(0, i);
printf("%c", WALL_SYMBOL);
gotoxy(GAME_WIDTH - 1, i);
printf("%c", WALL_SYMBOL);
}
for (j = 0; j < GAME_WIDTH; j++) {
gotoxy(j, 0);
printf("%c", WALL_SYMBOL);
}
}
void draw_bricks() {
int i;
for (i = 0; i < num_bricks; i++) {
gotoxy(bricks[i][0], bricks[i][1]);
printf("%c", BRICK_SYMBOL);
}
}
void move_paddle_left() {
if (paddle_position > 0) {
paddle_position--;
}
}
void move_paddle_right() {
if (paddle_position < GAME_WIDTH - PADDLE_WIDTH) {
paddle_position++;
}
}
void move_ball() {
ball_x += ball_speed_x;
ball_y += ball_speed_y;
if (ball_x == 0 || ball_x == GAME_WIDTH - 1) {
ball_speed_x = -ball_speed_x;
}
if (ball_y == 0) {
ball_speed_y = -ball_speed_y;
}
if (ball_y == GAME_HEIGHT - 1) {
printf("Game over!\n");
exit(0);
}
if (ball_y == GAME_HEIGHT - 2 && ball_x >= paddle_position && ball_x < paddle_position + PADDLE_WIDTH) {
ball_speed_y = -ball_speed_y;
score++;
}
int i;
for (i = 0; i < num_bricks; i++) {
if (ball_x == bricks[i][0] && ball_y == bricks[i][1]) {
ball_speed_y = -ball_speed_y;
score += 10;
bricks[i][0] = -1;
bricks[i][1] = -1;
}
}
}
void init_bricks() {
int i;
for (i = 0; i < GAME_WIDTH; i += 2) {
bricks[num_bricks][0] = i;
bricks[num_bricks][1] = 3;
num_bricks++;
}
}
void next_level() {
clear_screen();
ball_x = GAME_WIDTH / 2;
ball_y = GAME_HEIGHT - 2;
ball_speed_x = 1;
ball_speed_y = -1;
paddle_position = GAME_WIDTH / 2 - PADDLE_WIDTH / 2;
num_bricks = 0;
level++;
init_bricks();
}
int main() {
srand(time(NULL));
init_bricks();
while (1) {
clear_screen();
draw_wall();
draw_bricks();
draw_paddle();
draw_ball();
move_ball();
if (score == num_bricks * 10) {
if (level == MAX_LEVELS) {
printf("You won!\n");
exit(0);
}
next_level();
}
if (_kbhit()) {
char c = _getch();
if (c == 'a') {
move_paddle_left();
}
if (c == 'd') {
move_paddle_right();
}
}
Sleep(50);
}
return 0;
}
```
注意:此代码仅供参考。
阅读全文