鼠标单击数组中的矩形时出现问题

本文关键字:问题 单击 数组 鼠标 | 更新日期: 2023-09-27 18:04:26

所以,我试图在屏幕上创建一个网格,为此,我实现了一个多维矩形数组。

当程序启动时,我使用for循环来增加x和y坐标以形成网格。

public Form1() {
    InitializeComponent();
    for (int x = 0; x < 12; x++) {
        for (int y = 0; y < 12; y++) {
            recArray[x, y] = new Rectangle(y * 50, x * 50, 100, 100);
        }
        Application.DoEvents();
    }
}

我的问题是试图弄清楚用户何时点击了一个矩形,此外,他/她点击了数组中的哪个矩形。当给定正确的矩形时,我将把边框改为红色。

我使用的是Visual Studio 2008,下面是我到目前为止的代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Quoridor {
    public partial class Form1 : Form {
        private Pen pen = Pens.Black;
        Rectangle[,] recArray = new Rectangle[12, 12];
        public Form1() {
            InitializeComponent();
            for (int x = 0; x < 12; x++) {
                for (int y = 0; y < 12; y++) {
                    recArray[x, y] = new Rectangle(y * 50, x * 50, 100, 100);
                }
                Application.DoEvents();
            }
        }
        protected override void OnPaint(PaintEventArgs e) {
            base.OnPaint(e);
            for (int x = 0; x < 12; x++) {
                for (int y = 0; y < 12; y++) {
                    e.Graphics.DrawRectangle(pen, recArray[x, y]);
                    Application.DoEvents();
                }
            }
        }
        private void Form1_Click(object sender, EventArgs e) {
            Point cursor = this.PointToClient(Cursor.Position);
            Refresh();
        }
    }
}

我正在把它变成一个真正的游戏,类和所有。但要记住,这是我编程的第二个月,所以不要太苛刻^_^

鼠标单击数组中的矩形时出现问题

首先,几个指针:

  • 将计算出的y坐标存储为矩形的x位置,反之亦然。切换矩形构造函数的前两个参数来解决这个问题。
  • 使用鼠标点击事件代替点击事件。前者为您提供一个MouseEventArgs,其中包含点击相对于Form的坐标。
  • 你的矩形目前是重叠的,因为它们是100 x 100,但相距50像素。这似乎是无意的(因为点击通常会落在2个矩形上)。这也是为什么你的网格看起来是13x13而不是12x12。要解决这个问题,传递50而不是100作为你的Rectangle s的宽度和高度。

然后可以按如下方式确定已单击的Rectangle:

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
    Rectangle clickedRectangle = FindClickedRectangle(e.Location);
    if (!clickedRectangle.IsEmpty)
        Console.WriteLine("X: {0} Y: {1}", clickedRectangle.X, clickedRectangle.Y);
}
private Rectangle FindClickedRectangle(Point point)
{
    // Calculate the x and y indices in the grid the user clicked
    int x = point.X / 50;
    int y = point.Y / 50;
    // Check if the x and y indices are valid
    if (x < recArray.GetLength(0) && y < recArray.GetLength(1))
        return recArray[x, y];
    return Rectangle.Empty;
}

注意,我使用一个简单的计算来确定被单击的矩形,这是可能的,因为您的矩形位于网格中。如果你想要脱离网格布局,循环覆盖所有的矩形并使用Rectangle.Contains(Point)来测试它们是另一种解决方案。