1. 模块化的飞机游戏

2020-11-05  本文已影响0人  卡尔书院

bug

有时子弹击中后没有效果

代码

#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#include<conio.h>

//全局变量
int height, width;//游戏窗口尺寸
int score;//得分
int miss;//没打中的
int positionX, positionY;//飞机位置
int bulletX, bulletY;//子弹的位置
int enemyX, enemyY;//敌机位置

/**
*   隐藏光标
*/
void hideCursor() {
    CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };//第二个值为o表示隐藏光标
    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}

/**
*   初始化游戏数据
*/
void init() {
    hideCursor();//隐藏光标
    height = 16;//游戏窗口尺寸
    width = 60;
    positionX = width / 2;//飞机位置
    positionY = height * 2 / 3;
    bulletY = -1;//子弹Y坐标
    enemyY = height + 1;//敌机Y坐标, 敌机Y坐标在height时处于被摧毁状态
}

/**
*   光标移动至(x, y)
*/
void cursorGoto(int x, int y) {
    HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos;
    pos.X = x;
    pos.Y = y;
    SetConsoleCursorPosition(handle, pos);
}
/**
*   显示游戏内容
*/
void show() {
    cursorGoto(0, 0);
    for (size_t i = 0; i < height; i++) {
        for (size_t j = 0; j < width; j++) {
            if (i == positionY && j == positionX) {
                printf("*");
            } else if (i == bulletY && j == bulletX) {
                printf("^");
            } else if (i == enemyY && j == enemyX) {
                printf("$");
            } else {
                printf(" ");
            }
        }
        printf("|\n");
    }
    for (size_t i = 0; i < width; i++) {
        putchar('-');
    }
    printf("|\n     得分:%d     错过:%d", score, miss);
}

/**
*   与输入有关的更新
*/
void updateWithInput() {
    char input;
    if (_kbhit()) {
        input = _getch();
        switch (input) {
        case 'a':positionX = positionX - 1 < 0? width-1: positionX-1;
            break;
        case 'd':positionX = positionX + 1 > width - 1 ? 0 : positionX + 1;
            break;
        case 'w':positionY = positionY - 1 < 0 ? 0 : positionY - 1;
            break;
        case 's':positionY = positionY + 1 > height-1 ? height - 1 : positionY + 1;
            break;
        case ' ':bulletX = positionX;
            bulletY = positionY - 1;
            break;
        default:
            break;
        }
    }
}

/**
*   与输入无关的更新
*/
void updateWithoutInput() {
    static int speed = 0;
    if (bulletY > -1 && bulletY <= positionY) {
        bulletY--;
    }
    if (enemyY < height) {
        if (speed > 5) {
            enemyY++;
            if (enemyY == height - 1) {
                miss++;
            }
            speed = 0;
        } else {
            speed++;
        }
    } else {
        enemyY = 0;
        enemyX = rand() % width;
    }
    if (enemyX == bulletX && enemyY == bulletY) {
        enemyY = height + 1;
        bulletY = height + 3;
        score++;
    }
}

int main() {
    init();//初始化游戏数据
    while (1) {
        show();//显示
        updateWithoutInput();//与输入无关的更新
        updateWithInput();//与输入有关的更新
    }
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读