#include #include//system here:#include <> #include using namespace std; #define MAX 100 char playArray[MAX][MAX];//the playing array char dispArray[MAX][MAX];//the displaying array void set_bomb(int s); void set_antibomb(int s); void initialize_grid(int s); void display_grid(char C[][MAX],int s); int error_check(int x,int y,int n); int check_position(int x,int y); int main() { int s, x, y, count = 0; cout << "Enter the grid size: "; cin >> s; initialize_grid(s); set_bomb(s); set_antibomb(s); display_grid(dispArray, s); while (1) { cout << "Enter the x position for tank: "; cin >> x; cout << "Enter the y position for tank: "; cin >> y; if (error_check(x, y, s) == 0) continue; int res = check_position(x, y); if (res == 1) { cout << "Game Over! You hit a bomb!" << endl; display_grid(playArray, s); break; } else if (res == 2) { cout << "You collected an anti-bomb!" << endl; playArray[x][y] = '#'; } else { playArray[x][y] = '#'; count++; if (count == 5) { cout << "Congratulations! You won!" << endl; break; } } dispArray[x][y] = '+'; display_grid(dispArray, s); } return 0; } void set_bomb(int s) { srand(time(0)); for (int i = 0; i < s; i++) { for (int j = 0; j < s; j++) { if (rand() % 10 <= 4) playArray[i][j] = '@'; else playArray[i][j] = '#'; } } } void set_antibomb(int s) { srand(time(0)); int x = rand() % s, y = rand() % s; while (playArray[x][y] == '@') { x = rand() % s; y = rand() % s; } playArray[x][y] = '&'; x = rand() % s; y = rand() % s; while (playArray[x][y] == '@' || playArray[x][y] == '&') { x = rand() % s; y = rand() % s; } playArray[x][y] = '&'; } void initialize_grid(int s) { for (int i = 0; i < s; i++) { for (int j = 0; j < s; j++) { dispArray[i][j] = '#'; } } } void display_grid(char C[][MAX],int s) { cout << " "; for (int i = 0; i < s; i++) { cout << i << " "; } cout << endl; for (int i = 0; i < s; i++) { cout << i << " "; for (int j = 0; j < s; j++) { cout << C[i][j] << " "; } cout << endl; } } int error_check(int x, int y, int n) { if (x < 0 || x >= n || y < 0 || y >= n) { cout << "Invalid position to move the tank" << endl; return 0; } if (dispArray[x][y] == '+') { cout << "You have already moved to this position" << endl; return 0; } return 1; } int check_position(int x, int y) { if (playArray[x][y] == '@') return 1; else if (playArray[x][y] == '&') return 2; else return 3; }

本作业类似于扫雷游戏the game of mines sweeper要求编程实现Tank游戏。游戏中坦克基于用户输入的位置在一个2D方格二维字符矩阵上开行。若该位置标有炸弹bomb那么游戏结束;若该位置未标有bomb则可将坦克开行到该位置;若用户能够连续5次开行坦克至无bomb位置则判定用户取得胜利。在二维方格on the 2D array的某些位置同样也埋有反炸弹anti-bomb坦克开行到标

原文地址: https://www.cveoy.top/t/topic/bZW8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录