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

C# 實作找不同小遊戲

     編輯:關於C語言

遊戲邏輯

  1. 預設兩張圖片的差異座標區域(左上、右下點)
  2. 雙 PictureBox 並排顯示圖片
  3. 滑鼠點擊時判斷座標是否落於差異區域
  4. 命中則以紅框標記,全部找到後自動換關
  5. 計時器記錄通關時間

核心程式碼結構

public partial class Form1 : Form {
    private Point[][] _diffRegions; // [關卡][4點: 兩個矩形]
    private bool[] _found;
    private int _level = 0;
    private int _seconds = 0;
    const int MAX_LEVEL = 2;

    private void Form1_Load(...) {
        _found = new bool[MAX_LEVEL];
        _diffRegions = new Point[MAX_LEVEL][];
        // 關卡 0 差異區域
        _diffRegions[0] = new Point[4] { new Point(245,50), new Point(253,61), new Point(263,520), new Point(287,546) };
        // 關卡 1 差異區域
        _diffRegions[1] = new Point[4] { new Point(190,237), new Point(203,249), new Point(121,490), new Point(137,497) };
    }

    private void picBox_Click(object sender, MouseEventArgs e) {
        Point pt = e.Location;
        if (InRegion(pt, _diffRegions[_level][0], _diffRegions[_level][1])) { _found[0]=true; picBox.Invalidate(); }
        if (InRegion(pt, _diffRegions[_level][2], _diffRegions[_level][3])) { _found[1]=true; picBox.Invalidate(); }
    }

    private bool InRegion(Point p, Point tl, Point br) =>
        p.X >= tl.X && p.Y >= tl.Y && p.X <= br.X && p.Y <= br.Y;

    private void picBox_Paint(object sender, PaintEventArgs e) {
        Pen pen = new Pen(Color.Red, 3);
        if (_found[0]) e.Graphics.DrawRectangle(pen, RectFromPoints(_diffRegions[_level][0], _diffRegions[_level][1]));
        if (_found[1]) e.Graphics.DrawRectangle(pen, RectFromPoints(_diffRegions[_level][2], _diffRegions[_level][3]));
        if (_found[0] && _found[1]) {
            Thread.Sleep(100);
            _level++; _found[0]=_found[1]=false;
            LoadPicture();
        }
    }

    private void timer_Tick(...) => lblTime.Text = $"{++_seconds} 秒";
}

擴充建議

  • 將差異資料外部化(JSON/XML)支援多關卡
  • 加入提示、暫停、難度選擇
  • 使用雙緩衝減少閃爍
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved