/// <summary> /// Can return null!!! /// </summary> /// <param name="world"></param> /// <param name="row"></param> /// <param name="column"></param> /// <returns></returns> private string whatItIs(World world, int row, int column) { Apple apple = null; while (apple == null) { apple = world.GetApple(); } GroupObj[] wObjects = world.Objects.ToArray(); if (apple.Parts[0].Row == row && apple.Parts[0].Column == column) { return("apple"); } foreach (GroupObj gObj in wObjects) { if (gObj.GetType() == new Wall(null).GetType()) { if (gObj.Parts[0].Row == row && gObj.Parts[0].Column == column) { return("wall"); } } } Snake snake = world.GetSnake(); foreach (Obj part in snake.Parts) { if (part.GetType() != new Head().GetType() && part.Row == row && part.Column == column) { return("snake"); } } return("nothing"); }
public void Main() { int gameFieldRow = 40; int uiFieldRow = 5; int gameFieldColumn = 40; int uiFieldColumn = 0; int wallLength = 1; int gameSpeed = 50; //low - means faster ConsoleWindow console = new ConsoleWindow (gameFieldRow + uiFieldRow + wallLength * 2, gameFieldColumn + uiFieldColumn + wallLength * 2, "ASCII Snake"); while (true) { World world = new World(); world.Objects.Add(createSnake(gameFieldRow, uiFieldRow, gameFieldColumn, uiFieldColumn)); foreach (Wall wall in createWalls(gameFieldRow, uiFieldRow, gameFieldColumn, uiFieldColumn)) { world.Objects.Add(wall); } createApple(gameFieldRow, uiFieldRow, gameFieldColumn, uiFieldColumn, wallLength, console, world); CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; checkKeyboardAsync(console, world, world.GetSnake(), token); while (console.WindowUpdate()) { Thread.Sleep(gameSpeed); Snake snake = world.GetSnake(); if (snake != null) { snake.Move(console.GetKey()); } GroupObj thatContactWithSnake = world.WithWhatSnakeIsContact(); if (thatContactWithSnake != null) { if (thatContactWithSnake.GetType() == new Apple(null).GetType()) { world.Objects.Remove(world.GetApple()); snake.Lengthen(); } else if ((thatContactWithSnake.GetType() == new Wall(null).GetType())) { break; } else if (thatContactWithSnake.GetType() == new Snake().GetType()) { break; } } if (!world.IsAppleExist()) { createApple(gameFieldRow, uiFieldRow, gameFieldColumn, uiFieldColumn, wallLength, console, world); } Renderer.Render(console, world.Objects); } cts.Cancel(); if (!console.WindowUpdate()) { break; } } }