c#写的贪吃蛇小游戏

80酷酷网    80kuku.com

  

下面是游戏的源代码。有两个文件:Main.cs 和 Snake.cs

//
// Main.cs Begin
//
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;

namespace GreedySnake
{
 ///
 /// formMain 的摘要说明。
 ///
 public class formMain : System.Windows.Forms.Form
 {
  ///
  /// 必需的设计器变量。
  ///
  private System.ComponentModel.Container components = null;
  private System.Windows.Forms.MenuItem menuGame;
  private System.Windows.Forms.MenuItem menuGameBegin;
  private System.Windows.Forms.MenuItem menuGameEnd;
  private System.Windows.Forms.MainMenu menuMain;
  private System.Windows.Forms.MenuItem menuGameRebegin;
  private System.Windows.Forms.MenuItem menuOption;
  private System.Windows.Forms.MenuItem menuOptionTopMost;

  private System.Windows.Forms.MenuItem menuOptionGameDifficulty;
  private System.Windows.Forms.MenuItem menuOptionSplit;
  private System.Windows.Forms.MenuItem menuOptionGameDifficultyEasy;
  private System.Windows.Forms.MenuItem menuOptionGameDifficultyCommon;
  private System.Windows.Forms.MenuItem menuOptionGameDifficultyDifficult;

  private System.Windows.Forms.Panel panelGameRegion;
  private System.Windows.Forms.Panel panel1;
  private System.Windows.Forms.Label labelGameDifficulty;
  private System.Windows.Forms.Label labelGameCurrentDifficulty;
  private System.Windows.Forms.Label labelGameIntroduce;
  private System.Windows.Forms.Label labelUp;
  private System.Windows.Forms.Label labelDown;
  private System.Windows.Forms.Label labelLeft;
  private System.Windows.Forms.Label labelRight;
  private System.Windows.Forms.Label labelStatistic;
  private System.Windows.Forms.Label labelInitCount;
  private System.Windows.Forms.Label labelCurrentCount;
  private System.Windows.Forms.Label labelScore;
 
  private System.Windows.Forms.Label labelEatGreenCount;

  private const int ciSpeed = 80; // 游戏速度(默认难度:一般)
  private int iSpeed = ciSpeed;  // 游戏速度

  private const int iCount = 18;  // 蛇长
  private const int iRadius = 5;  // 蛇骨接的半径
  private const int iStep = 2 * iRadius;  // 两个相邻的蛇骨中心相差的距离

  private const int iMaxCount = 5;  // 最多能剩下的食物总数

  private Snake snake;
  private SnakeFood snakeFood;

  public formMain()
  {
   //
   // Windows 窗体设计器支持所必需的
   //
   InitializeComponent();

   //
   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
   //
  }

  #region 清理正在使用的资源
  ///
  /// 清理所有正在使用的资源。
  ///
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }
  #endregion

  #region Windows 窗体设计器生成的代码
  ///
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  ///
  private void InitializeComponent()
  {
   this.menuMain = new System.Windows.Forms.MainMenu();
   this.menuGame = new System.Windows.Forms.MenuItem();
   this.menuGameBegin = new System.Windows.Forms.MenuItem();
   this.menuGameRebegin = new System.Windows.Forms.MenuItem();
   this.menuGameEnd = new System.Windows.Forms.MenuItem();
   this.menuOption = new System.Windows.Forms.MenuItem();
   this.menuOptionGameDifficulty = new System.Windows.Forms.MenuItem();
   this.menuOptionGameDifficultyEasy = new System.Windows.Forms.MenuItem();
   this.menuOptionGameDifficultyCommon = new System.Windows.Forms.MenuItem();
   this.menuOptionGameDifficultyDifficult = new System.Windows.Forms.MenuItem();
   this.menuOptionSplit = new System.Windows.Forms.MenuItem();
   this.menuOptionTopMost = new System.Windows.Forms.MenuItem();
   this.panelGameRegion = new System.Windows.Forms.Panel();
   this.panel1 = new System.Windows.Forms.Panel();
   this.labelScore = new System.Windows.Forms.Label();
   this.labelEatGreenCount = new System.Windows.Forms.Label();
   this.labelCurrentCount = new System.Windows.Forms.Label();
   this.labelInitCount = new System.Windows.Forms.Label();
   this.labelStatistic = new System.Windows.Forms.Label();
   this.labelRight = new System.Windows.Forms.Label();
   this.labelLeft = new System.Windows.Forms.Label();
   this.labelDown = new System.Windows.Forms.Label();
   this.labelUp = new System.Windows.Forms.Label();
   this.labelGameIntroduce = new System.Windows.Forms.Label();
   this.labelGameCurrentDifficulty = new System.Windows.Forms.Label();
   this.labelGameDifficulty = new System.Windows.Forms.Label();
   this.panel1.SuspendLayout();
   this.SuspendLayout();
   //
   // menuMain
   //
   this.menuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                      this.menuGame,
                      this.menuOption});
   //
   // menuGame
   //
   this.menuGame.Index = 0;
   this.menuGame.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                      this.menuGameBegin,
                      this.menuGameRebegin,
                      this.menuGameEnd});
   this.menuGame.Text = "游戏(&G)";
   //
   // menuGameBegin
   //
   this.menuGameBegin.Index = 0;
   this.menuGameBegin.Text = "开始(&S)";
   this.menuGameBegin.Click += new System.EventHandler(this.menuGameBegin_Click);
   //
   // menuGameRebegin
   //
   this.menuGameRebegin.Enabled = false;
   this.menuGameRebegin.Index = 1;
   this.menuGameRebegin.Text = "重新开始(&R)";
   this.menuGameRebegin.Click += new System.EventHandler(this.menuGameRebegin_Click);
   //
   // menuGameEnd
   //
   this.menuGameEnd.Index = 2;
   this.menuGameEnd.Text = "结束(&X)";
   this.menuGameEnd.Click += new System.EventHandler(this.menuGameEnd_Click);
   //
   // menuOption
   //
   this.menuOption.Index = 1;
   this.menuOption.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                        this.menuOptionGameDifficulty,
                        this.menuOptionSplit,
                        this.menuOptionTopMost});
   this.menuOption.Text = "选项(&O)";
   //
   // menuOptionGameDifficulty
   //
   this.menuOptionGameDifficulty.Index = 0;
   this.menuOptionGameDifficulty.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                          this.menuOptionGameDifficultyEasy,
                          this.menuOptionGameDifficultyCommon,
                          this.menuOptionGameDifficultyDifficult});
   this.menuOptionGameDifficulty.Text = "游戏难度";
   //
   // menuOptionGameDifficultyEasy
   //
   this.menuOptionGameDifficultyEasy.Index = 0;
   this.menuOptionGameDifficultyEasy.RadioCheck = true;
   this.menuOptionGameDifficultyEasy.Text = "容易";
   this.menuOptionGameDifficultyEasy.Click += new System.EventHandler(this.menuOptionGameDifficultyEasy_Click);
   //
   // menuOptionGameDifficultyCommon
   //
   this.menuOptionGameDifficultyCommon.Checked = true;
   this.menuOptionGameDifficultyCommon.Index = 1;
   this.menuOptionGameDifficultyCommon.RadioCheck = true;
   this.menuOptionGameDifficultyCommon.Text = "一般";
   this.menuOptionGameDifficultyCommon.Click += new System.EventHandler(this.menuOptionGameDifficultyCommon_Click);
   //
   // menuOptionGameDifficultyDifficult
   //
   this.menuOptionGameDifficultyDifficult.Index = 2;
   this.menuOptionGameDifficultyDifficult.RadioCheck = true;
   this.menuOptionGameDifficultyDifficult.Text = "极难";
   this.menuOptionGameDifficultyDifficult.Click += new System.EventHandler(this.menuOptionGameDifficultyDifficult_Click);
   //
   // menuOptionSplit
   //
   this.menuOptionSplit.Index = 1;
   this.menuOptionSplit.Text = "-";
   //
   // menuOptionTopMost
   //
   this.menuOptionTopMost.Index = 2;
   this.menuOptionTopMost.Text = "总在最前面";
   this.menuOptionTopMost.Click += new System.EventHandler(this.menuOptionTopMost_Click);
   //
   // panelGameRegion
   //
   this.panelGameRegion.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
    | System.Windows.Forms.AnchorStyles.Left)
    | System.Windows.Forms.AnchorStyles.Right)));
   this.panelGameRegion.BackColor = System.Drawing.Color.Black;
   this.panelGameRegion.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
   this.panelGameRegion.Location = new System.Drawing.Point(8, 16);
   this.panelGameRegion.Name = "panelGameRegion";
   this.panelGameRegion.Size = new System.Drawing.Size(500, 540);
   this.panelGameRegion.TabIndex = 0;
   //
   // panel1
   //
   this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
    | System.Windows.Forms.AnchorStyles.Right)));
   this.panel1.Controls.Add(this.labelScore);
   this.panel1.Controls.Add(this.labelEatGreenCount);
   this.panel1.Controls.Add(this.labelCurrentCount);
   this.panel1.Controls.Add(this.labelInitCount);
   this.panel1.Controls.Add(this.labelStatistic);
   this.panel1.Controls.Add(this.labelRight);
   this.panel1.Controls.Add(this.labelLeft);
   this.panel1.Controls.Add(this.labelDown);
   this.panel1.Controls.Add(this.labelUp);
   this.panel1.Controls.Add(this.labelGameIntroduce);
   this.panel1.Controls.Add(this.labelGameCurrentDifficulty);
   this.panel1.Controls.Add(this.labelGameDifficulty);
   this.panel1.Location = new System.Drawing.Point(515, 8);
   this.panel1.Name = "panel1";
   this.panel1.Size = new System.Drawing.Size(104, 545);
   this.panel1.TabIndex = 3;
   //
   // labelScore
   //
   this.labelScore.ForeColor = System.Drawing.Color.White;
   this.labelScore.Location = new System.Drawing.Point(8, 184);
   this.labelScore.Name = "labelScore";
   this.labelScore.Size = new System.Drawing.Size(88, 16);
   this.labelScore.TabIndex = 11;
   this.labelScore.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
   //
   // labelEatGreenCount
   //
   this.labelEatGreenCount.ForeColor = System.Drawing.Color.Green;
   this.labelEatGreenCount.Location = new System.Drawing.Point(8, 168);
   this.labelEatGreenCount.Name = "labelEatGreenCount";
   this.labelEatGreenCount.Size = new System.Drawing.Size(88, 16);
   this.labelEatGreenCount.TabIndex = 10;
   this.labelEatGreenCount.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
   //
   // labelCurrentCount
   //
   this.labelCurrentCount.ForeColor = System.Drawing.Color.White;
   this.labelCurrentCount.Location = new System.Drawing.Point(8, 144);
   this.labelCurrentCount.Name = "labelCurrentCount";
   this.labelCurrentCount.Size = new System.Drawing.Size(88, 16);
   this.labelCurrentCount.TabIndex = 9;
   this.labelCurrentCount.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
   //
   // labelInitCount
   //
   this.labelInitCount.ForeColor = System.Drawing.Color.White;
   this.labelInitCount.Location = new System.Drawing.Point(8, 119);
   this.labelInitCount.Name = "labelInitCount";
   this.labelInitCount.Size = new System.Drawing.Size(88, 16);
   this.labelInitCount.TabIndex = 8;
   this.labelInitCount.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
   //
   // labelStatistic
   //
   this.labelStatistic.Font = new System.Drawing.Font("隶书", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
   this.labelStatistic.ForeColor = System.Drawing.Color.White;
   this.labelStatistic.Location = new System.Drawing.Point(8, 80);
   this.labelStatistic.Name = "labelStatistic";
   this.labelStatistic.Size = new System.Drawing.Size(88, 32);
   this.labelStatistic.TabIndex = 7;
   this.labelStatistic.Text = "游戏统计:";
   this.labelStatistic.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
   //
   // labelRight
   //
   this.labelRight.ForeColor = System.Drawing.Color.White;
   this.labelRight.Location = new System.Drawing.Point(8, 408);
   this.labelRight.Name = "labelRight";
   this.labelRight.Size = new System.Drawing.Size(88, 23);
   this.labelRight.TabIndex = 6;
   this.labelRight.Text = "D(Right)  右";
   this.labelRight.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
   //
   // labelLeft
   //
   this.labelLeft.ForeColor = System.Drawing.Color.White;
   this.labelLeft.Location = new System.Drawing.Point(8, 376);
   this.labelLeft.Name = "labelLeft";
   this.labelLeft.Size = new System.Drawing.Size(88, 23);
   this.labelLeft.TabIndex = 5;
   this.labelLeft.Text = "A(Left)   左";
   this.labelLeft.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
   //
   // labelDown
   //
   this.labelDown.ForeColor = System.Drawing.Color.White;
   this.labelDown.Location = new System.Drawing.Point(8, 344);
   this.labelDown.Name = "labelDown";
   this.labelDown.Size = new System.Drawing.Size(88, 23);
   this.labelDown.TabIndex = 4;
   this.labelDown.Text = "S(Down) 向下";
   this.labelDown.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
   //
   // labelUp
   //
   this.labelUp.ForeColor = System.Drawing.Color.White;
   this.labelUp.Location = new System.Drawing.Point(8, 312);
   this.labelUp.Name = "labelUp";
   this.labelUp.Size = new System.Drawing.Size(88, 23);
   this.labelUp.TabIndex = 3;
   this.labelUp.Text = "W(Up)   向上";
   this.labelUp.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
   //
   // labelGameIntroduce
   //
   this.labelGameIntroduce.Font = new System.Drawing.Font("隶书", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
   this.labelGameIntroduce.ForeColor = System.Drawing.Color.White;
   this.labelGameIntroduce.Location = new System.Drawing.Point(8, 272);
   this.labelGameIntroduce.Name = "labelGameIntroduce";
   this.labelGameIntroduce.Size = new System.Drawing.Size(88, 32);
   this.labelGameIntroduce.TabIndex = 2;
   this.labelGameIntroduce.Text = "游戏说明:";
   this.labelGameIntroduce.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
   //
   // labelGameCurrentDifficulty
   //
   this.labelGameCurrentDifficulty.ForeColor = System.Drawing.Color.White;
   this.labelGameCurrentDifficulty.Location = new System.Drawing.Point(8, 48);
   this.labelGameCurrentDifficulty.Name = "labelGameCurrentDifficulty";
   this.labelGameCurrentDifficulty.Size = new System.Drawing.Size(88, 23);
   this.labelGameCurrentDifficulty.TabIndex = 1;
   this.labelGameCurrentDifficulty.Text = "一般";
   this.labelGameCurrentDifficulty.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
   //
   // labelGameDifficulty
   //
   this.labelGameDifficulty.Font = new System.Drawing.Font("隶书", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
   this.labelGameDifficulty.ForeColor = System.Drawing.Color.White;
   this.labelGameDifficulty.Location = new System.Drawing.Point(8, 8);
   this.labelGameDifficulty.Name = "labelGameDifficulty";
   this.labelGameDifficulty.Size = new System.Drawing.Size(88, 32);
   this.labelGameDifficulty.TabIndex = 0;
   this.labelGameDifficulty.Text = "游戏难度:";
   this.labelGameDifficulty.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
   //
   // formMain
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.BackColor = System.Drawing.Color.Black;
   this.ClientSize = new System.Drawing.Size(632, 565);
   this.ControlBox = false;
   this.Controls.Add(this.panel1);
   this.Controls.Add(this.panelGameRegion);
   this.Menu = this.menuMain;
   this.Name = "formMain";
   this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
   this.Text = "贪吃蛇 - by lzumcj";
   this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
   this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.formMain_KeyDown);
   this.panel1.ResumeLayout(false);
   this.ResumeLayout(false);

  }
  #endregion

  ///
  /// 应用程序的主入口点。
  ///
  [STAThread]
  static void Main()
  {
   Application.Run(new formMain());
  }

  ///
  /// 选择开始游戏
  ///
  ///
  ///
  private void menuGameBegin_Click(object sender, System.EventArgs e)
  {
   this.menuGameBegin.Enabled = false;
   this.menuGameRebegin.Enabled = true;

   BeginGame();
  }

  ///
  /// 选择重新开始游戏
  ///
  ///
  ///
  private void menuGameRebegin_Click(object sender, System.EventArgs e)
  {
   BeginGame();
  }

  ///
  /// 选择结束游戏
  ///
  ///
  ///
  private void menuGameEnd_Click(object sender, System.EventArgs e)
  {
   ExitGame();
  }

  ///
  /// 选择游戏难度
  ///
  ///
  ///
  private void menuOptionGameDifficultyEasy_Click(object sender, System.EventArgs e)
  {
   SelectGameDifficulty(sender , e);
  }

  private void menuOptionGameDifficultyCommon_Click(object sender, System.EventArgs e)
  {
   SelectGameDifficulty(sender , e);
  }

  private void menuOptionGameDifficultyDifficult_Click(object sender, System.EventArgs e)
  {
   SelectGameDifficulty(sender , e);
  }

  ///
  /// 选择总在最前面
  ///
  ///
  ///
  private void menuOptionTopMost_Click(object sender, System.EventArgs e)
  {
   menuOptionTopMost.Checked = !menuOptionTopMost.Checked;
   this.TopMost = menuOptionTopMost.Checked;
  }

  ///
  /// 响应键盘输入
  ///
  ///
  ///
  private void formMain_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
  {
   //
   // 根据键盘输入重新设置蛇的运动方向
   //
   if (snake != null)
    snake.ResetMoveDirection(e.KeyData.ToString());
  }

  ///
  /// 开始游戏(设置游戏规则)
  ///
  private void BeginGame()
  {
   int iGreenCount = 0;  // 吃的绿色数

   // 清除上次剩下的食物
   if (snakeFood != null)
   {
    snakeFood.Clear();
    snakeFood.Dispose();
   }
   snakeFood = new SnakeFood(this.panelGameRegion , iMaxCount , iRadius);

   // 清除上次的蛇
   if (snake != null)
   {
    snake.Clear();
    snake.Dispose();
   }

   // 初始化新蛇
   snake = new Snake(this.panelGameRegion , iCount , iRadius);
   snake.Draw();

   int k = 0;
   while (!GameOver())
   {
    Application.DoEvents();
    snake.MoveNext();

    for (int iIndex=0; iIndex    {
     if (snakeFood[iIndex].CenterX == snake.CurrentHeadX && snakeFood[iIndex].CenterY == snake.CurrentHeadY)
     {
      if (snakeFood[iIndex].ColorNode == Color.Green)
      {
       snake.AddTrail();

       iGreenCount++;
       snakeFood.RemoveFood(iIndex);
      }
     }
    }

    // 统计结果
    labelInitCount.Text = "初始蛇长:" + Convert.ToString(iCount);
    labelCurrentCount.Text = "现在蛇长:" + Convert.ToString(snake.Count);
    labelEatGreenCount.Text = "吃了:● × " + Convert.ToString(iGreenCount);
    labelScore.Text = "得分:" + Convert.ToString(iGreenCount * 20);

    // 两次移动的时间间隔(即移动速度)
    Thread.Sleep(iSpeed);

    // 显示随机产生的点 , 且控制当前最多只能有iMaxCount
    if (k%(iSpeed/40*30) == 0 && snakeFood.CurrentCount    {
     snakeFood.AddFood();
    }
    k++;
   }

   this.menuGameRebegin.Enabled = true;

   DialogResult drResult = MessageBox.Show("重新开始游戏?" , "提示" , MessageBoxButtons.OKCancel , MessageBoxIcon.Information , MessageBoxDefaultButton.Button1);

   if (drResult == DialogResult.OK)
    BeginGame();
   else
    ExitGame();
  }

  ///
  /// 判断游戏是否满足结束条件
  ///
  ///
  private bool GameOver()
  {
   if (snake != null)
   {
    snake.Check();
    return snake.IsEatself || snake.IsOutOfRange;
   }

   return false;
  }

  ///
  /// 退出游戏
  ///
  private void ExitGame()
  {
   if (Application.AllowQuit)
   {
    Application.ExitThread();
    Application.Exit();
   }
  }

  ///
  /// 选择游戏难度(互斥)
  ///
  ///
  ///
  private void SelectGameDifficulty(object sender , EventArgs e)
  {
   if (sender == menuOptionGameDifficultyEasy)
   {
    menuOptionGameDifficultyEasy.Checked = true;
    menuOptionGameDifficultyCommon.Checked = false;
    menuOptionGameDifficultyDifficult.Checked = false;

    labelGameCurrentDifficulty.Text =  menuOptionGameDifficultyEasy.Text;;

    iSpeed = ciSpeed * 2;
   }
   else if (sender == menuOptionGameDifficultyCommon)
   {
    menuOptionGameDifficultyEasy.Checked = false;
    menuOptionGameDifficultyCommon.Checked = true;
    menuOptionGameDifficultyDifficult.Checked = false;

    labelGameCurrentDifficulty.Text =  menuOptionGameDifficultyCommon.Text;

    iSpeed = ciSpeed;
   }
   else if (sender == menuOptionGameDifficultyDifficult)
   {
    menuOptionGameDifficultyEasy.Checked = false;
    menuOptionGameDifficultyCommon.Checked = false;
    menuOptionGameDifficultyDifficult.Checked = true;

    labelGameCurrentDifficulty.Text =  menuOptionGameDifficultyDifficult.Text;

    iSpeed = ciSpeed / 2;
   }
  }
 }
}
//
// Main.cs End
//

//
// Snake.cs Begin
//
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.Timers;

namespace GreedySnake
{
 #region Snake 蛇身
 ///
 /// Snake 的摘要说明。
 ///
 public class Snake
 {
  private Control dcControl;

  private static int iMoveDirection = 0x1000; // 蛇的运动方向 , 初始化为 right - 0x1000

  private int iCount;   // 骨节的总数
  private int iRadius;  // 骨节的半径

  private static int iCurrentHeadX; // 当前蛇头的中心坐标 X
  private static int iCurrentHeadY; // 当前蛇头的中心坐标 Y 

  private static int iCurrentTrailX; // 当前蛇尾的中心坐标 X
  private static int iCurrentTrailY; // 当前蛇尾的中心坐标 Y 

  private static int iNextHeadX;  // 下一时刻蛇头的中心坐标 X
  private static int iNextHeadY;  // 下一时刻蛇头的中心坐标 Y

  private static int iPreTrailX;  // 前一时刻蛇尾的中心坐标 X
  private static int iPreTrailY;  // 前一时刻蛇尾的中心坐标 Y

  private static ArrayList alSnake; // 存放整条蛇
  private bool bDisposing = true;

  private bool bIsEatself = false; // 是否吃自己
  private bool bIsOutOfRange = false; // 是否超出允许活动的范围

  public Control DcControl
  {
   set { dcControl = value; }
   get { return dcControl;}
  }
  public int MoveDirection
  {
   set { iMoveDirection = value; }
   get { return iMoveDirection; }
  }

  public int Count
  {
   set { iCount = value; }
   get { return iCount; }
  }

  public int Radius
  {
   set { iRadius = value; }
   get { return iRadius; }
  }

  public int CurrentHeadX
  {
   set { iCurrentHeadX = value; }
   get { return iCurrentHeadX; }
  }

  public int CurrentHeadY
  {
   set { iCurrentHeadY = value; }
   get { return iCurrentHeadY; }
  }

  public int CurrentTrailX
  {
   set { iCurrentTrailX = value; }
   get { return iCurrentTrailX; }
  }

  public int CurrentTrailY
  {
   set { iCurrentTrailY = value; }
   get { return iCurrentTrailY; }
  }

  public int NextHeadX
  {
   set { iNextHeadX = value; }
   get { return iNextHeadX; }
  }

  public int NextHeadY
  {
   set { iNextHeadY = value; }
   get { return iNextHeadY; }
  }

  public int PreTrailX
  {
   set { iPreTrailX = value; }
   get { return iPreTrailX; }
  }

  public int PreTrailY
  {
   set { iPreTrailY = value; }
   get { return iPreTrailY; }
  }

  public bool IsEatself
  {
   set { bIsEatself = value; }
   get { return bIsEatself; }
  }

  public bool IsOutOfRange
  {
   set { bIsOutOfRange = value; }
   get { return bIsOutOfRange;}
  }

  public Snake() : this(null , 20 , 5)
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
  }

  public Snake(Control control , int iCount , int iRadius)
  {
   DcControl = control;

   Count = iCount;
   Radius = iRadius;

   CurrentHeadX = CurrentTrailX = PreTrailX = 5;
   CurrentHeadY = CurrentTrailY = PreTrailY = 5;

   Initialize();
  }

  ~Snake()
  {
   Dispose(false);
  }

  // 初始化蛇
  private void Initialize()
  {
   alSnake = new ArrayList();

   for (int i=0 ; i   {
    alSnake.Insert(0 , new SnakeNode(DcControl , CurrentHeadX , CurrentHeadY , Radius));
    CurrentHeadX += 2 * Radius;
   }

   CurrentHeadX -= 2 * Radius;

   NextHeadX = CurrentHeadX + 2 * Radius;
   NextHeadY = CurrentHeadY;
  }

  public void Dispose()
  {
   Dispose(true);
   GC.SuppressFinalize(this);
  }
 
  public void Dispose( bool bDisposing )
  {
   if (bDisposing)
   {
    // 调用 Dispose 处理受控资源中的字段
    MoveDirection = 0x1000;
    CurrentHeadX = CurrentHeadY = NextHeadX = NextHeadY = 5;
    alSnake.Clear();
   }
   // 清除非受控资源
  }

  // 加头
  public void AddHead()
  {
   alSnake.Insert(0 , new SnakeNode(DcControl , NextHeadX , NextHeadY , Radius));

   CurrentHeadX = NextHeadX;
   CurrentHeadY = NextHeadY;

   Count++;
  }

  // 加尾
  public void AddTrail()
  {
   alSnake.Add(new SnakeNode(DcControl , PreTrailX , PreTrailY , Radius));

   Count++;

   ((SnakeNode)alSnake[Count - 1]).Draw();
  }

  // 去尾
  public void RemoveTrail()
  {
   if (alSnake.Count>1)
   {
    PreTrailX = ((SnakeNode)alSnake[Count - 1]).CenterX;
    PreTrailY = ((SnakeNode)alSnake[Count - 1]).CenterY;

    alSnake.RemoveAt(alSnake.Count - 1);

    Count--;

    CurrentTrailX = ((SnakeNode)alSnake[Count - 1]).CenterX;
    CurrentTrailY = ((SnakeNode)alSnake[Count - 1]).CenterY;
   }
  }

  // 移动到下一位置
  public void MoveNext()
  {
   // 加头
   AddHead();
   // 画头
   ((SnakeNode)alSnake[0]).Draw();
   // 清除尾(将蛇尾用背景色填充)
   ((SnakeNode)alSnake[Count-1]).Clear();
   // 去尾(将蛇尾从 ArrayList 中删除)
   RemoveTrail();
  }
 
  // 画整条蛇
  public void Draw()
  {
   for (int i=0; i   {
    ((SnakeNode)alSnake[i]).Draw();
   }
  }

  // 清除整条蛇
  public void Clear()
  {
   for (int i=0; i   {
    ((SnakeNode)alSnake[i]).Clear();
   }
  }

  // 重设运动方向
  public void ResetMoveDirection(string strKeyData)
  {
   // 获取键盘输入
   int iKeyDirection;

   switch (strKeyData)
   {
    case "W":
    case "Up":
     iKeyDirection = 0x0001;
     break;
    case "S":
    case "Down":
     iKeyDirection = 0x0010;
     break;
    case "A":
    case "Left":
     iKeyDirection = 0x0100;
     break;
    case "D":
    case "Right":
     iKeyDirection = 0x1000;
     break;
    default:
     iKeyDirection = 0x0010;
     break;
   }

   // 重设蛇的运动方向(综合按键方向和当前蛇的运动方向考虑)
   int iDirection = iKeyDirection | MoveDirection;
   if (iDirection == 0x0011 || iDirection == 0x1100)
    MoveDirection = MoveDirection; // 运动方向保持不变
   else
    MoveDirection = iKeyDirection; // 运动方向等于按键方向
  }

  // 是否超出范围
  public void Check()
  {
   GetNextHeadXY();

   // 检查是否吃自己
   foreach (SnakeNode sn in alSnake)
   {
    if (sn.CenterX == NextHeadX && sn.CenterY == NextHeadY)
    {
     IsEatself = true;
     break;
    }
   }

   // 检查是否超出允许活动的范围
   IsOutOfRange = NextHeadX<0 || NextHeadX>DcControl.Width || NextHeadY<0 || NextHeadY>DcControl.Height;
  }

  // 预先算出下个位置坐标
  private void GetNextHeadXY()
  {
   switch (MoveDirection)
   {
    case 0x0001:
     NextHeadX = CurrentHeadX;
     NextHeadY = CurrentHeadY - 2 * Radius;
     break;
    case 0x0010:
     NextHeadX = CurrentHeadX;
     NextHeadY = CurrentHeadY + 2 * Radius;
     break;
    case 0x0100:
     NextHeadX = CurrentHeadX - 2 * Radius;
     NextHeadY = CurrentHeadY;
     break;
    case 0x1000:
     NextHeadX = CurrentHeadX + 2 * Radius;
     NextHeadY = CurrentHeadY;
     break;
    default:
     break;
   }
  }
 }
 #endregion
 
 #region SnakeNode 蛇的骨节
 ///
 /// Snake Note
 /// 蛇的骨节
 ///
 public class SnakeNode
 {
  private Control dcControl; // 用于画图的控件

  private int iCenterX; // 中心坐标 X
  private int iCenterY; // 中心坐标 Y
  private int iRadius; // 半径
  private Color colorNode; // 颜色

  public Control DcControl
  {
   set { dcControl = value; }
   get { return dcControl; }
  }

  public int CenterX
  {
   set { iCenterX = value; }
   get { return iCenterX; }
  }

  public int CenterY
  {
   set { iCenterY = value; }
   get { return iCenterY; }
  }

  public int Radius
  {
   set { iRadius = value; }
   get { return iRadius; }
  }

  public Color ColorNode
  {
   set { colorNode = value; }
   get { return colorNode; }
  }

  private bool bDisposing = true;

  public SnakeNode() : this(null , 0 , 0 , 5)
  {
  }

  public SnakeNode(Control control , int iX , int iY , int iR)
  {
   DcControl = control;

   CenterX = iX;
   CenterY = iY;
   Radius  = iR;
  }

  ~SnakeNode()
  {
   Dispose(false);
  }
 
  public void Dispose()
  {
   Dispose(true);
   GC.SuppressFinalize(this);
  }
 
  public void Dispose( bool bDisposing )
  {
   if (bDisposing)
   {
    // 调用 Dispose 处理受控资源中的字段
    CenterX = CenterY = 0;
    Radius = 5;
   }
   // 清除非受控资源
  }

  // 画自身
  public void Draw()
  {
   Draw(Color.Blue);
  }

  public void Draw(Color color)
  {
   // 以指定颜色画圆
   ColorNode = color;
   DrawCircle(ColorNode);
  }

  // 清除
  public void Clear()
  {
   // 以控件的背景色画圆
   DrawCircle(DcControl.BackColor);
  }

  // 以骨节的中心画圆
  public void DrawCircle(Color color)
  {
   using (Graphics dc = DcControl.CreateGraphics())
   {
    // 创建实心的笔刷
    SolidBrush sbBrush = new SolidBrush(color);
    // 创建圆的区间范围
    float x = CenterX - Radius;
    float y = CenterY - Radius;
    float width = 2 * Radius;
    float height = 2 * Radius;
    // 创建开始和扫过的弧度
    float fStartAngle = 0.0F;
    float fSweepAngle = 360.0F;
    // 画圆
    dc.FillPie(sbBrush , x , y , width , height , fStartAngle , fSweepAngle);
   }
  }
 }
 #endregion
 
 #region SnakeFood 蛇的食物
 ///
 /// SnakeFood 的摘要说明。
 ///
 public class SnakeFood
 {
  private Control dcControl;

  private int iMaxCount;   // 最多能剩下的食物总数
  private int iCurrentCount;  // 当前剩下的食物总数
  private int iRadius;  // 骨节的半径

  private Color[] acolor = new Color[]{Color.Red , Color.Green , Color.Yellow}; // 新点的颜色取值范围
  private static ArrayList alSnakeFood; // 蛇的食物
  private bool bDisposing = true;

  public Control DcControl
  {
   set { dcControl = value; }
   get { return dcControl;}
  }
  public int MaxCount
  {
   set { iMaxCount = value; }
   get { return iMaxCount; }
  }

  public int CurrentCount
  {
   set { iCurrentCount = value;}
   get { return iCurrentCount;}
  }

  public int Radius
  {
   set { iRadius = value; }
   get { return iRadius; }
  }

  public SnakeNode this[int index]
  {
   get
   {
    if (index<0 || index>=CurrentCount)
    {
     throw new IndexOutOfRangeException();
    }
    return (SnakeNode)alSnakeFood[index];
   }
  }

  public SnakeFood() : this(null , 5 , 5)
  {
  }

  public SnakeFood(Control control , int iMaxCount , int iRadius)
  {
   DcControl = control;

   MaxCount = iMaxCount;
   CurrentCount = 0;
   Radius = iRadius;

   alSnakeFood = new ArrayList();
  }

  ~SnakeFood()
  {
   Dispose(false);
  }

  public void Dispose()
  {
   Dispose(true);
   GC.SuppressFinalize(this);
  }
 
  public void Dispose( bool bDisposing )
  {
   if (bDisposing)
   {
    // 调用 Dispose 处理受控资源中的字段
    CurrentCount = 0;
    alSnakeFood.Clear();
   }
   // 清除非受控资源
  }

  // 添加食物
  public void AddFood()
  {
   Random random = new Random();

   int iStep = Radius + Radius;
   int iX = Radius + iStep * random.Next(0 , DcControl.Width/iStep);
   int iY = Radius + iStep * random.Next(0 , DcControl.Height/iStep);

   SnakeNode sn = new SnakeNode(DcControl , iX , iY , iRadius);

   Random randomIndex = new Random();
   Color color = acolor[randomIndex.Next(0 , acolor.Length)];
   color = Color.Green;
   sn.Draw(color);

   alSnakeFood.Add(sn);

   // 当前剩下的食物总数加1
   CurrentCount++;
  }

  // 删除被吃掉的食物
  public void RemoveFood(int iIndex)
  {
   if (CurrentCount>0)
   {
    alSnakeFood.RemoveAt(iIndex);

    // 当前剩下的食物总数减1
    CurrentCount--;
   }
  }

  // 画所有食物
  public void Draw()
  {
   foreach (SnakeNode sn in alSnakeFood)
   {
    sn.Draw();
   }
  }

  // 清除所有食物
  public void Clear()
  {
   foreach (SnakeNode sn in alSnakeFood)
   {
    sn.Clear();
   }
  }
 }
 #endregion
}
//
// Snake.cs End
//

 

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: