这篇文章主要为大家展示了C#如何实现贪吃蛇游戏,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。

贪吃蛇分析
游戏规则:
1、蛇起始长度5,每吃一个食物增加1,大15过关
2、蛇用蓝色表示,食物用绿色,障碍物用黑色
3、当蛇碰到自己、墙壁、障碍物则游戏失败
4、方向键控制蛇的移动方向,蛇不可反方向移动,如正在向上移动,不能马上向下,只能向左、右、上运动
5、每过关一次速度提升一次
大概思路:
1、地图用网格的形式表示,蛇由方格组成,保存在list中
2、1中提到了方格,方格保存的内容有,颜色,坐标,是否可以通过,是否是食物
3、向前移动一次,将前面方格添加进蛇列表中,将列表最后一个移除,若为前方格子为食物,则不移除最后一个
4、使用while死循环来做整个移动
5、空格键为加速键,通过修改while循环sleep时间来实现加速
包括了3个类一个主窗体,分别是Node(用来表示方格)、Map(用来表示地图)、Serpent(用来表示蛇),另外一个主窗体。下面依次把代码贴上,基本上每个方法都有注释
代码1:
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace EngorgeSerpent
{
///
/// 节点
///
class Node
{
#region 字段
private int x;
private int y;
private int width = 10;
private bool isFood = false;
private bool isPass = true;//是否可通过
private Color bgColor = Color.FromArgb(224, 224, 224);
private Color foodColor = Color.Green;
private Color hinderColor = Color.Black;
private Color thisColor;
private Color serpentColor = Color.Chocolate;
#endregion
///
/// 设置食物参数
///
///
public void SetFood(bool _isFood)
{
IsFood = _isFood;
if (_isFood)
{
ThisColor = FoodColor;
}
else
{
ThisColor = BgColor;
}
}
///
/// 设置障碍物参数
///
/// 是否为障碍物
public void SetHinder(bool _isHinder)
{
IsPass =! _isHinder;
if (_isHinder)
{
ThisColor = HinderColor;
}
else
{
ThisColor = BgColor;
}
}
///
/// 设置蛇颜色
///
///
public void SetSerpent(bool _isSerpent)
{
IsPass = !_isSerpent;
if (_isSerpent)
{
ThisColor = SerpentColor;
}
else
{
ThisColor = BgColor;
}
}
#region 构造函数
public Node()
{
thisColor = bgColor;
}
///
/// 有参构造方法
///
/// 相对x坐标
/// 相对y坐标
/// 边长
/// 是否是食物
/// 是否可通过
public Node(int _x, int _y, int _width, bool _isFood, bool _isPass)
{
thisColor = bgColor;
X = _x;
Y = _y;
Width = _width;
IsFood = _isFood;
IsPass = _isPass;
}
///
/// 有参构造方法
///
/// 相对x坐标
/// 相对y坐标
/// 边长
public Node(int _x, int _y, int _width)
{
X = _x;
Y = _y;
Width = _width;
}
///
/// 有参构造方法
///
/// 相对x坐标
/// 相对y坐标
public Node(int _x, int _y)
{
X = _x;
Y = _y;
}
#endregion
#region 属性
///
/// 蛇颜色
///
public Color SerpentColor
{
get { return serpentColor; }
}
///
/// 背景色
///
public Color BgColor
{
get { return bgColor; }
}
///
/// 食物颜色
///
public Color FoodColor
{
get { return foodColor; }
}
///
/// 障碍物颜色
///
public Color HinderColor
{
get { return hinderColor; }
}
///
/// 当前颜色
///
public Color ThisColor
{
get { return thisColor; }
set { thisColor = value; }
}
///
/// 获取或设置相对横坐标
///
public int X
{
get { return x; }
set { x = value; }
}
///
/// 获取或设置相对纵坐标
///
public int Y
{
get { return y; }
set { y = value; }
}
///
/// 获取或设置节点边长
///
public int Width
{
get { return width; }
set { width = value; }
}
///
/// 获取或设置是否为食物
///
public bool IsFood
{
get { return isFood; }
set { isFood = value; }
}
///
/// 获取或设置是否可以通过
///
public bool IsPass
{
get { return isPass; }
set { isPass = value; }
}
#endregion
}
}另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。