3. Movement for the player
In this first approach to the movement for the player, we will move a letter (the symbol which represents our player) in the screen. We will use "standard keys" first, and then we will improve it so the arrow keys can be used.
So... What's new?
- We are going to be able to move the character using keys as WASD (W = up, S = down, A = left, D = right). The keys will be read as text (strings). That means that we will need to press Enter after each of these keys.
- We will use abbreviated expressions such as "x++;" to increase the value of the coordinate x (horizontal) or "y--;" to decrease Y (vertical).
The full source might be:
/* First mini-console-game skeleton Version D: player movement */ using System; public class Game01c { public static void Main() { int x=40, y=12; string key; // Game Loop while( 1 == 1 ) { // Draw Console.Clear(); Console.SetCursorPosition(x, y); Console.Write("C"); // Read keys and calculate new position key = Console.ReadLine(); if (key == "a") x = x - 1; // Move left if (key == "d") x = x + 1; // Move right if (key == "w") y = y - 1; // Move up if (key == "s") y = y + 1; // Move down // Move enemies and environment // TO DO // Collisions, lose energy or lives, etc // TO DO // Pause till next fotogram // TO DO } } }
Which would look like this:
But having to press Enter after each key... is not very friendly. We can improve it if we access the keyboard directly, using "Readkey" instead of "ReadLine", this way:
/* First mini-console-game skeleton Version E: player movement using arrows */ using System; public class Game01e { public static void Main() { int x=40, y=12; ConsoleKeyInfo userKey; // Game Loop while( 1 == 1 ) { // Draw Console.Clear(); Console.SetCursorPosition(x, y); Console.Write("C"); // Read keys and calculate new position userKey = Console.ReadKey(false); if(userKey.Key == ConsoleKey.RightArrow) x++; if(userKey.Key == ConsoleKey.LeftArrow) x--; if(userKey.Key == ConsoleKey.DownArrow) y++; if(userKey.Key == ConsoleKey.UpArrow) y--; // Move enemies and environment // TO DO // Collisions, lose energy or lives, etc // TO DO // Pause till next fotogram // TO DO } } }
Which would look more natural:
Suggested exercise: This version of the game fails when the symbol is moved beyond the screen limits (on the right, left or top). Correct it.