public void SnakeCreationInDefaultPositionWithHead() { var snake = new Snake(0, 0); Assert.IsTrue(snake.Head.X == 0); Assert.IsTrue(snake.Head.Y == 0); Assert.IsNull(snake.Head.Next); }
public void CreateSnakeAtOrigin() { var snake = new Snake(gridSize, Color.Green); Assert.AreEqual(Vector2D.Half, snake.Get<Body>().HeadPosition); Assert.AreEqual(new Vector2D(startPosition, startPosition), snake.Get<Body>().BodyParts[0].TopLeft); }
public Snake() { listPieces = new ArrayList (); instance = this; }
public void Init() { m_levelData = new GameLevel(); m_levelData.LoadFromSource(new Level1()); m_snake = GameObject.Find("SnakeObject").GetComponent<Snake>(); m_headZ = 0; m_goldNum = 0; }
// Use this for initialization void Start() { s_snake = this; defaultDirection = Direction.Left; body = new List<GameObject> (); for (int i = 0; i < defaultBodyParts; ++i) { createPart(i, defaultDirection, new Vector3(i,0,0)); } }
public void turnPlayer( Snake.Direction dir ) { if( GameManager.isGameOver ) return; bool hasTurned = Player.TurnTo(dir); if( !hasTurned ) return; stopStepping(); NotifySteppers(); startStepping(); }
public void SnakeEatAndGrowth() { var snake = new Snake(0, 0); snake.Move(); snake.Eat(); Assert.IsTrue(snake.Head.X == 0); Assert.IsTrue(snake.Head.Y == 1); Assert.IsTrue(snake.Tail.X == 0); Assert.IsTrue(snake.Tail.Y == 0); }
public void SnakeMoveInEachDirectionCorrect(MoveDirection changeDirection, int resultX, int resultY) { var snake = new Snake(1, 1); snake.ChangeDirection(changeDirection); snake.Move(); Assert.IsTrue(snake.Head.X == resultX); Assert.IsTrue(snake.Head.Y == resultY); Assert.IsNull(snake.Head.Next); }
public Model() { this.gameStatus = GameStatus.Stopping; this.rnd = new Random(); this.snake = new Snake(); this.apples = new List<Apple>() { new Apple(rnd.Next(2, 29), rnd.Next(2, 34)), new Apple(rnd.Next(2, 29), rnd.Next(2, 34)), new Apple(rnd.Next(2, 29), rnd.Next(2, 34)), new Apple(rnd.Next(2, 29), rnd.Next(2, 34)), new Apple(rnd.Next(2, 29), rnd.Next(2, 34)), new Apple(rnd.Next(2, 29), rnd.Next(2, 34))}; }
void device_StartButtonPressed(object sender, System.EventArgs e) { DisplayManager.Clear(); if (snake != null) { snake.Dispose(); snake = null; } snake = new Snake(); DisplayManager.Show(snake.Head); ShowBait(); }
public override void Hit(Snake snake) { if (!cellData.Hit(snake)) return; grid.GetComponent<MeshFilter>().mesh = ResManager.m_gridDarkBlockMesh; if (decal != null) ResManager.ReturnDecalObject(decal); decal = ResManager.CreateDecalObject(new Vector3(cellData.x + 0.5f, 0.705f, cellData.z + 0.5f), ResManager.DECAL_HIT); decal.transform.localScale = new Vector3(0.5f, 1, 0.5f); GameRuntime.ShakeCamera((new Vector3(0.2f, 0.4f, 1.0f)).normalized, 0.4f, 0.1f, 20); snake.SetSpeedTo(5, 10); }
void Initial() { snake = new Snake(5, 5, ConsoleColor.Green, "8"); for (int a = 0; a < boardBase.GetLength(0); a++) { for (int b = 0; b < boardBase.GetLength(1); b++) { boardBase[a, b] = new BoardPiece(ConsoleColor.DarkGreen, '0'); boardTmp[a, b] = new BoardPiece(ConsoleColor.DarkGreen, ' '); } } }
public void SnakeEatTwiceGrowthMoveAndChangeDirection() { var snake = new Snake(0, 0); snake.Move(); snake.Eat(); snake.Move(); snake.Eat(); snake.ChangeDirection(MoveDirection.Right); snake.Move(); Assert.IsTrue(snake.Head.X == 1); Assert.IsTrue(snake.Head.Y == 2); Assert.IsTrue(snake.Tail.X == 0); Assert.IsTrue(snake.Tail.Y == 1); }
public static void Init() { isActive = true; snake = new Snake(); food = new Food(); wall = new Wall(); snake.body.Add(new Point { x = 5, y = 10 }); //initial point of the head of the snake food.body.Add(new Point { x = 8, y = 15 });// The 1st position of the food //colors of the items food.color = ConsoleColor.Green; wall.color = ConsoleColor.White; snake.color = ConsoleColor.Yellow; Console.SetWindowSize(24, 32); }
static void Main(string[] args) { List<Point> snakePoints = new List<Point>(); int width = 50; int height = 25; Snake snake = new Snake(width, height); ConsoleRender render = new ConsoleRender(width, height); ConsoleKey key = new ConsoleKey(); while (key != ConsoleKey.Q && !snake.Dead) { if (Console.KeyAvailable) { ConsoleKeyInfo keyInfo = Console.ReadKey(true); key = keyInfo.Key; switch (key) { case ConsoleKey.RightArrow: snake.Right(); break; case ConsoleKey.LeftArrow: snake.Left(); break; case ConsoleKey.UpArrow: snake.Up(); break; case ConsoleKey.DownArrow: snake.Down(); break; default: break; } } render.displaySnake(snake.Move()); render.displayItem(snake.item); } if (snake.Dead) render.displayGameOver(); }
void Start() { exitButton = exitButton.GetComponent<Button>(); menuCanvas = menuCanvas.GetComponent<Canvas>(); uiCanvas = uiCanvas.GetComponent<Canvas>(); gamePausedCanvas = gamePausedCanvas.GetComponent<Canvas>(); playButton = playButton.GetComponent<Button>(); continueButton = continueButton.GetComponent<Button>(); continueText = continueText.GetComponent<Text>(); playText = playText.GetComponent<Text>(); snakeObject = GameObject.FindGameObjectWithTag("Snake"); snakeScript = snakeObject.GetComponent<Snake>(); backgroundObject = GameObject.FindGameObjectWithTag("Background"); addPortalScript = backgroundObject.GetComponent<AddPortal>(); GameObject startmenu = GameObject.FindGameObjectWithTag("Startmenu"); startMenuScript = startmenu.GetComponent<StartMenu>(); uiCanvas.enabled = false; }
public void setNext(Snake inside) { next = inside; } // setNext
public virtual void Hit(Snake snake) { cellData.Hit (snake); }
public override void Hit(Snake snake) { cellData.Hit (snake); }
// Main entry point. public static void Main(String[] args) { // Initialize the console routines and put us into the // "alternative" screen mode under Unix. Console.Clear(); // Turn off the cursor, if possible. Console.CursorVisible = false; // Set the terminal window's title. Console.Title = "DotGNU Snake!"; // Create the game object. Snake snake; if(args.Length > 0 && args[0] == "--monochrome") { snake = new Snake(true); } else { snake = new Snake(false); } // Draw the initial board layout. snake.DrawBoard(); // Install the timeouts that we need. snake.SetupTimers(); // Enter the main key processing loop. snake.MainLoop(); // Shut down the timers. snake.ShutdownTimers(); // Clear the screen to the default attributes before exiting. Console.CursorVisible = true; SetTextAttribute(ConsoleColor.Gray, ConsoleColor.Black); Console.Clear(); }
//{ // new Snake // { // ID=1, // Family=SnakeFamily.Viperidae, // CommonSpeciesName="Bob", // LengthInCentimeters=23M, // Venomous=true // }, // new Snake // { // ID=2, // Family=SnakeFamily.Colubridae, // CommonSpeciesName="Steve", // LengthInCentimeters=26M, // Venomous=true // } //}; public Snake Create(Snake snake) { _snakeList.Add(snake); return(snake); }
public abstract bool OnSnakeContact(Snake pSnake);
public void Setnext(Snake IN) { next = IN; }
public void SetNext(Snake snake) { next = snake; }
private Direction GetNewDirection() { var newDirection = Snake.Direccion; if (!Snake.IsOpositeDirection(Direction.Down) && IsMaxValue(AvailableMovesDown, AvailableMovesLeft, AvailableMovesUp, AvailableMovesRight)) { newDirection = Direction.Down; } if (!Snake.IsOpositeDirection(Direction.Left) && IsMaxValue(AvailableMovesLeft, AvailableMovesDown, AvailableMovesUp, AvailableMovesRight)) { newDirection = Direction.Left; } if (!Snake.IsOpositeDirection(Direction.Up) && IsMaxValue(AvailableMovesUp, AvailableMovesDown, AvailableMovesLeft, AvailableMovesRight)) { newDirection = Direction.Up; } if (!Snake.IsOpositeDirection(Direction.Right) && IsMaxValue(AvailableMovesRight, AvailableMovesDown, AvailableMovesLeft, AvailableMovesUp)) { newDirection = Direction.Right; } switch (newDirection) { case Direction.Down: if (LockingWayDown) { if (AvailableMovesLeft > 0 || AvailableMovesUp > 0 || AvailableMovesRight > 0) { AvailableMovesDown = -1; newDirection = GetNewDirection(); } } break; case Direction.Left: if (LockingWayLeft) { if (AvailableMovesDown > 0 || AvailableMovesUp > 0 || AvailableMovesRight > 0) { AvailableMovesLeft = -1; newDirection = GetNewDirection(); } } break; case Direction.Up: if (LockingWayUp) { if (AvailableMovesLeft > 0 || AvailableMovesDown > 0 || AvailableMovesRight > 0) { AvailableMovesUp = -1; newDirection = GetNewDirection(); } } break; case Direction.Right: if (LockingWayRight) { if (AvailableMovesLeft > 0 || AvailableMovesUp > 0 || AvailableMovesDown > 0) { AvailableMovesRight = -1; newDirection = GetNewDirection(); } } break; } return(newDirection); }
public SMSG_e_UpdateSnakeDirection(Snake snake, double direction) { this.Snake = snake; this.Direction = direction; }
public Engine(DrawManager drawManager, Snake snake) { this.drawManager = drawManager; this.snake = snake; }
public SnakeController(Snake snake) { this.snake = snake; }
//Player is about to finish this "level", and the game will generate another one. private void OnTriggerEnter(Collider other) { if (other.name == "Player" && open && !entered) { if (transform.parent.name != "StartingLevel") { //Add score depending on what the theme difficulty is if (Skins.levelTheme == Skins.Themes.RUINS) { GlobalStats.AddScore(150, other.transform.position); } else if (Skins.levelTheme == Skins.Themes.FACTORY) { GlobalStats.AddScore(250, other.transform.position); } else if (Skins.levelTheme == Skins.Themes.DUNGEON) { GlobalStats.AddScore(150, other.transform.position); } else { GlobalStats.AddScore(100, other.transform.position); } CoinObjective.CheckForObjective((int)CoinObjective.Objective.BEAT_THEMED_LEVELS, (int)Skins.levelTheme); } //Remove the arrow cube reference if it exists GameObject arrowObject = GameObject.Find("CubeArrow"); if (arrowObject) { arrowObject.GetComponent <LookAtCube>().RemoveRefernce(); } SoundManager.PlaySound(SoundManager.Sounds.ENTER_GATE); //Remove any obstacles so they stop with the damn spike trap sounds :P GameObject[] hazardsToKill = GameObject.FindGameObjectsWithTag("BurnableNotSolid"); for (int i = hazardsToKill.Length - 1; i >= 0; i--) { Destroy(hazardsToKill[i]); } //Ranzomide level theme if that is set Skins.CheckForRandomization(true); Snake snake = other.GetComponent <Snake>(); snake.IncreaseSpeed(); snake.lastSpawnPosition = transform.position; //Spawn in more level here. Despawn the oldest level, but not the one being exited. entered = true; LevelSpawner spawner = GameObject.Find("LevelSpawner").GetComponent <LevelSpawner>(); spawner.EndLevel(transform.position); } else if (other.tag == "Wall") //Alternatively if a level is spawned in, despawn any walls that would be in the way of the door. { Destroy(other.gameObject); } Debug.Log(other.tag); }
public MoveUpCommand(ref Snake Snake) : base(ref Snake) { }
// --------------------------------------------------------------------------------------------------- // DestroyInstance() // --------------------------------------------------------------------------------------------------- // Destroys the ScreenField instance // --------------------------------------------------------------------------------------------------- public void DestroyInstance() { print("Snake Instance destroyed"); instance = null; }
public void onSpecialFoodEated(Snake snake) { this.growSnakeBody(snake); _gui.updateScore(FoodType.SPECIAL); }
// Use this for initialization void Start() { enemy = gameObject.transform.parent.GetComponent <Enemy>(); snakeLogic = enemy.snakeLogic; }
public void Awake() { snake = GetComponent <Snake>(); }
private void RestartGame() { snake = null; Device.Stop(); }
// SpawnFood is called here so that it would be called before everything else (in handler) public void Setup(Snake snake) { this.snake = snake; SpawnFood(); }
public override void Solve(string filename) { this.LoadFiles(filename); int numTests = this.ReadInt(); for (int i = 1; i <= numTests; i++) { Console.WriteLine("Solving Case {0}", i); var line = this.ReadIntArr(); int numTurnActions = line[0]; int numRows = line[1]; int numCols = line[2]; var turnActions = new Dictionary<int, bool>(); for (int j = 0; j < numTurnActions; j++) { var lineStr = this.ReadLine().Split(' '); turnActions[int.Parse(lineStr[0])] = lineStr[1] == "L"; } var eatenFood = new HashSet<Point>(); int timeSinceLastEvent = 0; int timer = 1; var snake = new Snake(numRows, numCols); while (timer < 1e9) { if (timeSinceLastEvent >= numRows*2 && timeSinceLastEvent >= numCols*2) { // nothing has happened in a long time, so end break; } // try to move var newHead = snake.CalculateNextMove(); // eat if there is food bool hasFood = false; if ((newHead.X + newHead.Y) % 2 == 1) { // note that we keep track of the food AFTER it has been eaten, rather than before - as it takes too long to populate a list of uneaten food on the large board // large board = 1,000,000 * 1,000,000 cells = 1,000,000,000,000 cells / 2 = 500,000,000 food = TOO MUCH TO HANDLE var headPoint = new Point(newHead.X, newHead.Y); hasFood = !eatenFood.Contains(headPoint); eatenFood.Add(headPoint); if (hasFood) { timeSinceLastEvent = 0; } } // move the snake if (!snake.Step(newHead, hasFood)) { // WE DEAD break; } // do the input action if there is one for this second if (turnActions.ContainsKey(timer)) { bool turnLeft = turnActions[timer]; snake.DoTurn(turnLeft); timeSinceLastEvent = 0; } timeSinceLastEvent++; timer++; } this.Outfile.WriteLine("Case #{0}: {1}", i, snake.Length); } }
public StandardGame(Snake snake, Map map, GameRules gameRules, Reward reward, IDisplay display, int snakeSpeedInMilliseconds) : base(map, gameRules, reward, display, snakeSpeedInMilliseconds) { _snake = snake; }
public override void Hit(Snake snake) { if (!cellData.Hit(snake)) return; GameRuntime.ShakeCamera((new Vector3(0.2f, 0.4f, 1.0f)).normalized, 0.5f, 0.2f, 20); }
public void DisposeSnake() { var snake = new Snake(gridSize, Color.Green) { IsActive = false }; Assert.AreEqual(2, snake.Get<Body>().BodyParts.Count); snake.Dispose(); Assert.Throws<Entity.ComponentNotFound>(() => snake.Get<Body>()); }
public override void Hit(Snake snake) { if (!cellData.Hit(snake)) return; bonus.GetComponent<Gold>().Fly(); GameObject par = ParticleMan.PlayParticle("gfx/GoldSpark", new Vector3(cellData.x + 0.5f, 0.0f, cellData.z + 0.5f)); AdjustPos.AttachTo(par); SpriteCollect.CreateNew(new Vector3(cellData.x + 0.5f, 0.0f, cellData.z + 0.5f)); }
//Comparing performance of a circular linked list and circular array static void Q4() { void mainloop(object circ) { void addElement(MobileObject t) { // if the dataype is circular array, enqueue otherwise addback if (circ is DLinkedList) { (circ as DLinkedList).enqueue(t); } else if (circ is CircularArray <MobileObject> ) { (circ as CircularArray <MobileObject>).AddBack(t); } } Random random = new Random(); MobileObject temp; for (int i = 0; i < 2; i++) { for (int j = 0; j < 25; j++) { if (i == 0) { /*adding mobile objects to a linked list and * determinig the the value range of cat attributes*/ temp = new Cat("CatName", j + i * 25, new Position(100), /*To make Cat attribute values a float I used (float) * keyword, devided the values by 2 and added a floating point number.*/ (float)((random.NextDouble() / 2) + 0.5), //Leglength (float)((random.NextDouble() / 2) + 0.5), //Torsoheight (float)((random.NextDouble() / 2) + 0.5), //HeadLength (float)((random.NextDouble() / 2) + 0.5), //Taillength (float)((random.NextDouble() / 2) + 0.5)); //Mass } else { /*adding mobile objects to a linked list and * determinig the the value range of snake attributes*/ //Console.WriteLine("Adding Snake"); temp = new Snake("SnakeName", j + i * 25, new Position(100), /*To make length and radius values a float I used (float) * keyword, devided the values by 2 and added a floating point number.*/ (float)((random.NextDouble() / 2) + 0.5), //Length (float)((random.NextDouble() / 10) + 0.05), //Radius (float)((random.NextDouble() * 100) + 1), //Mass in kg random.Next(200, 301)); //Vertabrae } // dynamic add element depending on inputted datatype addElement(temp); } } } Stopwatch stopWatch; // initialize arrays holding loop information string[] types = new string[] { "CircularLinkedList", "CircularArray" }; int[] times = new int[] { 1, 5, 10 }; //for 1, 5, and 10 seconds // Run loop once for each datatype foreach (string type in types) { Console.WriteLine("Testing: {0}", type); // Run loop for each of the 3 times (1, 5, 10 seconds) foreach (int time in times) { // Start new stopWatch stopWatch = Stopwatch.StartNew(); // Initialize loop counter int count = 0; // Loop while stopwatch is less than time (in milliseconds for accuracy) while (stopWatch.ElapsedMilliseconds < time * 1000) { if (type == "CircularLinkedList") { mainloop(new DLinkedList()); } else if (type == "CircularArray") { mainloop(new CircularArray <MobileObject>(50)); } count++; } Console.WriteLine("Time: {0}s\t| Loop(s): {1}", time, count); } Console.WriteLine(""); } }
public GameRules(GameField gameField, Snake snake) { this.gameField = gameField; this.snake = snake; }
public SNPiece () { snake = Snake.getInstance ( ); // this.index = snake.getMyCellIndex (); // Debug.Log ("this.index:"+this.index); }
public void Run() { Console.OutputEncoding = Encoding.Unicode; field = new Field(10, 10); //field.UpdateValue(4, 0, "F"); //field.UpdateValue(3, 2, "F"); snake = new Snake(field, new Point(4, 4), 4); AlgorithmsAndDataStructures.Matrix.MatrixProblems.PrintMatrix(field.Points); _moveTimer = new Timer(500); _moveTimer.Elapsed -= OnTimerTick; _moveTimer.Elapsed += OnTimerTick; _fruitTimer = new Timer(5000); _fruitTimer.Elapsed -= OnFruitTimerTick; _fruitTimer.Elapsed += OnFruitTimerTick; _moveTimer.Start(); _fruitTimer.Start(); while (isValid) { ConsoleKeyInfo dir = Console.ReadKey(); string key = dir.KeyChar.ToString().ToUpper(); if (dir.Key == ConsoleKey.UpArrow) { key = "U"; } if (dir.Key == ConsoleKey.DownArrow) { key = "D"; } if (dir.Key == ConsoleKey.LeftArrow) { key = "L"; } if (dir.Key == ConsoleKey.RightArrow) { key = "R"; } if (string.Equals(key, "u", StringComparison.OrdinalIgnoreCase) || string.Equals(key, "d", StringComparison.OrdinalIgnoreCase) || string.Equals(key, "l", StringComparison.OrdinalIgnoreCase) || string.Equals(key, "r", StringComparison.OrdinalIgnoreCase)) { lock (_locker) { // prevent left when direction is right. if ((direction == "L" && key == "R") || (direction == "R" && key == "L")) { continue; } // prevent up when directioni is down and vice versa. if ((direction == "U" && key == "D") || (direction == "D" && key == "U")) { continue; } direction = key.ToUpper(); } } } }
public void Init(Snake _snake) { snake = _snake; bodySprite = GetComponent <SpriteRenderer>(); }
// Use this for initialization void Awake() { m_Snake = GetComponent <Snake>(); enabled = false; }
private void Awake() { snake = GameObject.Find("Snake").GetComponent <Snake>(); MaximumLengthDisplayer = GetComponent <Text>(); MaximumLengthOfSnake = snake.LengthOfSnake; }
/// <summary> /// Load graphics content for the game. /// </summary> public override void Activate(InputState input) { grid = new DrawableGrid(3); landscape = new Landscape(); effectSprites = new List<EffectSprite>(); //for (int i = 0; i < Main.backgroundLoops.Count; i++) //Main.backgroundLoops[i].Play(); scoreText = new IconText("", Main.sprites["points"], new Vector2(Main.windowSize.X / 10.0f, Main.windowSize.X / 10.0f), new Vector2(Main.windowSize.X / 6.0f, Main.windowSize.X / 12.0f), 0.5f, Color.Goldenrod, TextAlignment.Right); snake = new Snake(grid, Main.windowSize * 0.5f, this.snakeSpeed, this.startSnakeLength); landscape.AddComponent(snake); List<Type> snakeConditions = new List<Type>(); snakeConditions.Add(typeof(Mouse)); snakeConditions.Add(typeof(Rabbit)); snake.ScheduleCollisionHandling(snakeConditions); animals = new List<IDrawableGridAsset>(); for (int i = 0; i < 5; i++) this.PlaceAnimal(); ScreenManager.Game.ResetElapsedTime(); base.Activate(input); }
public void Delete(int ID) { Snake snakeToDelete = _snakeList.Find(s => s.ID == ID); _snakeList.Remove(snakeToDelete); }
// Use this for initialization void Start() { quitDialog = quitDialog.GetComponent<Canvas>(); //assigned actual game object to variable aboutCanvas = aboutCanvas.GetComponent<Canvas>(); levelsCanvas = levelsCanvas.GetComponent<Canvas>(); controlsCanvas = controlsCanvas.GetComponent<Canvas>(); controls1Canvas = controls1Canvas.GetComponent<Canvas>(); optionsCanvas = optionsCanvas.GetComponent<Canvas>(); menuCanvas = menuCanvas.GetComponent<Canvas>(); uiCanvas = uiCanvas.GetComponent<Canvas>(); gameOver = gameOver.GetComponent<Canvas>(); playButton = playButton.GetComponent<Button>(); continueButton = continueButton.GetComponent<Button>(); continueText = continueText.GetComponent<Text>(); exitButton = exitButton.GetComponent<Button>(); controlsButton = controlsButton.GetComponent<Button>(); optionsButton = optionsButton.GetComponent<Button>(); aboutButton = aboutButton.GetComponent<Button>(); levelsButton = levelsButton.GetComponent<Button>(); audioSource = GetComponents<AudioSource>(); musicSlider = musicSlider.GetComponent<Slider>(); soundSlider = soundSlider.GetComponent<Slider>(); snakeObject = GameObject.FindGameObjectWithTag("Snake"); snakeScript = snakeObject.GetComponent<Snake>(); backgroundObject = GameObject.FindGameObjectWithTag("Background"); addPortalScript = backgroundObject.GetComponent<AddPortal>(); lock1 = lock1.GetComponent<Text>(); level1 = level1.GetComponent<Button>(); lock2 = lock2.GetComponent<Text>(); level2 = level2.GetComponent<Button>(); lock3 = lock3.GetComponent<Text>(); level3 = level3.GetComponent<Button>(); lock4 = lock4.GetComponent<Text>(); level4 = level4.GetComponent<Button>(); continueText.enabled = false; continueButton.enabled = false; quitDialog.enabled = false; aboutCanvas.enabled = false; controlsCanvas.enabled = false; controls1Canvas.enabled = false; optionsCanvas.enabled = false; uiCanvas.enabled = false; gameOver.enabled = false; levelsCanvas.enabled = false; }
public GameStateBase(Game game, GameScreenController manager) : base(game, manager) { gameReference = (Snake)game; }
public GameInstance(int boardWidth, int boardHeight, int snakeSize, int seed) { Board = new Board(boardWidth, boardHeight, seed); Snake = new Snake(snakeSize, Board); }
/// <summary> /// Crée un nouveau fruit /// </summary> /// <param name="area">La zone de jeu, pour que le fruit soit créé dedans</param> /// <returns></returns> public Fruit CreateFruit(GameArea area, Snake snake) { //Random position Random randX = new Random(); Random randY = new Random(); int X = randX.Next(0, area.Width); int Y = randX.Next(0, area.Height); bool onSnake = false; do { onSnake = false; for (int i = 0; i < snake.BodyPosition.Count(); i++) { if (snake.BodyPosition[i].x == X && snake.BodyPosition[i].y == Y) { onSnake = true; X = randX.Next(0, area.Width); Y = randX.Next(0, area.Height); } } if (snake.HeadPosition.x == X && snake.HeadPosition.y == Y) { onSnake = true; X = randX.Next(0, area.Width); Y = randX.Next(0, area.Height); } }while (onSnake); // Random Color Random randColor = new Random(); int color = randColor.Next(1, 4); ConsoleColor randomColor; switch (color) { case 1: randomColor = ConsoleColor.Yellow; break; case 2: randomColor = ConsoleColor.Red; break; case 3: randomColor = ConsoleColor.Green; break; default: throw new Exception("invalid default fruit's color value "); break; } return(new Fruit(X, Y, randomColor)); }
public void RemovingAllBodyPartsStillGivesAPosition() { var snake = new Snake(gridSize, Color.Green); snake.Get<Body>().BodyParts.Clear(); AdvanceTimeAndUpdateEntities(); Assert.AreEqual(Vector2D.Half, snake.Get<Body>().HeadPosition); }
private void Start() { snake = GetComponent <Snake>(); bombLauncher = GetComponentInChildren <Weapon>(); }
public void CheckTrailingVector() { var snake = new Snake(gridSize, Color.Green); Assert.IsTrue(snake.Get<Body>().GetTrailingVector().IsNearlyEqual(new Vector2D(0, blockSize))); }
public override void Bind(Entity entity, Main main, bool creating = false) { if (ParticleSystem.Get(main, "SnakeSparks") == null) { ParticleSystem.Add(main, "SnakeSparks", new ParticleSystem.ParticleSettings { TextureName = "Particles\\splash", MaxParticles = 1000, Duration = TimeSpan.FromSeconds(1.0f), MinHorizontalVelocity = -7.0f, MaxHorizontalVelocity = 7.0f, MinVerticalVelocity = 0.0f, MaxVerticalVelocity = 7.0f, Gravity = new Vector3(0.0f, -10.0f, 0.0f), MinRotateSpeed = -2.0f, MaxRotateSpeed = 2.0f, MinStartSize = 0.3f, MaxStartSize = 0.7f, MinEndSize = 0.0f, MaxEndSize = 0.0f, BlendState = Microsoft.Xna.Framework.Graphics.BlendState.AlphaBlend, MinColor = new Vector4(2.0f, 2.0f, 2.0f, 1.0f), MaxColor = new Vector4(2.0f, 2.0f, 2.0f, 1.0f), }); ParticleSystem.Add(main, "SnakeSparksRed", new ParticleSystem.ParticleSettings { TextureName = "Particles\\splash", MaxParticles = 1000, Duration = TimeSpan.FromSeconds(1.0f), MinHorizontalVelocity = -7.0f, MaxHorizontalVelocity = 7.0f, MinVerticalVelocity = 0.0f, MaxVerticalVelocity = 7.0f, Gravity = new Vector3(0.0f, -10.0f, 0.0f), MinRotateSpeed = -2.0f, MaxRotateSpeed = 2.0f, MinStartSize = 0.3f, MaxStartSize = 0.7f, MinEndSize = 0.0f, MaxEndSize = 0.0f, BlendState = Microsoft.Xna.Framework.Graphics.BlendState.AlphaBlend, MinColor = new Vector4(1.4f, 0.8f, 0.7f, 1.0f), MaxColor = new Vector4(1.4f, 0.8f, 0.7f, 1.0f), }); ParticleSystem.Add(main, "SnakeSparksYellow", new ParticleSystem.ParticleSettings { TextureName = "Particles\\splash", MaxParticles = 1000, Duration = TimeSpan.FromSeconds(1.0f), MinHorizontalVelocity = -7.0f, MaxHorizontalVelocity = 7.0f, MinVerticalVelocity = 0.0f, MaxVerticalVelocity = 7.0f, Gravity = new Vector3(0.0f, -10.0f, 0.0f), MinRotateSpeed = -2.0f, MaxRotateSpeed = 2.0f, MinStartSize = 0.3f, MaxStartSize = 0.7f, MinEndSize = 0.0f, MaxEndSize = 0.0f, BlendState = Microsoft.Xna.Framework.Graphics.BlendState.AlphaBlend, MinColor = new Vector4(1.4f, 1.4f, 0.7f, 1.0f), MaxColor = new Vector4(1.4f, 1.4f, 0.7f, 1.0f), }); } Snake snake = entity.GetOrCreate <Snake>("Snake"); entity.CannotSuspendByDistance = true; Transform transform = entity.GetOrCreate <Transform>("Transform"); AI ai = entity.GetOrCreate <AI>("AI"); Agent agent = entity.GetOrCreate <Agent>("Agent"); const float defaultSpeed = 5.0f; const float chaseSpeed = 18.0f; const float closeChaseSpeed = 12.0f; const float crushSpeed = 125.0f; VoxelChaseAI chase = entity.GetOrCreate <VoxelChaseAI>("VoxelChaseAI"); chase.Add(new TwoWayBinding <Vector3>(transform.Position, chase.Position)); chase.Speed.Value = defaultSpeed; chase.EnablePathfinding.Value = ai.CurrentState.Value == "Chase"; chase.Filter = delegate(Voxel.State state) { if (state == Voxel.States.Infected || state == Voxel.States.Neutral || state == Voxel.States.Hard || state == Voxel.States.HardInfected) { return(true); } return(false); }; entity.Add(new CommandBinding(chase.Delete, entity.Delete)); PointLight positionLight = null; if (!main.EditorEnabled) { positionLight = new PointLight(); positionLight.Serialize = false; positionLight.Color.Value = new Vector3(1.5f, 0.5f, 0.5f); positionLight.Attenuation.Value = 20.0f; positionLight.Add(new Binding <bool, string>(positionLight.Enabled, x => x != "Suspended", ai.CurrentState)); positionLight.Add(new Binding <Vector3, string>(positionLight.Color, delegate(string state) { switch (state) { case "Chase": case "Crush": return(new Vector3(1.5f, 0.5f, 0.5f)); case "Alert": return(new Vector3(1.5f, 1.5f, 0.5f)); default: return(new Vector3(1.0f, 1.0f, 1.0f)); } }, ai.CurrentState)); entity.Add("PositionLight", positionLight); ParticleEmitter emitter = entity.GetOrCreate <ParticleEmitter>("Particles"); emitter.Serialize = false; emitter.ParticlesPerSecond.Value = 100; emitter.Add(new Binding <string>(emitter.ParticleType, delegate(string state) { switch (state) { case "Chase": case "Crush": return("SnakeSparksRed"); case "Alert": return("SnakeSparksYellow"); default: return("SnakeSparks"); } }, ai.CurrentState)); emitter.Add(new Binding <Vector3>(emitter.Position, transform.Position)); emitter.Add(new Binding <bool, string>(emitter.Enabled, x => x != "Suspended", ai.CurrentState)); positionLight.Add(new Binding <Vector3>(positionLight.Position, transform.Position)); emitter.Add(new Binding <Vector3>(emitter.Position, transform.Position)); agent.Add(new Binding <Vector3>(agent.Position, transform.Position)); Sound.AttachTracker(entity); } AI.Task checkMap = new AI.Task { Action = delegate() { if (chase.Voxel.Value.Target == null || !chase.Voxel.Value.Target.Active) { entity.Delete.Execute(); } }, }; AI.Task checkOperationalRadius = new AI.Task { Interval = 2.0f, Action = delegate() { bool shouldBeActive = (transform.Position.Value - main.Camera.Position).Length() < snake.OperationalRadius; if (shouldBeActive && ai.CurrentState == "Suspended") { ai.CurrentState.Value = "Idle"; } else if (!shouldBeActive && ai.CurrentState != "Suspended") { ai.CurrentState.Value = "Suspended"; } }, }; AI.Task checkTargetAgent = new AI.Task { Action = delegate() { Entity target = ai.TargetAgent.Value.Target; if (target == null || !target.Active) { ai.TargetAgent.Value = null; ai.CurrentState.Value = "Idle"; } }, }; Func <Voxel, Direction> randomValidDirection = delegate(Voxel m) { Voxel.Coord c = chase.Coord; Direction[] dirs = new Direction[6]; Array.Copy(DirectionExtensions.Directions, dirs, 6); // Shuffle directions int i = 5; while (i > 0) { int k = this.random.Next(i); Direction temp = dirs[i]; dirs[i] = dirs[k]; dirs[k] = temp; i--; } foreach (Direction dir in dirs) { if (chase.Filter(m[c.Move(dir)])) { return(dir); } } return(Direction.None); }; Direction currentDir = Direction.None; chase.Add(new CommandBinding <Voxel, Voxel.Coord>(chase.Moved, delegate(Voxel m, Voxel.Coord c) { if (chase.Active) { string currentState = ai.CurrentState.Value; Voxel.t id = m[c].ID; if (id == Voxel.t.Hard) { m.Empty(c); m.Fill(c, Voxel.States.HardInfected); m.Regenerate(); } else if (id == Voxel.t.Neutral) { m.Empty(c); m.Fill(c, Voxel.States.Infected); m.Regenerate(); } else if (id == Voxel.t.Empty) { m.Fill(c, Voxel.States.Infected); m.Regenerate(); } AkSoundEngine.PostEvent(AK.EVENTS.PLAY_SNAKE_MOVE, entity); if (currentState == "Idle") { if (currentDir == Direction.None || !chase.Filter(m[chase.Coord.Value.Move(currentDir)]) || this.random.Next(8) == 0) { currentDir = randomValidDirection(m); } chase.Coord.Value = chase.Coord.Value.Move(currentDir); } else if (snake.Path.Length > 0) { chase.Coord.Value = snake.Path[0]; snake.Path.RemoveAt(0); } } })); const float sightDistance = 50.0f; const float hearingDistance = 0.0f; ai.Setup ( new AI.AIState { Name = "Suspended", Tasks = new[] { checkOperationalRadius }, }, new AI.AIState { Name = "Idle", Enter = delegate(AI.AIState previous) { Entity voxelEntity = chase.Voxel.Value.Target; if (voxelEntity != null) { Voxel m = voxelEntity.Get <Voxel>(); if (currentDir == Direction.None || !chase.Filter(m[chase.Coord.Value.Move(currentDir)])) { currentDir = randomValidDirection(m); } chase.Coord.Value = chase.Coord.Value.Move(currentDir); } }, Tasks = new[] { checkMap, checkOperationalRadius, new AI.Task { Interval = 1.0f, Action = delegate() { Agent a = Agent.Query(transform.Position, sightDistance, hearingDistance, x => x.Entity.Type == "Player"); if (a != null) { ai.CurrentState.Value = "Alert"; } }, }, }, }, new AI.AIState { Name = "Alert", Enter = delegate(AI.AIState previous) { chase.EnableMovement.Value = false; }, Exit = delegate(AI.AIState next) { chase.EnableMovement.Value = true; }, Tasks = new[] { checkMap, checkOperationalRadius, new AI.Task { Interval = 0.4f, Action = delegate() { if (ai.TimeInCurrentState > 3.0f) { ai.CurrentState.Value = "Idle"; } else { Agent a = Agent.Query(transform.Position, sightDistance, hearingDistance, x => x.Entity.Type == "Player"); if (a != null) { ai.TargetAgent.Value = a.Entity; ai.CurrentState.Value = "Chase"; } } }, }, }, }, new AI.AIState { Name = "Chase", Enter = delegate(AI.AIState previousState) { chase.EnablePathfinding.Value = true; chase.Speed.Value = chaseSpeed; }, Exit = delegate(AI.AIState nextState) { chase.EnablePathfinding.Value = false; chase.Speed.Value = defaultSpeed; }, Tasks = new[] { checkMap, checkOperationalRadius, checkTargetAgent, new AI.Task { Interval = 0.07f, Action = delegate() { Vector3 targetPosition = ai.TargetAgent.Value.Target.Get <Agent>().Position; float targetDistance = (targetPosition - transform.Position).Length(); chase.Speed.Value = targetDistance < 15.0f ? closeChaseSpeed : chaseSpeed; if (targetDistance > 50.0f || ai.TimeInCurrentState > 30.0f) // He got away { ai.CurrentState.Value = "Alert"; } else if (targetDistance < 4.0f) // We got 'im { // First, make sure we're not near a reset block Voxel v = chase.Voxel.Value.Target.Get <Voxel>(); if (VoxelAStar.BroadphaseSearch(v, chase.Coord, 6, x => x.Type == Lemma.Components.Voxel.States.Reset) == null) { ai.CurrentState.Value = "Crush"; } } else { chase.Target.Value = targetPosition; } }, }, }, }, new AI.AIState { Name = "Crush", Enter = delegate(AI.AIState lastState) { // Set up cage Voxel.Coord center = chase.Voxel.Value.Target.Get <Voxel>().GetCoordinate(ai.TargetAgent.Value.Target.Get <Agent>().Position); int radius = 1; // Bottom for (int x = center.X - radius; x <= center.X + radius; x++) { for (int z = center.Z - radius; z <= center.Z + radius; z++) { snake.Path.Add(new Voxel.Coord { X = x, Y = center.Y - 4, Z = z }); } } // Outer shell radius = 2; for (int y = center.Y - 3; y <= center.Y + 3; y++) { // Left for (int z = center.Z - radius; z <= center.Z + radius; z++) { snake.Path.Add(new Voxel.Coord { X = center.X - radius, Y = y, Z = z }); } // Right for (int z = center.Z - radius; z <= center.Z + radius; z++) { snake.Path.Add(new Voxel.Coord { X = center.X + radius, Y = y, Z = z }); } // Backward for (int x = center.X - radius; x <= center.X + radius; x++) { snake.Path.Add(new Voxel.Coord { X = x, Y = y, Z = center.Z - radius }); } // Forward for (int x = center.X - radius; x <= center.X + radius; x++) { snake.Path.Add(new Voxel.Coord { X = x, Y = y, Z = center.Z + radius }); } } // Top for (int x = center.X - radius; x <= center.X + radius; x++) { for (int z = center.Z - radius; z <= center.Z + radius; z++) { snake.Path.Add(new Voxel.Coord { X = x, Y = center.Y + 3, Z = z }); } } chase.EnablePathfinding.Value = false; chase.Speed.Value = crushSpeed; snake.CrushCoordinate.Value = chase.Coord; }, Exit = delegate(AI.AIState nextState) { chase.Speed.Value = defaultSpeed; chase.Coord.Value = chase.LastCoord.Value = snake.CrushCoordinate; snake.Path.Clear(); }, Tasks = new[] { checkMap, checkOperationalRadius, checkTargetAgent, new AI.Task { Interval = 0.01f, Action = delegate() { Agent a = ai.TargetAgent.Value.Target.Get <Agent>(); a.Damage.Execute(0.01f / 1.5f); // seconds to kill if (!a.Active) { ai.CurrentState.Value = "Alert"; } else { if ((a.Position - transform.Position.Value).Length() > 5.0f) // They're getting away { ai.CurrentState.Value = "Chase"; } } } } }, } ); this.SetMain(entity, main); entity.Add("OperationalRadius", snake.OperationalRadius); }
Direction GetCurrentDirection() { Snake snake = app.model.snake; return(snake.GetCurrentDirection()); }
static void Main(string[] args) { Console.Clear(); Console.CursorVisible = false; Snake snake = new Snake(); Board game = new Board(18, 36); bool gameLost = false; int originalHeight = Console.WindowHeight; int originalWidth = Console.WindowWidth; ConsoleKeyInfo userDirection; game.Draw(); snake.Draw(); game.SetApple(snake.Parts); do { while (Console.KeyAvailable == false) { snake.Change(); snake.Draw(); if (game.Collision(snake)) { gameLost = true; break; } Thread.Sleep(100); // Loop until input is entered. } if (gameLost) { break; } userDirection = Console.ReadKey(true); switch (userDirection.Key) { case ConsoleKey.Z: if (snake.Move != Direction.Bottom) { snake.Move = Direction.Top; } break; case ConsoleKey.S: if (snake.Move != Direction.Top) { snake.Move = Direction.Bottom; } break; case ConsoleKey.Q: if (snake.Move != Direction.Right) { snake.Move = Direction.Left; } break; case ConsoleKey.D: if (snake.Move != Direction.Left) { snake.Move = Direction.Right; } break; default: break; } } while (userDirection.Key != ConsoleKey.Escape && !gameLost); // quit the game Console.Clear(); if (gameLost) { Console.SetCursorPosition(7, 3); Console.WriteLine($"Lost !!! You got {game.Score} points"); Console.SetCursorPosition(7, 5); Console.WriteLine("<press any key to exit>"); } else { Console.SetCursorPosition(7, 3); Console.WriteLine("Bye"); } Console.ReadKey(true); Console.SetWindowSize(originalWidth, originalHeight); Console.SetBufferSize(originalWidth, originalHeight); Console.Clear(); }