用c语言写一个吃豆人游戏
时间: 2024-05-05 19:20:03 浏览: 197
好的,下面是一个简单的用 C 语言实现的吃豆人游戏:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define DX 1
#define DY 1
#define BOARD_WIDTH 20
#define BOARD_HEIGHT 20
#define MAX_DOTS (BOARD_WIDTH-2)*(BOARD_HEIGHT-2)
int x, y;
int dots;
int exit_game;
int board[BOARD_WIDTH][BOARD_HEIGHT];
int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };
void init_board();
void init_game();
void print_board();
void move(int direction);
void update();
void game_over();
void set_cursor_visible(int visible);
int main()
{
init_game();
while (!exit_game) {
if (_kbhit()) {
int ch = _getch();
if (ch == 'q' || ch == 'Q') {
exit_game = 1;
} else if (ch == 'w' || ch == 'W') {
move(0);
} else if (ch == 'd' || ch == 'D') {
move(1);
} else if (ch == 's' || ch == 'S') {
move(2);
} else if (ch == 'a' || ch == 'A') {
move(3);
}
}
update();
Sleep(100);
}
game_over();
return 0;
}
void init_board()
{
int i, j;
for (i = 0; i < BOARD_WIDTH; i++) {
for (j = 0; j < BOARD_HEIGHT; j++) {
if (i == 0 || i == BOARD_WIDTH-1 ||
j == 0 || j == BOARD_HEIGHT-1) {
board[i][j] = -1;
} else {
board[i][j] = 0;
}
}
}
}
void init_game()
{
init_board();
x = BOARD_WIDTH/2;
y = BOARD_HEIGHT/2;
board[x][y] = 1;
dots = 0;
exit_game = 0;
set_cursor_visible(0);
print_board();
}
void print_board()
{
int i, j;
system("cls");
for (i = 0; i < BOARD_WIDTH; i++) {
for (j = 0; j < BOARD_HEIGHT; j++) {
if (board[i][j] == -1) {
printf("X");
} else if (board[i][j] == 0) {
printf(" ");
} else if (board[i][j] == 1) {
printf("O");
} else if (board[i][j] == 2) {
printf(".");
}
}
printf("\n");
}
printf("Dots: %d\n", dots);
}
void move(int direction)
{
int new_x = x + dx[direction];
int new_y = y + dy[direction];
if (board[new_x][new_y] == -1) {
exit_game = 1;
} else if (board[new_x][new_y] == 0) {
x = new_x;
y = new_y;
board[x][y] = 1;
} else if (board[new_x][new_y] == 2) {
x = new_x;
y = new_y;
board[x][y] = 1;
dots--;
}
}
void update()
{
int i, j;
for (i = 1; i < BOARD_WIDTH-1; i++) {
for (j = 1; j < BOARD_HEIGHT-1; j++) {
if (board[i][j] == 2) {
continue;
}
int k;
for (k = 0; k < 4; k++) {
int new_x = i + dx[k];
int new_y = j + dy[k];
if (board[new_x][new_y] == 2) {
board[i][j] = 2;
break;
}
}
}
}
if (dots == 0) {
exit_game = 1;
}
print_board();
}
void game_over()
{
set_cursor_visible(1);
printf("Game over!\n");
}
void set_cursor_visible(int visible)
{
HANDLE hConsoleOutput;
CONSOLE_CURSOR_INFO structCursorInfo;
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleCursorInfo(hConsoleOutput, &structCursorInfo);
structCursorInfo.bVisible = visible;
SetConsoleCursorInfo(hConsoleOutput, &structCursorInfo);
}
```
这个游戏使用了 Windows.h 头文件中的一些函数,因此只能在 Windows 操作系统上运行。在游戏中,玩家需要控制吃豆人在迷宫中移动,并尽可能地吃掉所有的豆子,避免撞到墙壁或敌人。玩家可以通过按下 W、A、S、D 键来控制吃豆人的方向,按下 Q 键可以退出游戏。
阅读全文