极简版本:贪吃蛇

#include <iostream>
#include <windows.h>
void main()
{
	const int w = 20; 
	const int h = 20;
	const int s = w * h;
	char map[s] = {	};
	int snake[s];
	int len = 2;
	snake[0] = 0;
	snake[1] = 1;
	int food;
	int dir = 3;
	for (int i = 0;i < 5; ++i)
		map[rand() % (s-1)+1] = 1;
	do{food = rand() % s;}while (map[food] == 1);
	while (1)
	{
		system("cls");
		int temp[s] = {};
		for (int i = 0; i < s; ++i)
			temp[i] = map[i];
		temp[food] = 2;
		for (int i = 0;i < len-1; ++i)
			temp[ snake[i] ] = 3;
		temp[ snake[len-1] ] = 4;
		for (int i = 0;i < s; ++i)
		{
			switch(temp[i])
			{
			case 0:std::cout<<"□";break;
			case 1:std::cout<<"■";break;
			case 2:std::cout<<"★";break;
			case 3:std::cout<<"◎";break;
			case 4:std::cout<<"●";break;
			}
			if (i % w == w-1)
				std::cout<<std::endl;
		}
		snake[len-1];
		int xx[] = {0,0,-1,1};
		int yy[] = {-1,1,0,0};
		int nextx = snake[len-1] % w + xx[dir];
		if (nextx < 0) 
			nextx = w-1;
		else if (nextx > w-1)
			nextx = 0;
		int nexty = snake[len-1] / w + yy[dir];
		if (nexty < 0)
			nexty = h-1;
		else if (nexty > h-1)
			nexty = 0;
		int next = nextx + nexty * w;
		bool die = false;
		if (map[next] == 1)
			die = true;
		for (int i = 0;i < len-1; ++i)
			if (snake[i] == next)
			{
				die = true;
				break;
			}
		if (die)
		{
			std::cout<<"死亡!";
			system("pause");
			return;
		}
		if (next == food)
		{
			snake[len] = next;
			len++;
			do{
				food = rand() % s;
			}while (map[food] == 1);
		}
		for (int i = 1; i < len; ++i)
			snake[i-1] = snake[i];
		snake[len-1] = next;

		if (GetAsyncKeyState('W') & 1)
		{
			if (dir != 1)
				dir = 0;
		}
		if (GetAsyncKeyState('S') & 1)
		{
			if (dir != 0)
				dir = 1;
		}
		if (GetAsyncKeyState('A') & 1)
		{
			if (dir != 3)
				dir = 2;
		}
		if (GetAsyncKeyState('D') & 1)
		{
			if (dir != 2)
				dir = 3;
		}
		Sleep(100);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值