winform窗体-贪食蛇
1、.cs文件
private void Form1_Load(object sender, EventArgs e)
{
snacks = new Snack();
this.Controls.AddRange(snacks.snack.ToArray());
InitFruit();
}
private void timer1_Tick(object sender, EventArgs e)
{
UpdateGame();
this.DoubleBuffered = true; //辅佐缓冲区
}
private void DrawGame()
{
this.Controls.Clear();
this.Controls.AddRange(snacks.snack.ToArray());
this.Controls.Add(food);
}
/// <summary>
/// 更新蛇的坐标
/// </summary>
private void UpdateGame() {
for (int i =snacks.snack.Count-1; i >0 ; i--)
{
int bodyX = snacks.snack[i].Location.X;
int bodyY = snacks.snack[i].Location.Y;
bodyX = snacks.snack[i - 1].Location.X;
bodyY = snacks.snack[i - 1].Location.Y;
snacks.snack[i].Location = new Point(bodyX,bodyY);
}
//头部单独走
int headX = snacks.snack[0].Location.X;
int headY = snacks.snack[0].Location.Y;
switch (snacks.Direction)
{
case 1:
headY -= 20;
break;
case 2:
headY += 20;
break;
case 3:
headX -= 20;
break;
case 4:
headX += 20;
break;
default:
break;
}
snacks.snack[0].Location = new Point(headX, headY);
if (snacks.snack[0].Location == food.Location)
{
snacks.snack.Add(food);
//重新产生食物
InitFruit();
}
else if (headX<0||headX>330 ||headY>340||headY<0)
{
timer1.Stop();
MessageBox.Show("游戏结束");
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up:
snacks.Direction = 1;
break;
case Keys.Down:
snacks.Direction = 2;
break;
case Keys.Left:
snacks.Direction = 3;
break;
case Keys.Right:
snacks.Direction = 4;
break;
default:
break;
}
}
Button food;
Random r = new Random();
/// <summary>
/// 食物
/// </summary>
private void InitFruit()
{
int randomX = r.Next(0, this.ClientSize.Width / 20) * 20;
int randomY = r.Next(0, this.ClientSize.Height / 20) * 20;
food = new Button();
food.Size = new Size(20, 20);
food.BackColor = Color.Gray;
food.Location = new Point(randomX, randomY);
food.Enabled = false;
this.Controls.Add(food);
}
2、Snack.cs
public List<Button>snack;
public Snack()
{
this.SnackLength = SnackLength;
this.Direction = 1;//默认向上
this.snack= new List<Button>();//定义一个蛇的泛型集合
Button head = new Button();//画个蛇头
head.Size = new Size(20, 20);//大小
head.BackColor = Color.Black;//颜色
head.Location = new Point(100, 100);//蛇头的初始位置
head.Enabled = false;//禁用按钮
snack.Add(head);//添加一个蛇头到蛇的泛型集合里
//蛇身
for (int i = 0; i < 3; i++)
{
Button body = new Button();//画个蛇头
body.Size = new Size(20, 20);//大小
body.BackColor = Color.Gray;//颜色
body.Location = new Point(100, 100+i*20);//蛇块的初始位置
body.Enabled = false;//禁用按钮
snack.Add(body);//添加一个蛇块到蛇的泛型集合里
}
}
//蛇的长度
private int snackLength;
//方向
private int direction;
//封装成属性
public int SnackLength { get => snackLength; set => snackLength = value; }
public int Direction { get => direction; set => direction = value; }
3、效果图