贪吃蛇 – 100行版本

简介

高一时受学校图形计算器上原装贪吃蛇程序启发而写的C++小游戏

高三时整理压缩至100行

代码

//By Eric Jin 2018     编译后切换至英文  a左d右w上s下       使用了Sleep() _kbhit() _getch() system("cls")等
#include <iostream> 
#include <sstream>
#include <string>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <windows.h>
std::string o(int i)//4左6右8上2下
{
	if (i == 0) return "  ";
	else if (i == 1) return "# ";
	else if (i == 3) return "$ ";
	else return "* ";
}
void drawmap(int h, int l, int maptest[100][100])//绘图
{
	std::stringstream ss;
	for (int i = 1; i <= h; i++)
	{
		for (int j = 1; j <= l; j++) ss << o(maptest[i][j]);
		ss << std::endl;
	}
	std::string out = ss.str();
	system("cls");
	std::cout << out;
}
void findfood(int maptest[100][100], int& foodx, int& foody, int h, int l)//出食物
{
	for (;;)
	{
		srand((int)time(0));
		foodx = rand() % h + 1, foody = rand() % l + 1;
		if (maptest[foodx][foody] == 0) break;
	}
}
int gamein()
{
	int speed, h = 20, l = 30, tail = 6, maptest[100][100], x = h / 2, y = l / 2, tx = h / 2, ty = l / 2 - tail, foodx, foody, dir = 6, tdir = 6, food = 0;
	bool skip = 0;
	std::cout << "Speed (100-slow 50-medium 10-fast):" << std::endl;
	std::cin >> speed;
	Sleep(500);
	system("cls");
	for (int i = 1; i <= h; i++)//设置边界
	{
		for (int j = 1; j <= l; j++)
		{
			maptest[i][j] = 0;
			if (i == 1 || i == h) maptest[i][j] = 1;
		}
		maptest[i][1] = 1, maptest[i][l] = 1;
	}
	for (int i = ty + 1; i <= y; i++) maptest[x][i] = 6;
	findfood(maptest, foodx, foody, h, l);
	maptest[foodx][foody] = 3;
	drawmap(h, l, maptest);
	for (;;)
	{
		maptest[x][y] = dir;
		x = (dir == 2) ? (x + 1) : (dir == 8 ? x - 1 : x), y = (dir == 6) ? (y + 1) : (dir == 4 ? y - 1 : y);
		if (maptest[x][y] == 0 || maptest[x][y] == 3) maptest[x][y] = dir;
		else
		{
			std::cout << std::endl << "You died." << std::endl << "Score: " << food << std::endl << "Speed: " << speed << std::endl;
			std::cout << "0:exit" << std::endl;
			std::cout << "1:new game" << std::endl;
			char in1 = _getch();
			std::cout << std::endl;
			if (in1 == '0') return 0;
			else return gamein();
		}
		if (skip == 0)
			tx = (tdir == 2) ? (tx + 1) : (tdir == 8 ? tx - 1 : tx), ty = (tdir == 6) ? (ty + 1) : (tdir == 4 ? ty - 1 : ty), tdir = maptest[tx][ty];
		else skip = 0;
		maptest[tx][ty] = 0;
		drawmap(h, l, maptest);
		std::cout << "Score: " << food << std::endl << "Speed: " << speed << std::endl;
		Sleep(speed);
		if (_kbhit() != 0)
		{
			int in = _getch();
			if (in == 97 && dir != 4 && dir != 6) dir = 4;
			if (in == 115 && dir != 2 && dir != 8) dir = 2;
			if (in == 119 && dir != 2 && dir != 8) dir = 8;
			if (in == 100 && dir != 4 && dir != 6) dir = 6;
		}
		if (x == foodx && y == foody)
		{
			food++;
			findfood(maptest, foodx, foody, h, l);
			maptest[foodx][foody] = 3;
			skip = 1;
		}
	}
}
int main()
{
	return gamein();
}

图片

发表评论