2014-05-21 39 views
0

所以,我试图在屏幕上创建一个网格,为此,我实现了矩形的多维数组。鼠标点击数组中的矩形问题

程序启动时,我使用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(); 
     } 
    } 
} 

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

+0

您需要沉入MouseClick事件并获取当前的x和y坐标。使用它来查找矩形列表中的矩形列表。我不记得确切,但我认为你需要将屏幕坐标转换为窗口或反之,以确保您获得正确的偏移量。 –

回答

0

首先,两个指针:

  • 你存储你的计算y坐标为x位置你的矩形,反之亦然。切换Rectangle构造函数的前两个参数来解决这个问题。
  • 使用MouseClick事件而不是Click事件。前者为您提供一个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)进行测试是另一种解决方案。