首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 實作尋找不同小遊戲完整原始碼

     編輯:關於C#

遊戲邏輯概述

雙圖找不同:預先定義每關的差異區域座標 (左上/右下兩點),遊戲載入兩張圖片,玩家點擊圖片,判斷點擊座標是否落於任一差異區域內,找到則以紅框標記,全找完自動進入下一關,計時記錄通關時間。

核心類別結構

public partial class Form1 : Form
{
    // 差異座標:[關卡][差異點*2] (左上、右下)
    private Point[][] local;
    private bool[] check;   // 每個差異是否已找到
    private int index;      // 目前關卡
    private const int COUNT = 2; // 總關卡數
    private int second;     // 計時秒數
    // ...
}

關鍵方法解析

座標比對

private bool LocationCompare(Point current, Point topLeft, Point bottomRight)
{
    return current.X >= topLeft.X && current.Y >= topLeft.Y
        && current.X <= bottomRight.X && current.Y <= bottomRight.Y;
}

點擊事件處理


private void pictureBox1_Click(object sender, EventArgs e)
{
    Point pt = ((MouseEventArgs)e).Location;
    if (LocationCompare(pt, local[index][0], local[index][1])) { check[0]=true; pictureBox1.Refresh(); }
    if (LocationCompare(pt, local[index][2], local[index][3])) { check[1]=true; pictureBox1.Refresh(); }

    if (check[0] && check[1]) { /* 畫面重繪事件中處理換關 */ }
}

重繪事件繪製紅框


private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    Pen pen = new Pen(Color.Red, 3);
    if (check[0]) e.Graphics.DrawRectangle(pen, GetRect(local[index][0], local[index][1]));
    if (check[1]) e.Graphics.DrawRectangle(pen, GetRect(local[index][2], local[index][3]));

    if (check[0] && check[1]) 
    { 
        Thread.Sleep(100); 
        index++; check[0]=check[1]=false; 
        LoadPicture(); 
    }
}

Rectangle GetRect(Point p1, Point p2) => 
    new Rectangle(p1.X, p1.Y, p2.X-p1.X, p2.Y-p1.Y);

計時器


private void timer1_Tick(object sender, EventArgs e)
{
    lblTime.Text = $"{++second} 秒";
}

擴充建議

  • 使用 List<Rectangle> 取代固定陣列,支援任意數量差異點。
  • 圖片資源嵌入專案資源檔 (.resx),避免外部檔案遺失。
  • 加入難度設定:差異區域大小、時間限制、錯誤點擊懲罰。
  • 使用 DoubleBuffered = true 減少閃爍。
  • 分離遊戲邏輯類別 (GameEngine) 與 UI,便於單元測試。

完整原始碼已包含於專案中,可直接編譯執行體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved