用c语言写一个消灭星星的游戏
时间: 2023-11-18 18:04:52 浏览: 136
好的,下面是一个简单的用 C 语言编写的消灭星星游戏:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
#define NUM_COLORS 5
// 定义星星的颜色
enum Color {
RED, GREEN, BLUE, YELLOW, PURPLE
};
// 星星的结构体
struct Star {
enum Color color;
int row;
int col;
int is_eliminated;
};
// 初始化游戏界面,将所有星星都设为随机颜色
void init_game(struct Star board[ROWS][COLS]) {
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
board[i][j].color = rand() % NUM_COLORS;
board[i][j].row = i;
board[i][j].col = j;
board[i][j].is_eliminated = 0;
}
}
}
// 打印游戏界面
void print_board(struct Star board[ROWS][COLS]) {
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (board[i][j].is_eliminated) {
printf(" ");
} else {
switch (board[i][j].color) {
case RED:
printf("R ");
break;
case GREEN:
printf("G ");
break;
case BLUE:
printf("B ");
break;
case YELLOW:
printf("Y ");
break;
case PURPLE:
printf("P ");
break;
}
}
}
printf("\n");
}
}
// 判断星星是否可以被消除,如果可以,返回 1,否则返回 0
int can_eliminate(struct Star board[ROWS][COLS], int row, int col) {
int i, j;
enum Color color = board[row][col].color;
int num_same_color = 0;
// 横向判断
for (i = 0; i < COLS; i++) {
if (board[row][i].is_eliminated || board[row][i].color != color) {
break;
}
num_same_color++;
}
if (num_same_color >= 3) {
return 1;
}
// 纵向判断
num_same_color = 0;
for (j = 0; j < ROWS; j++) {
if (board[j][col].is_eliminated || board[j][col].color != color) {
break;
}
num_same_color++;
}
if (num_same_color >= 3) {
return 1;
}
return 0;
}
// 消除星星
void eliminate_star(struct Star board[ROWS][COLS], int row, int col) {
board[row][col].is_eliminated = 1;
}
// 消除一列星星
void eliminate_column(struct Star board[ROWS][COLS], int col) {
int i;
for (i = 0; i < ROWS; i++) {
eliminate_star(board, i, col);
}
}
// 消除一行星星
void eliminate_row(struct Star board[ROWS][COLS], int row) {
int i;
for (i = 0; i < COLS; i++) {
eliminate_star(board, row, i);
}
}
// 将被消除的星星删除,并且将上面的星星下落
void drop_stars(struct Star board[ROWS][COLS]) {
int i, j;
for (i = ROWS - 1; i >= 0; i--) {
for (j = 0; j < COLS; j++) {
if (board[i][j].is_eliminated) {
int k;
for (k = i - 1; k >= 0; k--) {
if (!board[k][j].is_eliminated) {
board[i][j].color = board[k][j].color;
board[i][j].is_eliminated = board[k][j].is_eliminated;
board[k][j].is_eliminated = 1;
break;
}
}
}
}
}
}
// 消除所有可以被消除的星星
void eliminate_all_stars(struct Star board[ROWS][COLS]) {
int i, j;
int has_eliminated = 1;
while (has_eliminated) {
has_eliminated = 0;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (!board[i][j].is_eliminated && can_eliminate(board, i, j)) {
eliminate_star(board, i, j);
has_eliminated = 1;
}
}
}
drop_stars(board);
}
}
int main() {
struct Star board[ROWS][COLS];
srand(time(NULL));
init_game(board);
print_board(board);
eliminate_all_stars(board);
printf("All stars are eliminated!\n");
return 0;
}
```
这个游戏的规则是:将所有可以被消除的星星都消除掉,直到没有可以被消除的星星为止。如果一行或一列中有连续三个或以上的同色星星,则这些星星就可以被消除。每次消除完星星之后,上面的星星会下落到下面来,填补空缺。
阅读全文