c语言写飞机大战
时间: 2023-07-13 13:14:15 浏览: 98
飞机大战是一款经典的游戏,可以用C语言来实现。以下是一个简单的C语言代码示例,可以帮助你开始编写飞机大战游戏:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define MAP_WIDTH 80
#define MAP_HEIGHT 25
int playerX, playerY;
int bulletX, bulletY;
int enemyX, enemyY;
int score = 0;
void gotoxy(int x, int y) {
COORD pos = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void drawMap() {
int i, j;
for (i = 0; i < MAP_HEIGHT; i++) {
for (j = 0; j < MAP_WIDTH; j++) {
if (i == 0 || i == MAP_HEIGHT - 1) {
printf("-");
}
else if (j == 0 || j == MAP_WIDTH - 1) {
printf("|");
}
else {
printf(" ");
}
}
printf("\n");
}
}
void drawPlayer() {
gotoxy(playerX, playerY);
printf("^");
}
void drawBullet() {
gotoxy(bulletX, bulletY);
printf("|");
}
void drawEnemy() {
gotoxy(enemyX, enemyY);
printf("*");
}
void movePlayer(int dx, int dy) {
playerX += dx;
playerY += dy;
if (playerX <= 1) playerX = 1;
if (playerX >= MAP_WIDTH - 2) playerX = MAP_WIDTH - 2;
if (playerY <= 1) playerY = 1;
if (playerY >= MAP_HEIGHT - 2) playerY = MAP_HEIGHT - 2;
}
void moveBullet() {
bulletY--;
if (bulletY <= 1) {
bulletX = 0;
bulletY = 0;
}
}
void moveEnemy() {
enemyY++;
if (enemyY >= MAP_HEIGHT - 1) {
enemyX = rand() % (MAP_WIDTH - 2) + 1;
enemyY = 1;
}
}
void collisionDetection() {
if (bulletX == enemyX && bulletY == enemyY) {
score++;
bulletX = 0;
bulletY = 0;
enemyX = rand() % (MAP_WIDTH - 2) + 1;
enemyY = 1;
}
}
int main() {
playerX = MAP_WIDTH / 2;
playerY = MAP_HEIGHT - 2;
bulletX = 0;
bulletY = 0;
enemyX = rand() % (MAP_WIDTH - 2) + 1;
enemyY = 1;
drawMap();
while (1) {
drawPlayer();
if (_kbhit()) {
int c = _getch();
switch (c) {
case 'a':
movePlayer(-1, 0);
break;
case 'd':
movePlayer(1, 0);
break;
case 'w':
movePlayer(0, -1);
break;
case 's':
movePlayer(0, 1);
break;
case ' ':
bulletX = playerX;
bulletY = playerY - 1;
break;
}
}
if (bulletY > 0) {
drawBullet();
moveBullet();
collisionDetection();
}
drawEnemy();
moveEnemy();
gotoxy(MAP_WIDTH + 2, 2);
printf("Score: %d", score);
Sleep(50);
system("cls");
drawMap();
}
return 0;
}
```
这只是一个简单的实现,你可以根据自己的需求进行修改和扩展。
阅读全文