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;
}
相关推荐
艾莉丝努力练剑18 小时前
【C++:C++11】C++11新特性深度解析:从可变参数模板到Lambda表达式
c++·stl·c++11·lambda·可变模版参数
同学小张20 小时前
【端侧AI 与 C++】1. llama.cpp源码编译与本地运行
开发语言·c++·aigc·llama·agi·ai-native
踢球的打工仔21 小时前
PHP面向对象(7)
android·开发语言·php
汤姆yu1 天前
基于python的外卖配送及数据分析系统
开发语言·python·外卖分析
Yue丶越1 天前
【C语言】字符函数和字符串函数
c语言·开发语言·算法
翔云 OCR API1 天前
人脸识别API开发者对接代码示例
开发语言·人工智能·python·计算机视觉·ocr
V***u4531 天前
MS SQL Server partition by 函数实战二 编排考场人员
java·服务器·开发语言
这是程序猿1 天前
基于java的ssm框架旅游在线平台
java·开发语言·spring boot·spring·旅游·旅游在线平台
芳草萋萋鹦鹉洲哦1 天前
【elemen/js】阻塞UI线程导致的开关卡顿如何优化
开发语言·javascript·ui
爱学习的小邓同学1 天前
C++ --- 多态
开发语言·c++