private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch(e.KeyCode)
{
case Keys.Up:
if(Dir != Direction.Down) //不能向当前方向的反方向移动
tmpDir = Direction.Up; ;
.......
case Keys.Space:
if(state == GameState.Start)
{
timer1.Enabled = !timer1.Enabled;
Invalidate();
}
break;
case Keys.S:
if (state == GameState.Start)
{
timer1.Enabled = false;
, , MessageBoxButtons.OKCancel) == DialogResult.Cancel)
{
timer1.Enabled = true;
break;
}
}
StartGame();
break;
}
}
}
蛇的移动,食物,游戏是否结束判断
switch (Dir) //使用策略模式来替代switch { case Direction.Up: { if (head.Y <= 0) //撞墙 { GameOver(); } foreach (var po in snake) { if (po.Y + 1 == head.Y && po.X == head.X) //吃掉自己 { GameOver(); break; } } if (state == GameState.Over) break; if (food.Y + 1 == head.Y && food.X == head.X) //吃掉食物 { snake.Enqueue(food); head = food; GenerateFood(); } { snake.Dequeue(); head = new Pos(head.X, head.Y - 1); snake.Enqueue(head); } } break; case Direction.Down:
整个程序的结构到此介绍完毕,总的来说是一个比较完整的小游戏了,当然有很多地方可以优化,但个人也就没那个兴趣和精力了(笑)
下载地址:GreedySnake