Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace CSLight
- {
- public class Program
- {
- private const char WallChar = '#';
- private const char EmptyChar = ' ';
- private const char PlayerChar = 'P';
- private const ConsoleKey MoveUpKey = ConsoleKey.W;
- private const ConsoleKey MoveDownKey = ConsoleKey.S;
- private const ConsoleKey MoveLeftKey = ConsoleKey.A;
- private const ConsoleKey MoveRightKey = ConsoleKey.D;
- private const ConsoleKey ExitKey = ConsoleKey.Q;
- public static void Main()
- {
- char[,] map = {
- { '#', '#', '#', '#', '#', '#', '#', '#', '#', '#' },
- { '#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#' },
- { '#', ' ', '#', ' ', '#', ' ', '#', '#', ' ', '#' },
- { '#', ' ', '#', ' ', ' ', ' ', ' ', '#', ' ', '#' },
- { '#', ' ', '#', '#', '#', '#', ' ', '#', ' ', '#' },
- { '#', ' ', ' ', ' ', ' ', ' ', ' ', '#', ' ', '#' },
- { '#', '#', '#', '#', '#', '#', '#', '#', '#', '#' }
- };
- int playerX = 1, playerY = 1;
- bool isRunning = true;
- while (isRunning)
- {
- DrawMap(map);
- DrawPlayer(playerX, playerY);
- ReadInput(ref isRunning, out int deltaX, out int deltaY);
- MovePlayer(map, ref playerX, ref playerY, deltaX, deltaY);
- }
- }
- private static void DrawMap(char[,] map)
- {
- Console.Clear();
- for (int y = 0; y < map.GetLength(0); y++)
- {
- for (int x = 0; x < map.GetLength(1); x++)
- {
- Console.Write(map[y, x] + " ");
- }
- Console.WriteLine();
- }
- }
- private static void DrawPlayer(int playerX, int playerY)
- {
- Console.SetCursorPosition(playerX * 2, playerY);
- Console.Write(PlayerChar);
- }
- private static void ReadInput(ref bool isRunning, out int deltaX, out int deltaY)
- {
- deltaX = 0;
- deltaY = 0;
- switch (Console.ReadKey(true).Key)
- {
- case MoveUpKey: deltaY = -1; break;
- case MoveDownKey: deltaY = 1; break;
- case MoveLeftKey: deltaX = -1; break;
- case MoveRightKey: deltaX = 1; break;
- case ExitKey: isRunning = false; break;
- }
- }
- private static void MovePlayer(char[,] map, ref int playerX, ref int playerY, int deltaX, int deltaY)
- {
- int newX = playerX + deltaX;
- int newY = playerY + deltaY;
- if (CanMoveTo(map, newX, newY))
- {
- playerX = newX;
- playerY = newY;
- }
- }
- private static bool CanMoveTo(char[,] map, int x, int y)
- {
- return x >= 0 && x < map.GetLength(1) &&
- y >= 0 && y < map.GetLength(0) &&
- map[y, x] != WallChar;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement