-
个人简介
贪吃蛇, 要用wsad操控,刚进去时是中文输入法,要切成英文输入法
#include <cstdlib> #include <iostream> #include <vector> #include <conio.h> #include <windows.h> #include <ctime> using namespace std;
const int WIDTH = 40; const int HEIGHT = 20; enum Direction { UP, DOWN, LEFT, RIGHT };
struct Point { int x, y; Point(int x = 0, int y = 0) : x(x), y(y) {} };
class SnakeGame { private: vector<Point> snake; Point food; Direction dir; bool gameOver; int score;
void generateFood() { srand(static_cast<unsigned>(time(0))); food.x = rand() % (WIDTH - 2) + 1; food.y = rand() % (HEIGHT - 2) + 1; // 修正1:使用传统循环替代范围循环 for (size_t i = 0; i < snake.size(); ++i) { if (snake[i].x == food.x && snake[i].y == food.y) { generateFood(); return; } } } void drawBoard() { system("cls"); for (int i = 0; i < WIDTH; i++) cout << "#"; cout << endl; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { if (j == 0 || j == WIDTH - 1) cout << "#"; else if (i == 0 || i == HEIGHT - 1) cout << "#"; else { bool isSnake = false; // 修正2:明确迭代类型 for (size_t k = 0; k < snake.size(); k++) { if (snake[k].x == j && snake[k].y == i) { // 修正3:蛇头检测逻辑 cout << (k == 0 ? 'O' : 'o'); isSnake = true; break; } } if (!isSnake) cout << (food.x == j && food.y == i ? 'F' : ' '); } } cout << endl; } cout << "Score: " << score << endl; } void checkCollision() { Point head = snake[0]; // 修正4:明确取首元素 if (head.x <= 0 || head.x >= WIDTH - 1 || head.y <= 0 || head.y >= HEIGHT - 1) gameOver = true; for (size_t i = 1; i < snake.size(); i++) { if (snake[i].x == head.x && snake[i].y == head.y) { gameOver = true; break; } } }
public: SnakeGame() : dir(RIGHT), gameOver(false), score(0) { snake.push_back(Point(WIDTH / 2, HEIGHT / 2)); snake.push_back(Point(WIDTH / 2 - 1, HEIGHT / 2)); snake.push_back(Point(WIDTH / 2 - 2, HEIGHT / 2)); generateFood(); }
void run() { while (!gameOver) { if (_kbhit()) { switch (_getch()) { case 'w': if (dir != DOWN) dir = UP; break; case 's': if (dir != UP) dir = DOWN; break; case 'a': if (dir != RIGHT) dir = LEFT; break; case 'd': if (dir != LEFT) dir = RIGHT; break; case 'x': gameOver = true; break; } } Point newHead = snake[0]; // 修正5:明确取首元素 switch (dir) { case UP: newHead.y--; break; case DOWN: newHead.y++; break; case LEFT: newHead.x--; break; case RIGHT: newHead.x++; break; } snake.insert(snake.begin(), newHead); if (newHead.x == food.x && newHead.y == food.y) { score += 10; generateFood(); } else { snake.pop_back(); } checkCollision(); drawBoard(); Sleep(100); } cout << "Game Over" << endl; }
};
int main() { SnakeGame game; game.run(); return 0; }
抖音
https://www.douyin.com/?recommend=1
不玩原神你活着干嘛
-
通过的题目
-
最近活动
题目标签
- 算法基础
- 3
- 入门
- 2
- 模拟算法
- 2
- 数学
- 2
- T3
- 1
- 二分
- 1
- 基本运算
- 1
- 普及
- 1
- 贪心
- 1
- 排序
- 1
- 字符串
- 1
- 一维数组
- 1
- 条件
- 1
- T1
- 1
- 二维数组
- 1
- 普及-
- 1