Hey everyone,

So basically I'm making a 'snake' game in a windows form. I want to make my line 'move' across the screen. I'm using the System.Graphics pen class to draw the line but for whatever reason the 'front' point of the line is incrementing but the back of the line is 'anchored.' I want the front to increment and then the back coordinate should be where the front coordinate was previously.

I'm incrementing both the x coordinates but the back coordinate is still anchored? Any ideas?

public partial class gameScreen : Form
 {
        Thread drawThread;
        int xLoc1,
            yLoc1,
            xLoc2,
            yLoc2;

        public gameScreen()
        {
            InitializeComponent();
            
            xLoc1 = 370;
            yLoc1 = 300;
            xLoc2 = 420;
            yLoc2 = 300;
        }
        private void drawString()
        {
            //keep drawing while the tread is alive
            while (drawThread.IsAlive)
            {
                Graphics graphics = this.CreateGraphics();
                //Draw with black
                Pen p = new Pen(Color.Black);
                p.Width = 8.0f;
                //draw a line
                graphics.DrawLine(p, xLoc1, yLoc1, xLoc2, yLoc2);
                //every second recall this thread
                Thread.Sleep(1000);
                //Increment
                xLoc2 += 20;
                //Increment
                xLoc1 += 20;
            }
        }
        private void gameScreen_Load(object sender, EventArgs e)
        {
            drawThread = new Thread(new ThreadStart(drawString));
            drawThread.Start();
        }
    }

Here are some suggestions,

1. Erase the line.
2. Get the new coordinate.
3. Draw a new line.

if you are creating a snake game you might want to create the snake as instances of a custom drawn square, so that you can place instances on the game board as positions on a grid. as this is how the game snake was originally written. ( I did one in javascript way back when )
just drawing a line will get really complicated when it gets to having your snake follow a movement path with corners.

best of luck.

This article has been dead for over six months. Start a new discussion instead.