This article is currently in the process of being translated into French (~33% done).

Création d'un jeu : SnakeWPF:
Chapter introduction:

In this article series, we're building a complete Snake game from scratch. It makes sense to start with the Introduction and then work your way through the articles one by one, to get the full understanding.

If you want to get the complete source code for the game at once, to get started modifying and learning from it right now, consider downloading all our samples!

Controlling the Snake

À ce stade de notre série d'articles sur SnakeWPF, nous avons maintenant un joli arrière-plan et un serpent en mouvement. Malheureusement, le serpent se contente de se déplacer dans une seule direction jusqu'à ce qu'il quitte la zone. Nous devons évidemment ajouter du code afin de pouvoir contrôler le serpent avec le clavier.

La plupart des contrôles WPF comportent des événements permettant de recevoir des entrées à la souris et au clavier. Ainsi, en fonction de l'endroit où vous souhaitez vérifier les données, vous pouvez vous inscrire à ces événements pour un ou plusieurs contrôles et y effectuer les traitements correspondants. Cependant, comme il s'agit d'un jeu, nous voulons capter les entrées du clavier quel que soit l'endroit où se trouve le centre d'intérêt, donc nous allons simplement nous inscrire à l'événement directement sur la fenêtre.

Pour réaliser cette tâche, l'événement KeyUp correspond parfaitement. Donc, dans le fichier XAML correspondant à la fenêtre, modifiez la balise Window de façon à ce qu'elle inclue l'événement KeyUp comme ceci :

<Window x:Class="WpfTutorialSamples.Games.SnakeWPFSample"  
Title="SnakeWPF - Score: 0" SizeToContent="WidthAndHeight"
ContentRendered="Window_ContentRendered" KeyUp="Window_KeyUp">

Dans votre le code associé (Code-behind), ajoutez le handler pour l'événement Window_KeyUp comme ceci :

private void Window_KeyUp(object sender, KeyEventArgs e)
    SnakeDirection originalSnakeDirection = snakeDirection;
case Key.Up:
    if(snakeDirection != SnakeDirection.Down)
snakeDirection = SnakeDirection.Up;
case Key.Down:
    if(snakeDirection != SnakeDirection.Up)
snakeDirection = SnakeDirection.Down;
case Key.Left:
    if(snakeDirection != SnakeDirection.Right)
snakeDirection = SnakeDirection.Left;
case Key.Right:
    if(snakeDirection != SnakeDirection.Left)
snakeDirection = SnakeDirection.Right;
case Key.Space:
    if(snakeDirection != originalSnakeDirection)

The first thing we do is to save a reference to the current direction that the snake is going in - we need this to make sure that the player is not trying to do something we won't allow, like reversing back over the snake body (e.g. from right to left). In other words, if the snake is moving vertically and the player wants to change the direction, it has to go horizontally first - you can't go directly from up to down or from left to right.

Next up is a switch statement, where we check which key was pressed. Here we check if one of the arrow keys (Up, Down, Left, Right) were pressed - if so, they are allowed to change the direction of the snake, unless the change is physically impossible, as described above. Also notice that I have added a check for the Space key: It will call the StartNewGame() method, to allow the player to choose when the game is started, instead of just starting it automatically. It will also allow the player to start a new game when the previous game has ended.

At the end of the method, we check if the direction has changed in comparison to the original direction - if it has, we call the MoveSnake() method, so that the change is reflected immediately.

We previously added a call to the StartNewGame() method in the Window_ContentRendered event - you can now remove this and instead start the game by pressing the Space key. Now lo and behold, the snake can be controlled - it's now close to being an actual game and not just an animated snake!


In this article, we added some pretty important functionality to our SnakeWPF implementation: Control of the snake! However, if you try to play it, you will notice that we still need one very important aspect, because the snake is currently disappearing out of the wall boundaries and it refuses to eat the food even when you hit it. In other words, we need to add some collision detection! More on that in the next article.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!