public void Tick(object o, EventArgs eventArgs) { try { mainTimer.Interval = 100 - GameContext.CurrentSettings.Speed; var bitmap = new Bitmap(drawingPanel.Width, drawingPanel.Height); var graphics = Graphics.FromImage(bitmap); Snake.Tick(graphics); if (Apple == null) { Apple = new Apple(Snake); } else { if (Snake.Head.HasBlockCollision(Apple)) { Snake.EatAppple(); EatenAppleCount++; if (Levels.Level.Contains(EatenAppleCount)) { GameContext.CurrentSettings.Speed += 5; } Apple = null; } } Drawer.Draw(graphics, new ObjectPaint <IDrawable> { Object = Snake, Brush = null }, new ObjectPaint <IDrawable> { Object = Apple, Brush = GameContext.AppleBrush }); drawingPanel.Image = bitmap; } catch (CollisionException) { mainTimer.Stop(); GameEndLabel.Text = $@"Score: {EatenAppleCount * GameContext.PointPerApple}"; GameEndLabel.Visible = true; GameContext.GameEnded = true; } }
public void defaultValues() { TheSnake = new PlayerSnake(1); TheApple = new Apple(); gameMap = new Place[PlayRows, PlayColumns]; for (int i = 0; i < PlayColumns; i++) { for (int j = 0; j < PlayRows; j++) { gameMap[i, j] = new Place(new Position(i, j)); } } StartButtonClicked = false; applesEaten = 0; }
public void repositionApple(Apple apple) { var temp = map.kép.GetPixel(apple.X * map.mapUnit + 1, apple.Y * map.mapUnit + 1); for (int i = 0; i < appleList.Count; i++) { while (!map.kép.GetPixel(apple.X * map.mapUnit + 1, apple.Y * map.mapUnit + 1).Equals(Color.White) && appleList[i].equals(apple) && appleList[i] != apple) { map.teliNegyzet(apple.X, apple.Y, Color.White); map.uresNegyzet(apple.X, apple.Y); apple.X = rnd1.Next(map.mapSize); apple.Y = rnd1.Next(map.mapSize); map.teliNegyzet(apple.X, apple.Y, apple.color); } } }
/// <summary> /// Can return null!!! /// </summary> /// <returns></returns> public Apple GetApple() { Apple example = new Apple(null); GroupObj[] wObjects = Objects.ToArray(); foreach (GroupObj checkObj in wObjects) { if (checkObj.GetType() == example.GetType()) { return((Apple)checkObj); } } return(null); }
public void changeDirection(Apple apple) { int Step = (int)a[0]; if (a.Count > 1) { Step = (int)a[1]; } Point pStep = ConvertToPoint(Step); if (!isMe(pStep) && !isWall(pStep)) { // go right if ((pStep.X - positionX) > 0) { direction = 1; } //go left if ((pStep.X - positionX) < 0) { direction = 3; } //go up if ((pStep.Y - positionY) < 0) { direction = 0; } //go down if ((pStep.Y - positionY) > 0) { direction = 2; } } else { killSnake = true; } }
private Apple createApple(int gameFieldRow, int uiFieldRow, int gameFieldColumn, int uiFieldColumn, int wallLength, ConsoleWindow console, World world) { Apple apple = new Apple(null); while (true) { int perhapsAppleRow = new Random().Next(uiFieldRow + wallLength, console.Rows - wallLength); int perhapsAppleColumn = new Random().Next(uiFieldColumn + wallLength, console.Cols - wallLength); apple = new Apple(new AppleObj(perhapsAppleRow, perhapsAppleColumn)); if (world.IsEmptyCell(perhapsAppleRow, perhapsAppleColumn)) { world.Objects.Add(apple); break; } } return(apple); }
/// <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 bool CollideswithElements(Snake snake, Apple apple) { if (this.RockCoords.EqualCoords(apple.AppleCoords)) { for (int i = 0; i < snake.SnakeBody.Count; i++) { if (this.RockCoords.EqualCoords(snake.SnakeBody[i])) { for (int y = 0; y < this.AllRocks.Count; y++) { if (this.RockCoords.EqualCoords(this.AllRocks[y])) { return(true); } } } } } this.AllRocks.Add(new Coords( this.RockCoords.x, this.RockCoords.y)); return(false); }
public Graphics(int sizeX, int sizeY, Snake snake, Apple apple) { this.sizeX = sizeX; this.sizeY = sizeY; this.snake = snake; this.apple = apple; gameField = new string[sizeX, sizeY]; for (int x = 0; x < sizeX; x++) { for (int y = 0; y < sizeY; y++) { if (x == 0 || y == 0 || x == sizeX - 1 || y == sizeY - 1) { gameField[x, y] = "*"; } else { gameField[x, y] = " "; } } } }
public bool Run() { while (GameRunning) { if (GameMode == GameMode.SinglePlayer) { if (Snake.CheckBoardCollision(Board)) { GameRunning = false; this.Winner = "Someone Else"; break; } if (Snake.CheckTailCollision()) { GameRunning = false; this.Winner = "Someone Else"; break; } } //-------------------------------------------- // Check for collision with tail and board //-------------------------------------------- if (GameMode == GameMode.SnakeVsApple) { if (Snake.CheckBoardCollision(Board)) { GameRunning = false; this.Winner = "Apple"; break; } if (Snake.CheckTailCollision()) { GameRunning = false; this.Winner = "Apple"; break; } } else if (GameMode == GameMode.SnakeVsSnake) { //-------------------------------------------- // Check for collision on Snake Player Two //-------------------------------------------- if (SnakePlayerTwo.CheckBoardCollision(Board)) { GameRunning = false; this.Winner = "Player 1"; break; } if (SnakePlayerTwo.CheckTailCollision()) { GameRunning = false; this.Winner = "Player 1"; break; } if (SnakePlayerTwo.CheckSnakeCollision(Snake)) { GameRunning = false; this.Winner = "Player 1"; break; } //-------------------------------------------- // Check for collision with other Snake //-------------------------------------------- //if (Snake.CheckSnakeCollision(SnakePlayerTwo)) //{ // GameRunning = false; // this.Winner = "Player 2"; // break; //} } //-------------------------------------------- // Getting movement direction //-------------------------------------------- if (Console.KeyAvailable) { Direction = Joystick.SetKeyDirection(SnakeDirection); if (Direction == KeyDirection.Up || Direction == KeyDirection.Down || Direction == KeyDirection.Left || Direction == KeyDirection.Right) { SnakeDirection = Direction; } else { AppleDirection = Direction; } } //-------------------------------------------- // Eating of the apple //-------------------------------------------- if (GameMode == GameMode.SnakeVsApple) { SnakeEnergy = Snake.GetEnergy(); IsFoodEaten = Snake.Eat(Apple); } else if (GameMode == GameMode.SinglePlayer) { IsFoodEaten = Snake.Eat(Food); } else if (GameMode == GameMode.SnakeVsSnake) { OnePlayerFoodIsEaten = Snake.Eat(Food); TwoPlayerFoodIsEaten = SnakePlayerTwo.Eat(Food); if (OnePlayerFoodIsEaten) { Score++; IsFoodEaten = true; } if (TwoPlayerFoodIsEaten) { TwoPlayerScore++; IsFoodEaten = true; } } Apple.EraseOldApple(); if (GameMode == GameMode.SnakeVsApple) { Snake.Move(SnakeDirection, IsFoodEaten); AppleDirection = Apple.Move(AppleDirection); } else if (GameMode == GameMode.SnakeVsSnake) { SnakeDirectionPlayerTwo = SnakePlayerTwo.TranslateAppleDirectionToSnake(AppleDirection, SnakeDirectionPlayerTwo); Snake.Move(SnakeDirection, OnePlayerFoodIsEaten); SnakePlayerTwo.Move(SnakeDirectionPlayerTwo, TwoPlayerFoodIsEaten); } else if (GameMode == GameMode.SinglePlayer) { Snake.Move(SnakeDirection, IsFoodEaten); } if (IsFoodEaten) { if (GameMode == GameMode.SnakeVsApple) { Apple.LoseLife(); Apple.MakeFood(BoardWidth, BoardHeight); Energy = Apple.GetEnergy(); Snake.GetEnergyFromApple(Energy); } else if (GameMode == GameMode.SnakeVsSnake) { Food.MakeFood(BoardWidth, BoardHeight); IsFoodEaten = false; } else { Score++; Food.MakeFood(BoardWidth, BoardHeight); } } //-------------------------------------------- // Drawing the graphics in both modes //-------------------------------------------- Snake.Draw("Green"); //-------------------------------------------- // Drawing different for Two vs One Player mode //-------------------------------------------- if (GameMode == GameMode.SnakeVsApple) { Apple.RottTheApple(); Energybar.Draw(BoardHeight, SnakeEnergy); Snake.LoseEnergy(); Apple.Draw(); Apple.DrawLifes(BoardHeight); } else if (GameMode == GameMode.SnakeVsSnake) { SnakePlayerTwo.Draw("Magenta"); Food.Draw(); } else { Food.Draw(); ShowScore(Score, BoardHeight); } if (SnakeEnergy < 1 && GameMode == GameMode.SnakeVsApple) { this.GameRunning = false; this.Winner = "Apple"; } if (Apple.GetLifes() < 1 && GameMode == GameMode.SnakeVsApple) { this.GameRunning = false; this.Winner = "Snake"; } //-------------------------------------------- // Timer for loop //-------------------------------------------- Thread.Sleep(100 - Speed); } Console.Clear(); Console.ForegroundColor = ConsoleColor.White; GameOver(this.Winner); bool playAgain = AskIfPlayAgain(); return(playAgain); }
static void Main(string[] args) { var game = new Game(); var apple = new Apple(); _window = new Window(3) { Title = "Snake" }; _window.OnKeyDown = key => { switch (key) { case ConsoleKey.RightArrow: if (game.Paused) { break; } if (snake.Orientation != "left") { snake.Orientation = "right"; } break; case ConsoleKey.LeftArrow: if (game.Paused) { break; } if (snake.Orientation != "right") { snake.Orientation = "left"; } break; case ConsoleKey.UpArrow: if (game.Paused) { break; } if (snake.Orientation != "down") { snake.Orientation = "up"; } break; case ConsoleKey.DownArrow: if (game.Paused) { break; } if (snake.Orientation != "up") { snake.Orientation = "down"; } break; case ConsoleKey.Escape: Console.WriteLine("Exit"); Environment.Exit(0); break; case ConsoleKey.P: if (game.Ended) { break; } if (game.Paused) { game.Resume(); break; } _window.Invoke(() => { _window.Screen.Text(205, 8, "Paused"); }); game.Pause(); break; case ConsoleKey.S: if (!game.Started || !game.Ended) { game.Start(); } break; case ConsoleKey.B: if (!game.Started) { snake.SetColors("#0000ff", "#ffff00"); } break; case ConsoleKey.O: if (!game.Started) { snake.SetColors("#ff9900", "#ffcc00"); } break; default: return; } }; _window.OnReady = window => { window.Invoke(() => { _window.Screen.SetColor("#33cc33"); _window.Screen.Rectangle(0, 0, 200, 200); _window.Screen.SetColor("#669999"); _window.Screen.Rectangle(200, 0, 120, 200); _window.Screen.SetColor("#000"); _window.Screen.Rectangle(200, 0, 2, 200); _window.Screen.SetColor("#000"); _window.Screen.Text(200 / 2 - 40, 200 / 2 - 20, "Press \"S\" to start the game"); _window.Screen.Text(205, 10, "Press \"B\" for Blue Snake"); _window.Screen.Text(205, 15, "Press \"O\" for Orange Snake"); }); snake = new Snake(); game.OnTick = () => { if (snake.CheckForCol()) { game.Stop(); window.Invoke(() => { _window.Screen.SetColor("#ff9900"); _window.Screen.Rectangle(75, 45, 60, 60); _window.Screen.SetColor("#000"); _window.Screen.Rectangle(80, 50, 50, 50); _window.Screen.SetColor("#FFF"); _window.Screen.Text(90, 67, "GAME OVER"); _window.Screen.Text(84, 74, "Press \"ESC\" to"); _window.Screen.Text(93, 79, "End Game"); }); } window.Invoke(() => { if (game.Ended) { return; } _window.Screen.SetColor("#33cc33"); _window.Screen.Rectangle(0, 0, 200, 200); apple.Draw(Random, _window.Screen, snake.Parts); if (apple.CheckIfEat(_window.Screen, snake.Parts)) { snake.AddPart(); snake.AddPart(); Score += 1; } snake.Draw(_window.Screen); _window.Screen.SetColor("#669999"); _window.Screen.Rectangle(200, 0, 120, 200); _window.Screen.SetColor("#000"); _window.Screen.Rectangle(200, 0, 2, 200); _window.Screen.SetColor("#000"); _window.Screen.Text(205, 2, $"Score: {Score}"); }); }; }; _window.Load(); }
public void Eat(Apple apple) { Length++; }
public void Update(Coords direction, Apple apple, Rocks rock) { for (int i = this.SnakeBody.Count - 1; i > 0; i--) { this.SnakeBody[i].x = this.SnakeBody[i - 1].x; this.SnakeBody[i].y = this.SnakeBody[i - 1].y; } this.SnakeBody[0].x += direction.x; this.SnakeBody[0].y += direction.y; ////to end if snake hits a wall //if (snakeBody[0].x<1|| // snakeBody[0].x>Console.WindowWidth|| // snakeBody[0].y<1|| // snakeBody[0].y>Console.WindowHeight) //{ // isGameOver = true; //} //to pass through walls if (this.SnakeBody[0].x == Console.BufferWidth - 2) { this.SnakeBody[0].x = 2; } if (this.SnakeBody[0].y == Console.BufferHeight - 2) { this.SnakeBody[0].y = 2; } if (this.SnakeBody[0].x == 1) { this.SnakeBody[0].x = Console.BufferWidth - 3; } if (this.SnakeBody[0].y == 1) { this.SnakeBody[0].y = Console.BufferHeight - 3; } // apple collision if (this.SnakeBody[0].EqualCoords(apple.AppleCoords)) { this.EatApple(apple); } // rock collision for (int i = 0; i < rock.AllRocks.Count; i++) { if (this.SnakeBody[0].EqualCoords(rock.AllRocks[i])) { isGameOver = true; break; } } // tail collison for (int i = 1; i < this.SnakeBody.Count; i++) { if (this.SnakeBody[0].EqualCoords(this.SnakeBody[i])) { isGameOver = true; break; } } }
protected void Initialize() { apple = new Apple() { x = 3, y = 3 }; snake = new Snake() { x = 10, y = 10, dy = 1 }; rng = new Random(); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(Constants.FRAMES_PER_SECOND, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, desc, out device, out swapChain); d2dFactory = new SharpDX.Direct2D1.Factory(); int width = form.ClientSize.Width; int height = form.ClientSize.Height; // Ignore all windows events factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); renderView = new RenderTargetView(device, backBuffer); Surface surface = backBuffer.QueryInterface <Surface>(); d2dRenderTarget = new RenderTarget(d2dFactory, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))); var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle() { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, width - 128 * 2, height - 128 * 2) }); var solidColorBrush = new SolidColorBrush(d2dRenderTarget, Color.White); var directInput = new DirectInput(); keyboard = new Keyboard(directInput); keyboard.Acquire(); apple.Initialize(d2dRenderTarget, Color.Red); snake.Initialize(d2dRenderTarget, Color.Green); }
static void Main(string[] args) { ConsoleKeyInfo cki = new ConsoleKeyInfo(); Field theField = new Field(); Fruit theFruit = new Apple(theField.GetFieldSize()); Game theGame = new Game(theField.GetFieldSize()); Snake snake = new Snake(new ConcreteStateDown()); theGame.DisplayWelcome(); snake.Request(); theField.SetField(); theFruit.CreateFruit(snake.GetXPosition(), snake.GetYPosition(), snake.GetSnakeBodyX(), snake.GetSnakeBodyY()); //main game play loop while (theGame.GetGameStatus() == true && cki.Key != ConsoleKey.Q) //Q can quit while game is in play { //if the Fruit has been eaten access this if block if (theFruit.GetIsEaten()) { theGame.UpdateGameSpeed(theFruit.GetUpdateSpeed()); snake.AddSnakeBody(); snake.UpdateAddToBody(); theGame.UpdateBiteCount(); theGame.SetGameScore(theFruit.GetFruitPoints()); if (theGame.GetBiteCount() % 5 == 0) { theFruit = new Berry(theField.GetFieldSize()); } else if (theGame.GetBiteCount() % 3 == 0) { theFruit = new Banana(theField.GetFieldSize()); } else { theFruit = new Apple(theField.GetFieldSize()); } theFruit.CreateFruit(snake.GetXPosition(), snake.GetYPosition(), snake.GetSnakeBodyX(), snake.GetSnakeBodyY()); theFruit.SetIsEaten(false); } //meta data theGame.DisplayGameScore(); theGame.DisplaySnakeBodyCount(snake.GetSnakeBodyCount()); //this while loop runs while a key HAS not been pressed && //the game status is still true meaning the snake has not died && //the fruit has not been eaten yet while (Console.KeyAvailable == false && theGame.GetGameStatus() == true && theFruit.GetIsEaten() == false) { //the game sleeps depending on the game speed //this is what produces the speed of the snake as it gets faster Thread.Sleep(theGame.GetGameSpeed()); snake.Request(); theGame.SetGameStatus(theField.DetectWallCollisions(snake.GetXPosition(), snake.GetYPosition()), snake.DetectBodyCollision()); theFruit.DetectFruitCollision(snake.GetXPosition(), snake.GetYPosition()); theGame.DisplaySnakePosition(snake.GetXPosition(), snake.GetYPosition()); //The Berry fruit has a time limit on it while the other fruits do not //therefore if it is a Berrt run this if block if (theFruit.GetIsBerry()) { theFruit.UpdateBerryMoves(); if (theFruit.GetBerryMoves() <= 0) { theFruit.RemoveOldFruit(); theFruit = new Apple(theField.GetFieldSize()); theFruit.CreateFruit(snake.GetXPosition(), snake.GetYPosition(), snake.GetSnakeBodyX(), snake.GetSnakeBodyY()); } } //with each iteration in this loop the snake must be drawn snake.DrawSnake(); } //when the while loop is exited due to a key press, that key needs to be read if (!theFruit.GetIsEaten() && theGame.GetGameStatus()) { cki = Console.ReadKey(true); snake.ReadKeyInput(cki); } //if the Game Status is false meaning the snake has died //give the user the choice of replaying //if they choose to the game is reset if (!theGame.GetGameStatus()) { theGame.DisplayReplayMessage(); theGame.GetReplayResponse(); if (theGame.GetReset()) { theFruit.RemoveOldFruit(); snake.RemoveSnakeBody(); theField.FixWall(snake.GetYPosition(), snake.GetXPosition()); snake.ResetSnake(new ConcreteStateDown(), theGame.GetReset()); theFruit = new Apple(theField.GetFieldSize()); theFruit.CreateFruit(snake.GetXPosition(), snake.GetYPosition(), snake.GetSnakeBodyX(), snake.GetSnakeBodyY()); } } } theGame.DisplayEnd(); }
public void ApplePlaatsen(Apple apple) { speelveld[apple.Coordinaten.xPos][apple.Coordinaten.yPos] = apple.AppleBody; }
public void BeweegSlang(Slang slang, Apple appel) { int repeat = 0; do { ConsoleKeyInfo keyinfo = Console.ReadKey(true); Console.Clear(); switch (keyinfo.Key) { case ConsoleKey.RightArrow: for (var i = 0; i < breedteSpeelveld; i++) { if (slang.Coordinaten.yPos == breedteSpeelveld - 1) { throw new Exception("Out of bounds!"); } } if (speelveld[slang.Coordinaten.xPos][slang.Coordinaten.yPos] == "O") { slang.Score += appel.Point; ApplePlaatsen(Apple.RandomApple()); } Console.Clear(); speelveld[slang.Coordinaten.xPos][slang.Coordinaten.yPos - 1] = " "; //speelveld[slang.Coordinaten.xPos + 1][slang.Coordinaten.yPos - 1] = " "; //speelveld[slang.Coordinaten.xPos - 1][slang.Coordinaten.yPos - 1] = " "; slang.Coordinaten.yPos++; break; case ConsoleKey.LeftArrow: for (var i = 0; i < breedteSpeelveld; i++) { if (slang.Coordinaten.xPos == 0) { throw new Exception("Out of bounds!"); } } Console.Clear(); speelveld[slang.Coordinaten.xPos][slang.Coordinaten.yPos + 1] = " "; //speelveld[slang.Coordinaten.xPos - 1][slang.Coordinaten.yPos + 1] = " "; //speelveld[slang.Coordinaten.xPos + 1][slang.Coordinaten.yPos + 1] = " "; slang.Coordinaten.yPos--; break; case ConsoleKey.UpArrow: for (var i = 0; i < hoogteSpeelveld; i++) { if (slang.Coordinaten.yPos == hoogteSpeelveld - 1) { throw new Exception("Out of bounds!"); } } Console.Clear(); speelveld[slang.Coordinaten.xPos + 1][slang.Coordinaten.yPos] = " "; //speelveld[slang.Coordinaten.xPos + 1][slang.Coordinaten.yPos - 1] = " "; //speelveld[slang.Coordinaten.xPos + 1][slang.Coordinaten.yPos + 1] = " "; slang.Coordinaten.xPos--; break; case ConsoleKey.DownArrow: for (var i = 0; i < hoogteSpeelveld; i++) { if (slang.Coordinaten.yPos == 0) { throw new Exception("Out of bounds!"); } } Console.Clear(); speelveld[slang.Coordinaten.xPos - 1][slang.Coordinaten.yPos] = " "; //speelveld[slang.Coordinaten.xPos - 1][slang.Coordinaten.yPos - 1] = " "; //speelveld[slang.Coordinaten.xPos - 1][slang.Coordinaten.yPos + 1] = " "; slang.Coordinaten.xPos++; break; } repeat = 1; } while (repeat == 0); }
public void eat(Apple apple) { body.Add(apple.pos); }