程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> c#寫的貪吃蛇小游戲

c#寫的貪吃蛇小游戲

編輯:關於C語言

下面是游戲的源代碼。有兩個文件: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
//

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved