c++贪吃蛇V1.0

哈哈哈,回归啦,也是成功的开学了好吧

贪吃蛇V1.0代码(如有bug可在评论区指出):wasd操控

cpp 复制代码
#include <iostream>
#include <vector>
#include <windows.h>
#include <conio.h>
#include <chrono>
#include <thread>

using namespace std;

const int WIDTH = 20;
const int HEIGHT = 20;
bool gameOver;
int x, y, fruitX, fruitY, score;
vector<pair<int, int>> snake;
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
Direction dir;

void Setup() {
	gameOver = false;
	dir = STOP;
	x = WIDTH / 2;
	y = HEIGHT / 2;
	fruitX = rand() % WIDTH;
	fruitY = rand() % HEIGHT;
	score = 0;
	snake.clear();
	snake.push_back({x, y});
}

void Draw() {
	system("cls");
	for (int i = 0; i < WIDTH + 2; i++)
		cout << "#";
	cout << endl;
	
	for (int i = 0; i < HEIGHT; i++) {
		for (int j = 0; j < WIDTH; j++) {
			if (j == 0) cout << "#";
			if (i == y && j == x) cout << "O";
			else if (i == fruitY && j == fruitX) cout << "F";
			else {
				bool isBody = false;
				for (auto segment : snake) {
					if (segment.first == j && segment.second == i) {
						cout << "o";
						isBody = true;
						break;
					}
				}
				if (!isBody) cout << " ";
			}
			if (j == WIDTH - 1) cout << "#";
		}
		cout << endl;
	}
	
	for (int i = 0; i < WIDTH + 2; i++)
		cout << "#";
	cout << endl;
	cout << "Score:" << score << endl;
}

void Input() {
	if (_kbhit()) {
		switch (_getch()) {
			case 'a': dir = LEFT; break;
			case 'd': dir = RIGHT; break;
			case 'w': dir = UP; break;
			case 's': dir = DOWN; break;
			case 'x': gameOver = true; break;
		}
	}
}

void Logic() {
	pair<int, int> prev = snake[0];
	pair<int, int> prev2;
	snake[0] = {x, y};
	for (size_t i = 1; i < snake.size(); i++) {
		prev2 = snake[i];
		snake[i] = prev;
		prev = prev2;
	}
	
	switch (dir) {
		case LEFT: x--; break;
		case RIGHT: x++; break;
		case UP: y--; break;
		case DOWN: y++; break;
	}
	
	if (x >= WIDTH || x < 0 || y >= HEIGHT || y < 0)
		gameOver = true;
	
	for (size_t i = 1; i < snake.size(); i++) {
		if (snake[i].first == x && snake[i].second == y)
			gameOver = true;
	}
	
	if (x == fruitX && y == fruitY) {
		score += 10;
		fruitX = rand() % WIDTH;
		fruitY = rand() % HEIGHT;
		snake.push_back({-1, -1});
	}
}

int main() {
	Setup();
	while (!gameOver) {
		Draw();
		Input();
		Logic();
		this_thread::sleep_for(chrono::milliseconds(100));
	}
	return 0;
}
相关推荐
CC.GG4 分钟前
【C++】AVL树
java·开发语言·c++
CoderCodingNo18 分钟前
【GESP】C++四级真题 luogu-B4416 [GESP202509 四级] 最长连续段
开发语言·c++·算法
a程序小傲21 分钟前
京东Java面试被问:Fork/Join框架的使用场景
java·开发语言·后端·postgresql·面试·职场和发展
⑩-25 分钟前
Java四种线程创建方式
java·开发语言
月光在发光26 分钟前
22_GDB调试记录(未完成)
java·开发语言
222you28 分钟前
SpringAOP的介绍和入门
java·开发语言·spring
程序员zgh29 分钟前
代码重构 —— 读后感
运维·c语言·开发语言·c++·重构
liulilittle36 分钟前
moodycamel::ConcurrentQueue 清空队列的方法论
开发语言·c++
shoubepatien38 分钟前
JAVA -- 09
java·开发语言
郑州光合科技余经理1 小时前
海外国际版同城服务系统开发:PHP技术栈
java·大数据·开发语言·前端·人工智能·架构·php