c语言植物大战僵尸代码
时间: 2023-09-24 10:13:17 浏览: 249
由于植物大战僵尸是一个商业游戏,它的源代码并不是公开的。但是,你可以尝试自己开发一个类似的游戏,以下是一个简单的 C 语言控制台版本植物大战僵尸的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 5
#define COL 8
#define MAX_SUN 50
#define GRASS ' '
#define ZOMBIE 'Z'
#define PLANT 'P'
#define BULLET '*'
#define SUN '$'
int sun = 0;
void init(char arr[ROW][COL]) {
int i, j;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
arr[i][j] = GRASS;
}
}
}
void print(char arr[ROW][COL]) {
int i, j;
printf("Sun: %d\n", sun);
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
printf("%c ", arr[i][j]);
}
printf("\n");
}
}
void move_zombie(char arr[ROW][COL]) {
int i, j;
for (j = COL - 1; j >= 0; j--) {
if (arr[0][j] == ZOMBIE) {
printf("Game Over!\n");
exit(0);
}
for (i = 0; i < ROW; i++) {
if (arr[i][j] == ZOMBIE) {
arr[i][j] = GRASS;
if (j == 0) {
printf("Game Over!\n");
exit(0);
} else {
arr[i][j - 1] = ZOMBIE;
}
}
}
}
}
void move_bullet(char arr[ROW][COL]) {
int i, j;
for (j = 0; j < COL; j++) {
for (i = 0; i < ROW; i++) {
if (arr[i][j] == BULLET) {
arr[i][j] = GRASS;
if (j == COL - 1) {
continue;
}
if (arr[i][j + 1] == ZOMBIE) {
arr[i][j + 1] = GRASS;
} else {
arr[i][j + 1] = BULLET;
}
}
}
}
}
void generate_sun(char arr[ROW][COL]) {
int i;
for (i = 0; i < ROW; i++) {
if (rand() % 10 == 0) {
int j = rand() % COL;
if (arr[i][j] == GRASS) {
arr[i][j] = SUN;
}
}
}
}
void generate_zombie(char arr[ROW][COL]) {
int i;
for (i = 0; i < ROW; i++) {
if (rand() % 10 == 0) {
if (arr[i][COL - 1] == GRASS) {
arr[i][COL - 1] = ZOMBIE;
}
}
}
}
void generate_bullet(char arr[ROW][COL], int row, int col) {
if (arr[row][col + 1] == ZOMBIE) {
arr[row][col + 1] = GRASS;
} else {
arr[row][col + 1] = BULLET;
}
}
void plant_sunflower(char arr[ROW][COL], int row, int col) {
if (sun >= 25 && arr[row][col] == GRASS) {
sun -= 25;
arr[row][col] = PLANT;
}
}
void plant_peashooter(char arr[ROW][COL], int row, int col) {
if (sun >= 50 && arr[row][col] == GRASS) {
sun -= 50;
arr[row][col] = PLANT;
}
}
void process_input(char arr[ROW][COL]) {
int row, col;
char input[10];
printf("Enter command: ");
scanf("%s", input);
if (strcmp(input, "sunflower") == 0) {
printf("Enter row and column: ");
scanf("%d %d", &row, &col);
plant_sunflower(arr, row, col);
} else if (strcmp(input, "peashooter") == 0) {
printf("Enter row and column: ");
scanf("%d %d", &row, &col);
plant_peashooter(arr, row, col);
} else if (strcmp(input, "quit") == 0) {
exit(0);
}
}
int main() {
char arr[ROW][COL];
init(arr);
srand(time(NULL));
while (1) {
system("clear");
print(arr);
move_zombie(arr);
move_bullet(arr);
generate_sun(arr);
generate_zombie(arr);
process_input(arr);
usleep(500000);
}
return 0;
}
```
该代码实现了一个简单的植物大战僵尸游戏,其中包括了植物和僵尸的移动、子弹的发射和消失、阳光的生成以及植物的种植等功能。你可以根据自己的需求进行修改和扩展。