Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to implement a snake game in C# using the WPF forms. Well I know to implement the snake game, where the snake is controlled by the keyboard. But how would I do it, if I wanted to control the snake using a mouse rather than a keyboard?

share|improve this question
That depends a lot on how you want to control the snake with the mouse. Should it turn gradually as you move the mouse left/right, should it stand still until you click somewhere and then use pathfinding to reach that point, should it always try to get to the mouse the most direct path it can or possibly even have buttons you click to alter the direction? Until you decide how you want the mouse to control the snake we cannot really help you with the code of how to control the snake with the mouse. – Daniel Carlsson Apr 16 '12 at 22:35
well there is no usage of buttons in this game, the snake should follow the path of the mouse, in the direction the mouse cursor has been moved. – user1221876 Apr 17 '12 at 0:07

On your gamefield element add a MouseMove event handler, in this handler add:

var pos = Mouse.GetPosition(e.MouseDevice.DirectlyOver);
worm.Target = new Vector(pos.X, pos.Y);

And in an appropriate spot in the worm class (such as an update method, or called from the Target/Position setters):

var delta = new Vector(Target.X - Position.X, Target.Y - Position.Y);
if (Math.Abs(delta.Y) > Math.Abs(delta.X))
    if (delta.Y < 0)
        this.Direction = Direction.Up;
        this.Direction = Direction.Down;
    if (delta.X < 0)
        this.Direction = Direction.Left;
        this.Direction = Direction.Right;

With this logic it would try to close in the longest orthogonal distance (x or y) first, and then go zigzag to the cursor when the distance is the same in both x and y, other options would be to use a line drawing algorithm to make it go more smoothly towards the cursor.

There is a few other things to consider as well, such as what do we do if the worm reaches the mouse, does it stop, or do we allow it to first pass the cursor and then double back thus hitting itself?

share|improve this answer
You could also add checks to ensure you could move along the axis with the smallest delta and if not then move along the other one. – George Duckett Apr 17 '12 at 6:51

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.