用C语言写一个打地鼠
时间: 2023-12-29 19:12:54 浏览: 78
用C#编写打地鼠
4星 · 用户满意度95%
好的,以下是一个基于C语言的打地鼠游戏示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 3
#define COLS 3
#define HOLE_SYMBOL 'O'
#define MOLE_SYMBOL 'M'
#define BLANK_SYMBOL '-'
#define NUM_MOLES 3
#define TIME_LIMIT 30
// 初始化游戏板
void init_board(char board[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
board[i][j] = HOLE_SYMBOL;
}
}
}
// 创建地鼠
void create_moles(char board[ROWS][COLS], int num_moles) {
srand(time(NULL));
for (int i = 0; i < num_moles; i++) {
int row = rand() % ROWS;
int col = rand() % COLS;
while (board[row][col] == MOLE_SYMBOL) {
row = rand() % ROWS;
col = rand() % COLS;
}
board[row][col] = MOLE_SYMBOL;
}
}
// 打印游戏板
void print_board(char board[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
printf("\n");
}
int main() {
char board[ROWS][COLS];
int hits = 0;
int misses = 0;
int time_left = TIME_LIMIT;
// 初始化游戏板和地鼠
init_board(board);
create_moles(board, NUM_MOLES);
// 游戏循环
while (time_left > 0) {
print_board(board);
printf("Time left: %d\n", time_left);
printf("Hits: %d\n", hits);
printf("Misses: %d\n", misses);
int row, col;
printf("Row: ");
scanf("%d", &row);
printf("Col: ");
scanf("%d", &col);
if (row < 0 || row >= ROWS || col < 0 || col >= COLS) {
printf("Invalid input!\n");
continue;
}
if (board[row][col] == MOLE_SYMBOL) {
board[row][col] = BLANK_SYMBOL;
hits++;
printf("Hit!\n");
} else {
misses++;
printf("Miss!\n");
}
time_left--;
}
// 游戏结束
printf("Time is up!\n");
printf("Hits: %d\n", hits);
printf("Misses: %d\n", misses);
printf("Score: %d\n", hits - misses);
return 0;
}
```
该代码使用二维字符数组表示游戏板,随机创建若干个地鼠,然后在游戏循环中允许玩家输入行和列,判断玩家是否击中地鼠。最后计算得分并输出。
阅读全文