3) 当游戏开始之后,草坪中出现一颗豆和一条蛇,并且蛇不停地 移动,蛇移动的方向与蛇头的方向一致。 4) 当游戏暂停之后,蛇停止移动。
5) 当蛇移动时,玩家可以使用“↑”、“↓”、“←”和“→”四个方向
键改变蛇的移动方向。
6) 当蛇头与豆的位置重合时,豆被蛇吃掉,同时在草坪中再生成 一颗新的豆,蛇身增加一节。
7) 当蛇头碰到蛇身时,则咬断蛇身,后半部分的蛇身消失。 8) 当蛇头碰到草坪四周时,蛇立即毙命,游戏结束。
4.需求分析
根据功能描述可知,贪吃蛇游戏的系统结构图如下所示。 定义数据字典如下:
1) 草坪(Lawn):草坪是贪吃蛇游戏的场地。豆和蛇只能存 在于草坪范围之内。草坪具有大小和颜色等属性。
2) 蛇(Snake):在贪吃蛇游戏中,蛇由若干节组成,其中第 一节是蛇头,其余是蛇身。在游戏过程中,有且仅有一条 蛇,并且蛇在不停地移动。如果蛇吃了豆,则蛇生长一节。 如果蛇头碰到蛇身,则咬断蛇身,后半部分的蛇身消失。 如果蛇头离开草坪,则蛇死亡游戏结束。蛇具有长度、颜 色、运动方向、每一节的位置等属性。
3) 豆(Bean):在贪吃蛇游戏中,豆是蛇的食物。在游戏过 程中,有且仅有一颗豆。如果蛇吃了豆,则重新生成一颗 豆。豆具有位置、大小和颜色等属性。
5.设计说明
根据需求分析可知,Snake的每一节都有位置和大小等属性。而 Bean也具有这两个属性。抽象出二者的共同特征,抽象出一般类
Block,用于描述一个块。Block派生出Bean和SnakeBlock两个类,其
中SnakeBlock类用于描述蛇的一节。
为了使游戏的运行更易于控制,定义Game类用于启动、暂停和 继续游戏。
根据需求分析可知,Lawn仅包含大小和颜色两个属性。为了减 少类的数量,可将其大小和颜色等属性添加到Game类中。 综上所述,在贪吃蛇游戏中,有Block(块)、Bean(豆)、SankeBlock
(节)、Snake(蛇)、Game(游戏)和MainForm(用户接口)六个
类。贪吃蛇游戏的逻辑模型如下图所示。
6.源代码
using System;
using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text;
using System.Windows.Forms;
namespace HungrySnake {
publicpartialclassForm1 : Form {
privateGame game; public Form1() {
InitializeComponent();
game = newGame(lawn.Width, lawn.Height); }
privatevoid Form1_Load(object sender, EventArgs e) {
}
privatevoid timer1_Tick(object sender, EventArgs e) {
if (game.isSnakeAlive) { Graphics g;
g = lawn.CreateGraphics();
game.OnTime(g, lawn.BackColor, lawn.Width, lawn.Height); if (!game.isSnakeAlive) {
MessageBox.Show(\); } } }
privatevoid ToolStripMenuItemStart_Click(object sender, EventArgs e) { Graphics g;
g = lawn.CreateGraphics();
game.Begin(g, lawn.BackColor, lawn.Width, lawn.Height); timer1.Enabled = true;
ToolStripMenuItemPause.Enabled = true; ToolStripMenuItemContinue.Enabled = false; }
privatevoid ToolStripMenuItemPause_Click(object sender, EventArgs e) {
timer1.Enabled = false;
ToolStripMenuItemPause.Enabled = false; ToolStripMenuItemContinue.Enabled = true; }
privatevoid ToolStripMenuItemContinue_Click(object sender, EventArgs e) {
timer1.Enabled = true;
ToolStripMenuItemPause.Enabled = true;
ToolStripMenuItemContinue.Enabled = false; }
privatevoid Form1_KeyDown(object sender, KeyEventArgs e) {
if (game.snake.direction == Direction.Down || game.snake.direction == Direction.Up) {
switch (e.KeyCode) { caseKeys.Left:
game.snake.direction = Direction.Left; break;
caseKeys.Right:
game.snake.direction = Direction.Right; break;
} } else
{
switch (e.KeyCode) { caseKeys.Up:
game.snake.direction = Direction.Up; break;
caseKeys.Down:
game.snake.direction = Direction.Down; break;
} } } } }
7.测试报告
测试用例
1 Bean 的生成与显示
1) 测试程序是否能在游戏开始时,生成一颗豆。 2) 测试程序是否能在游戏运行中,正常显示一颗豆。