Invalidate a region for smooth animation c#

320 views Asked by At

I am doing a project about a chess-like game, so players own their pawns on the map. Every time player decides to move a pawn, he needs to get a number from a dice, then that pawn would move according to the rolled number. Move function of pawns is finished, but I didn't show the moving process for them.

I have one panel for map and four panels for starting base(holding the pawns at the beginning of the game). GUI for gameboard

In paint event, I ask the system to draw everything.

private void P_Map_Paint(object sender, PaintEventArgs e)
    {
            manager.VisualizeCollection(map, gr_map);
            manager.VisualizeStartingBase(bases, grs); 
            manager.VisualizePawns(manager.Players, grs, gr_map);
            manager.DisplayAvailablePawn(gr_map, grs);
            manager.DisplaySelectedPawn(gr_map, grs);
    }

For every move of a pawn, I am trying to use a timer to make the image moving on the screen.

public void DoMovement(Pawn pawn)
    {
        if (TargetSpot != null)
        {
            System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
            EventHandler t_tick = null;
            Point targetP = TargetSpot.Location;
            Point currentP = pawn.ImageLocation;
            int XMove = (targetP.X - currentP.X) / 10;
            int YMove = (targetP.Y - currentP.Y) / 10;

            Rectangle drawRange = new Rectangle(pawn.ImageLocation.X - (int)(0.5 * pawn.Image.Width),
                                                pawn.ImageLocation.Y - (int)(0.5 * pawn.Image.Height), pawn.Image.Width, pawn.Image.Height);
            t_tick = (senders, args) =>
            {
                if (currentP.X > targetP.X - XMove || currentP.X < targetP.X + XMove)
                {// if the image of the pawn doesn't reach the destination
                    //we keep moving it and ask the pawn to redraw the old place
                    pawn.ImageLocation = new Point(currentP.X + XMove, currentP.Y + YMove);
                    pawn.CurrentPanel.Invalidate(drawRange);
                }
                else
                {
                    pawn.CurrentLocation.LeaveAPawn(pawn);
                    pawn.CurrentLocation = TargetSpot;
                    TargetSpot.AddAPawn(pawn);
                    pawn.CurrentPanel.Invalidate(drawRange);
                }
            };
            t.Tick += t_tick;
            t.Interval = 300;
            t.Start();
        }
    }

This is not working fine, everything on the panel is still redrawing. Why?

Excepting the project, I do have a question about the invalidating a region. Like I told the rules of drawing to paint event, then the panel invalidates itself. When we are going to invalidate a region, how the system knows the rule about drawing?

0

There are 0 answers