Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

c# - MouseEventArgs pass different values for mouse position to different click actions?

I'm working on a connect 4 game and I've got the following part done:

I've made the board which is able to display tiles of the board in 3 colors (white, red and yellow). I've also written some code to display a box around the column on which the user is hovering such that he can see where he is placing a dish.

I've also created the code which allows a dish to be added to the board. Both of these processes use the following code:

//Calculate the size of a single cell
int cellX = this.Size.Width / this.Columns;

//calculate the cell which was clicked
int nColumn = (int)Math.Floor((Double)x / cellX);

x is the value of MouseEventArgs.X of the pannel on which this is called. For drawing a boundry box this code works perfectly but for dropping a dish it doesn't. sometimes it drops 1 left of where I want it sometimes one right.

Here is the code for both events:

//draws the bounding box around the column for a given x value. 
public void drawBoundingBox(int x)
{
    //Calculate the size of a single cell
    int cellX = this.Size.Width / this.Columns;

    //calculate the cell which was clicked
    int nColumn = (int)Math.Floor((Double)x / cellX);

    if (nColumn != this.lastColumn)
    {
        this.Refresh();

        Graphics g = CreateGraphics();
        Pen pRed = new Pen(Color.Red, 3);

        if (nColumn < this.Columns)
        {
            Rectangle rect = new Rectangle(new Point(nColumn * cellX, 0),
                                           new Size(cellX, this.Size.Height));

            g.DrawRectangle(pRed, rect);
        }
    }
    this.lastColumn = nColumn;
}

public Boolean move(int mousePosition) {
    int cellX = this.Size.Width / this.Columns;

    int nColumn = (int)Math.Floor((Double)mousePosition / cellX);

    return board.Move(nColumn);
}

Here is the code for board.move():

public bool Move(int x)
{
    bool found = false;
    for (int i = Rows - 1; i >= 0 && !found; i--)
    {
        Console.WriteLine("X equals: " + x + " i equals: " + i);
        if (States[i,x] == 0) {
            found = true;
            States[i, x] = (byte)(((moves++) % 2) + 1);
        }
    }
    return found;
}

Here is a gif showing what I mean: enter image description here

To me it seams like a rounding error but it's wierd to me that the bounding box works well with the mouse but the clicking action doesn't...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...