Search Results

Search found 112 results on 5 pages for 'snake'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • Designing Snake AI

    - by Ronald
    I'm new to this gamedev stackechange but have used the math and cs sites before. So, I'm in a competition to create AI for a snake that will compete with 3 other snakes in 5 minute rounds where the rules are much like the traditional Nokia snake game except that there are 4 snakes, the board is 50x50 and there are a number of small obstacles on the field. Like the Nokia game, your snake grows when you get to the fruit and if you crash into yourself, another snake or the wall you die. The game runs with a 50ms delay between moves and the server sends the new game state every 50ms which the code must analyze and what not and output the next move. The winner is the snake who had the longest length at any point in the game. Tie breakers are decided by kills. So far what I have done is implemented an A* graph search from each snake to determine if my snake is the closest to the apple and if it is, it goes for the apple. Otherwise, I made a neat little algorithm to determine the emptiest area of the board, which my snake goes for, to anticipate the next apple. Other than this I have some small survivability checks to ensure my snake isn't walking into a trap that it can't get out and if it does get stuck, I have something to give it a better chance of getting out. ... Anyway, I've tested my snake on a test server and it does quite well. Generally, my strategy of only going for the apple when its a sure thing and finding space when its not makes it grow faster than any other snakes (some snakes do a similar thing but often just go to the middle or a corner) sometimes it wins these trial games but is more often than not beaten by the same snake who seems to have the edge on survivability(my snake grows quicker but then dies somehow and this other snake just plods slowly along and wins on consistency. So I was wondering about any ideas anyone has to try and improve my snake. Or maybe ideas at a new approach to take. My functions and classes are good so changes that might seem drastic shouldn't be too bad. I encourage all ideas. Any thoughts ??

    Read the article

  • Designing a simple snake A.I

    - by DillPixel
    I've looked at some stuff online regarding this specific topic, and a lot of the info that I read involved graphs and path finding. I really don't want to get involved in something too complex & out of my level, and also I don't need my snake to be that intelligent (it will be a large board with the snake not growing in size on every munch). How could you structure a simpler AI for the snake that gets the job done relatively well? I would be able to get the snake to move towards the food item correctly, but my issue is that I'm not sure how to deal with the snake colliding with itself. Say the snake has a look ahead, and it finds that its tail is in the way, it could change direction, but what happens next? Any ideas on how to tackle this? Should the snake build an instruction set from every square, or should it think on the go?

    Read the article

  • Snake Game Help

    - by MuhammadA
    I am making a snake game and learning XNA at the same time. I have 3 classes : Game.cs, Snake.cs and Apple.cs My problem is more of a conceptual problem, I want to know which class is really responsible for ... detecting collision of snake head on apple/itself/wall? which class should increase the snakes speed, size? It seems to me that however much I try and put the snake stuff into snake.cs that game.cs has to know a lot about the snake, like : -- I want to increase the score depending on size of snake, the score variable is inside game.cs, which means now I have to ask the snake its size on every hit of the apple... seems a bit unclean all this highly coupled code. or -- I DO NOT want to place the apple under the snake... now the apple suddenly has to know about all the snake parts, my head hurts when I think of that. Maybe there should be some sort of AppleLayer.cs class that should know about the snake... Whats the best approach in such a simple scenario? Any tips welcome. Game.cs : using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Design; namespace Snakez { public enum CurrentGameState { Playing, Paused, NotPlaying } public class Game1 : Microsoft.Xna.Framework.Game { private GraphicsDeviceManager _graphics; private SpriteBatch _spriteBatch; private readonly Color _niceGreenColour = new Color(167, 255, 124); private KeyboardState _oldKeyboardState; private SpriteFont _scoreFont; private SoundEffect _biteSound, _crashSound; private Vector2 _scoreLocation = new Vector2(10, 10); private Apple _apple; private Snake _snake; private int _score = 0; private int _speed = 1; public Game1() { _graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { _spriteBatch = new SpriteBatch(GraphicsDevice); _scoreFont = Content.Load<SpriteFont>("Score"); _apple = new Apple(800, 480, Content.Load<Texture2D>("Apple")); _snake = new Snake(Content.Load<Texture2D>("BodyBlock")); _biteSound = Content.Load<SoundEffect>("Bite"); _crashSound = Content.Load<SoundEffect>("Crash"); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { Content.Unload(); } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { KeyboardState newKeyboardState = Keyboard.GetState(); if (newKeyboardState.IsKeyDown(Keys.Escape)) { this.Exit(); // Allows the game to exit } else if (newKeyboardState.IsKeyDown(Keys.Up) && !_oldKeyboardState.IsKeyDown(Keys.Up)) { _snake.SetDirection(Direction.Up); } else if (newKeyboardState.IsKeyDown(Keys.Down) && !_oldKeyboardState.IsKeyDown(Keys.Down)) { _snake.SetDirection(Direction.Down); } else if (newKeyboardState.IsKeyDown(Keys.Left) && !_oldKeyboardState.IsKeyDown(Keys.Left)) { _snake.SetDirection(Direction.Left); } else if (newKeyboardState.IsKeyDown(Keys.Right) && !_oldKeyboardState.IsKeyDown(Keys.Right)) { _snake.SetDirection(Direction.Right); } _oldKeyboardState = newKeyboardState; _snake.Update(); if (_snake.IsEating(_apple)) { _biteSound.Play(); _score += 10; _apple.Place(); } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(_niceGreenColour); float frameRate = 1 / (float)gameTime.ElapsedGameTime.TotalSeconds; _spriteBatch.Begin(); _spriteBatch.DrawString(_scoreFont, "Score : " + _score, _scoreLocation, Color.Red); _apple.Draw(_spriteBatch); _snake.Draw(_spriteBatch); _spriteBatch.End(); base.Draw(gameTime); } } } Snake.cs : using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace Snakez { public enum Direction { Up, Down, Left, Right } public class Snake { private List<Rectangle> _parts; private readonly Texture2D _bodyBlock; private readonly int _startX = 160; private readonly int _startY = 120; private int _moveDelay = 100; private DateTime _lastUpdatedAt; private Direction _direction; private Rectangle _lastTail; public Snake(Texture2D bodyBlock) { _bodyBlock = bodyBlock; _parts = new List<Rectangle>(); _parts.Add(new Rectangle(_startX, _startY, _bodyBlock.Width, _bodyBlock.Height)); _parts.Add(new Rectangle(_startX + bodyBlock.Width, _startY, _bodyBlock.Width, _bodyBlock.Height)); _parts.Add(new Rectangle(_startX + (bodyBlock.Width) * 2, _startY, _bodyBlock.Width, _bodyBlock.Height)); _parts.Add(new Rectangle(_startX + (bodyBlock.Width) * 3, _startY, _bodyBlock.Width, _bodyBlock.Height)); _direction = Direction.Right; _lastUpdatedAt = DateTime.Now; } public void Draw(SpriteBatch spriteBatch) { foreach (var p in _parts) { spriteBatch.Draw(_bodyBlock, new Vector2(p.X, p.Y), Color.White); } } public void Update() { if (DateTime.Now.Subtract(_lastUpdatedAt).TotalMilliseconds > _moveDelay) { //DateTime.Now.Ticks _lastTail = _parts.First(); _parts.Remove(_lastTail); /* add new head in right direction */ var lastHead = _parts.Last(); var newHead = new Rectangle(0, 0, _bodyBlock.Width, _bodyBlock.Height); switch (_direction) { case Direction.Up: newHead.X = lastHead.X; newHead.Y = lastHead.Y - _bodyBlock.Width; break; case Direction.Down: newHead.X = lastHead.X; newHead.Y = lastHead.Y + _bodyBlock.Width; break; case Direction.Left: newHead.X = lastHead.X - _bodyBlock.Width; newHead.Y = lastHead.Y; break; case Direction.Right: newHead.X = lastHead.X + _bodyBlock.Width; newHead.Y = lastHead.Y; break; } _parts.Add(newHead); _lastUpdatedAt = DateTime.Now; } } public void SetDirection(Direction newDirection) { if (_direction == Direction.Up && newDirection == Direction.Down) { return; } else if (_direction == Direction.Down && newDirection == Direction.Up) { return; } else if (_direction == Direction.Left && newDirection == Direction.Right) { return; } else if (_direction == Direction.Right && newDirection == Direction.Left) { return; } _direction = newDirection; } public bool IsEating(Apple apple) { if (_parts.Last().Intersects(apple.Location)) { GrowBiggerAndFaster(); return true; } return false; } private void GrowBiggerAndFaster() { _parts.Insert(0, _lastTail); _moveDelay -= (_moveDelay / 100)*2; } } } Apple.cs : using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace Snakez { public class Apple { private readonly int _maxWidth, _maxHeight; private readonly Texture2D _texture; private readonly Random random = new Random(); public Rectangle Location { get; private set; } public Apple(int screenWidth, int screenHeight, Texture2D texture) { _maxWidth = (screenWidth + 1) - texture.Width; _maxHeight = (screenHeight + 1) - texture.Height; _texture = texture; Place(); } public void Place() { Location = GetRandomLocation(_maxWidth, _maxHeight); } private Rectangle GetRandomLocation(int maxWidth, int maxHeight) { // x and y -- multiple of 20 int x = random.Next(1, maxWidth); var leftOver = x % 20; x = x - leftOver; int y = random.Next(1, maxHeight); leftOver = y % 20; y = y - leftOver; return new Rectangle(x, y, _texture.Width, _texture.Height); } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(_texture, Location, Color.White); } } }

    Read the article

  • C# creating a simple snake game

    - by Guy David
    I was thinking about creating a snake game with C#, so I ran ideas in my head, and some problems came up. How can I track and output in the correct location the blocks that run after the snake's head? If the snake is built of five blocks, and the user starts going in a circle, how can I print the snake body in the right location? Also, how can I create an action that will run on the background, which will move the snake forward, no matter what the user does? What structure should my code have? (code design structure) This should be a console application, since it's the only framework I am familiar with. I am not looking for finished code, since I want to really understand how it should work.

    Read the article

  • 360 snake movement

    - by Darius Janavicius
    I'm trying to do 360 degree snake game in actionscript 3. Here is my movement code: //head movement head.x += snake_speed*Math.cos((head.rotation) * (Math.PI /180)); head.y += snake_speed*Math.sin((head.rotation) * (Math.PI /180)); if (dir == "left") head.rotation -= snake_speed*2; if (dir == "right") head.rotation +=snake_speed*2; //Body part movement for(var i:int = body_parts.length-1; i>0; i--) { var angle = (body_parts[i-1].rotation)*(Math.PI/180); body_parts[i].y = body_parts[i-1].y - (25 * Math.sin(angle)); body_parts[i].x = body_parts[i-1].x - (25 * Math.cos(angle)); body_parts[i].rotation = body_parts[i-1].rotation; } With this code head moves just like I want it to move, but body parts have the same angle as head and it looks wrong. What I want to achieve is to make body parts to move like in game "Ultimate snake". Here is a link to that game: http://armorgames.com/play/387/ultimate-snake P.S. I saw similar question here "How to approach 360 degree snake" but didnt understand the answer :/

    Read the article

  • How To Approach 360 Degree Snake

    - by Austin Brunkhorst
    I've recently gotten into XNA and must say I love it. As sort of a hello world game I decided to create the classic game "Snake". The 90 degree version was very simple and easy to implement. But as I try to make a version of it that allows 360 degree rotation using left and right arrows, I've come into sort of a problem. What i'm doing now stems from the 90 degree version: Iterating through each snake body part beginning at the tail, and ending right before the head. This works great when moving every 100 milliseconds. The problem with this is that it makes for a choppy style of gameplay as technically the game progresses at only 6 fps rather than it's potential 60. I would like to move the snake every game loop. But unfortunately because the snake moves at the rate of it's head's size it goes way too fast. This would mean that the head would need to move at a much smaller increment such as (2, 2) in it's direction rather than what I have now (32, 32). Because I've been working on this game off and on for a couple of weeks while managing school I think that I've been thinking too hard on how to accomplish this. It's probably a simple solution, i'm just not catching it. Here's some pseudo code for what I've tried based off of what makes sense to me. I can't really think of another way to do it. for(int i = SnakeLength - 1; i > 0; i--){ current = SnakePart[i], next = SnakePart[i - 1]; current.x = next.x - (current.width * cos(next.angle)); current.y = next.y - (current.height * sin(next.angle)); current.angle = next.angle; } SnakeHead.x += cos(SnakeAngle) * SnakeSpeed; SnakeHead.y += sin(SnakeAngle) * SnakeSpeed; This produces something like this: Code in Action. As you can see each part always stays behind the head and doesn't make a "Trail" effect. A perfect example of what i'm going for can be found here: Data Worm. Not the viewport rotation but the trailing effect of the triangles. Thanks for any help!

    Read the article

  • NHibernate Session Load vs Get when using Table per Hierarchy. Always use ISession.Get&lt;T&gt; for TPH to work.

    - by Rohit Gupta
    Originally posted on: http://geekswithblogs.net/rgupta/archive/2014/06/01/nhibernate-session-load-vs-get-when-using-table-per-hierarchy.aspxNHibernate ISession has two methods on it : Load and Get. Load allows the entity to be loaded lazily, meaning the actual call to the database is made only when properties on the entity being loaded is first accessed. Additionally, if the entity has already been loaded into NHibernate Cache, then the entity is loaded directly from the cache instead of querying the underlying database. ISession.Get<T> instead makes the call to the database, every time it is invoked. With this background, it is obvious that we would prefer ISession.Load<T> over ISession.Get<T> most of the times for performance reasons to avoid making the expensive call to the database. let us consider the impact of using ISession.Load<T> when we are using the Table per Hierarchy implementation of NHibernate. Thus we have base class/ table Animal, there is a derived class named Snake with the Discriminator column being Type which in this case is “Snake”. If we load This Snake entity using the Repository for Animal, we would have a entity loaded, as shown below: public T GetByKey(object key, bool lazy = false) { if (lazy) return CurrentSession.Load<T>(key); return CurrentSession.Get<T>(key); } var tRepo = new NHibernateReadWriteRepository<TPHAnimal>(); var animal = tRepo.GetByKey(new Guid("602DAB56-D1BD-4ECC-B4BB-1C14BF87F47B"), true); var snake = animal as Snake; snake is null As you can see that the animal entity retrieved from the database cannot be cast to Snake even though the entity is actually a snake. The reason being ISession.Load prevents the entity to be cast to Snake and will throw the following exception: System.InvalidCastException :  Message=Unable to cast object of type 'TPHAnimalProxy' to type 'NHibernateChecker.Model.Snake'. Thus we can see that if we lazy load the entity using ISession.Load<TPHAnimal> then we get a TPHAnimalProxy and not a snake. =============================================================== However if do not lazy load the same cast works perfectly fine, this is since we are loading the entity from database and the entity being loaded is not a proxy. Thus the following code does not throw any exceptions, infact the snake variable is not null: var tRepo = new NHibernateReadWriteRepository<TPHAnimal>(); var animal = tRepo.GetByKey(new Guid("602DAB56-D1BD-4ECC-B4BB-1C14BF87F47B"), false); var snake = animal as Snake; if (snake == null) { var snake22 = (Snake) animal; }

    Read the article

  • How to implement a multi-part snake with smooth movement? [closed]

    - by Jamie
    Sorry that i couldnt answer on my previous post but it got closed. I couldnt answer because i had to prepair for my finals. As there were problems with understanding of what im trying to achieve, im going to describe a little bit more in depth. Im creating a game in which you steer a snake. I assume everybody knows how that works. But in my case the snake isnt just propagating in an array element by element. Imagine a 2Dgrid on which the snake moves. Its 10x10 tiles. Lets say one tile is 4x4 meters. The snakes head spawns in the middle of the (3,2) tile (beginning with (0,0)), so its position is (4*3+2,4*2+2)(the 2's are so that the snake is in the middle of the 4x4 tile). And heres where the fun begins. when the snake moves, it doesnt jump to next tile. Instead it moves a fraction of the way there. So lets say the snake is heading to tile (4,2). After it moved once, its position is (4*3+2+0.1,4*2+2), where 0.1 is the fraction of the way it moved. This is done to achieve smooth movement. So now im adding the rest of the body. The rest is supposed to move along the exact same path as the head did. I implemented it so that each part of the body has its own position and direction. Then i apply this algorithm: 1.Move each part in its direction. 2.If a part is in the middle of the tile(which implies all of them are), change each parts direction to the direction of the part proceeding it. As i said before i could make this work, but i cant stop thinking that im overlooking a much easier and cleaner solution. So this is my question. Is there any easier/better/faster way to do this?

    Read the article

  • Terminal-based snake game: input thread manipulates output

    - by enlightened
    I'm writing a snake game for the terminal, i.e. output via print. The following works just fine: while status[snake_monad] do print to_string draw canvas, compose_all([ frame, specs, snake_to_hash(snake[snake_monad]) ]) turn! snake_monad, get_dir move! snake_monad, specs sleep 0.25 end But I don't want the turn!ing to block, of course. So I put it into a new Thread and let it loop: Thread.new do loop do turn! snake_monad, get_dir end end while status[snake_monad] do ... # no turn! here ... end Which also works logically (the snake is turning), but the output is somehow interspersed with newlines. As soon as I kill the input thread (^C) it looks normal again. So why and how does the thread have any effect on my output? And how do I work around this issue? (I don't know much about threads, even less about them in ruby. Input and output concurrently on the same terminal make the matter worse, I guess...) Also (not really important): Wanting my program as pure as possible, would it be somewhat easily possible to get the input non-blockingly while passing everything around? Thank you!

    Read the article

  • Snake game, can't add new rectangles?

    - by user1814358
    I had seen some problem on other forum, and i tried to solve them but unsuccesfully, now is too intersting for me and i just need to solve this for my ego... lol Main problem is when snake eat first food, snake added one rectangle, when snake eat second food nothings changed? When snake head position and food position are same, then i try to add another rectangle, i have list where i stored rectangles coordinates x and y. What do you think, how i can to solve this problem? I think that i'm so close, but my brain has stopped. :( code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Zmijice { enum Kontrole { Desno,Levo,Gore,Dole,Stoj } public partial class Zmijice : Form { int koox; int kooy; private int x; private int y; private int c; private int b; private const int visina=20; //width private const int sirina=20; //height //private int m = 20; //private int n = 20; private List<int> SegmentX = new List<int>(); private List<int> SegmentY = new List<int>(); Random rnd = new Random(); private Kontrole Pozicija; public Zmijice() { InitializeComponent(); //slucajne pozicije pri startu x = rnd.Next(1, 20) * 20; y = rnd.Next(1, 20) * 20; c = rnd.Next(1, 20) * 20; b = rnd.Next(1, 20) * 20; Pozicija = Kontrole.Stoj; //stop on start } private void Tajmer_Tick(object sender, EventArgs e) { if (Pozicija == Kontrole.Stoj) { //none } if (Pozicija == Kontrole.Desno) { x += 20; } else if (Pozicija == Kontrole.Levo) { x -= 20; } else if (Pozicija == Kontrole.Gore) { y -= 20; } else if (Pozicija == Kontrole.Dole) { y += 20; } Invalidate(); } private void Zmijice_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Down) { Pozicija = Kontrole.Dole; } else if (e.KeyCode == Keys.Up) { Pozicija = Kontrole.Gore; } else if (e.KeyCode == Keys.Right) { Pozicija = Kontrole.Desno; } else if (e.KeyCode == Keys.Left) { Pozicija = Kontrole.Levo; } } private void Zmijice_Paint(object sender, PaintEventArgs e) { int counter = 1; //ako je pojela hranu if (x==c && y==b) { counter++; c = rnd.Next(1, 20); //nova pozicija hrrane c = c * 20; b = rnd.Next(1, 20); b = b * 20; //povecaj zmijicu SegmentX.Add(x); SegmentY.Add(y); //label1.Text = SegmentX.Count().ToString() + " " + SegmentY.Count().ToString(); //left if (Pozicija == Kontrole.Levo) { koox = x+20; kooy = y; } //right if (Pozicija == Kontrole.Desno) { koox = x-20; kooy = y; } //up if (Pozicija == Kontrole.Gore) { koox = x; kooy = y+20; } //down if (Pozicija == Kontrole.Dole) { koox = x; kooy = y-20; } } foreach (int k in SegmentX) { foreach (int l in SegmentY) { e.Graphics.FillRectangle(Brushes.Orange, koox, kooy, sirina, visina); } } koox = x; kooy = y; e.Graphics.FillRectangle(Brushes.DarkRed, x, y, sirina, visina); e.Graphics.FillRectangle(Brushes.Aqua, c, b, sirina, visina); } } }

    Read the article

  • Snake App on Xcode

    - by Will Rose
    How do I make one square on a screen lead about 6 with more to be added as the game progresses and how do I control the direction of the lead square with buttons? I basically want to know how to make a "Snake" app for the iPhone, iPod and iPad Please answer!!!!!!

    Read the article

  • Inconsistent accessibility error in xna.

    - by Tom
    Hey all, you may remember me asking a question regarding a snake game I was creating about two weeks ago. Well I'm quite far now into making the game (thanks to a brilliant tutorial I found). But I've come across the error described named above. So heres my problem; I have a SnakeFood class that has a method called "Reposition". In the game1 class I have a method called "UpdateInGame" which calls the reposition method to load an orange that spawns in a random place every second. My latest piece of code changed the reposition method to allow the snake I have on the screen to not be overlapped by the orange that randomly spawns. Now I get the error (in full): Error 1 Inconsistent accessibility: parameter type 'TheMathsSnakeGame.Snake' is less accessible than method 'TheMathsSnakeGame.SnakeFood.Reposition(TheMathsSnakeGame.Snake)' C:\Users\Tom\Documents\Visual Studio 2008\Projects\TheMathsSnakeGame\TheMathsSnakeGame\SnakeFood.cs 33 21 TheMathsSnakeGame I understand what the errors trying to tell me but having changed the accessiblity of the methods, I still can't get it to work. Sorry about the longwinded question. Thanks in advance :) Edit: Code I'm using (Game1 Class) private void UpdateInGame(GameTime gameTime) { //Calls the oranges "reposition" method every second if (gameTime.TotalGameTime.Milliseconds % 1000 == 0) orange.Reposition(sidney); sidney.Update(gameTime); } (SnakeFood Class) public void Reposition(Snake snake) { do { position = new Point(rand.Next(Grid.maxHeight), rand.Next(Grid.maxWidth)); } while (snake.IsBodyOnPoint(position)); }

    Read the article

  • Moving my sprite in XNA using classes

    - by Tom
    Hey, im a newbie at this programming lark and its really frustrating me. I'm trying to move a snake in all directions while using classes. Ive created a vector2 for speed and ive attempted creating a method which moves the snake within the snake class. Now I'm confused and not sure what to do next. Appreciate any help. Thanks :D This is what i've done in terms of the method... public Vector2 direction() { Vector2 inputDirection = Vector2.Zero; if (Keyboard.GetState().IsKeyDown(Keys.Left)) inputDirection.X -= -1; if (Keyboard.GetState().IsKeyDown(Keys.Right)) inputDirection.X += 1; if (Keyboard.GetState().IsKeyDown(Keys.Up)) inputDirection.Y -= -1; if (Keyboard.GetState().IsKeyDown(Keys.Down)) inputDirection.Y += 1; return inputDirection * snakeSpeed; } Appreciate any help. Thanks :D EDIT: Well let me make everything clear. Im making a small basic game for an assignment. The game is similar to the old snake game on the old Nokia phones. I've created a snake class (even though I'm not sure whether this is needed because im only going to be having one moving sprite within the game). After I written the code above (in the snake class), the game ran with no errors but I couldn't actually move the image :( EDIT2: Thanks so much for everyones responses!!

    Read the article

  • Can I add a function to enums in Java?

    - by Samuel Carrijo
    Hi, I have an enum, which looks like public enum Animal { ELEPHANT, GIRAFFE, TURTLE, SNAKE, FROG } and I want to do something like Animal frog = ANIMAL.FROG; Animal snake = ANIMAL.SNAKE; boolean isFrogAmphibian = frog.isAmphibian(); //true boolean isSnakeAmphibian = snake.isAmphibian(); //false boolean isFrogReptile = frog.isReptile(); //false boolean isSnakeReptile = snake.isReptile(); //true boolean isFrogMammal = frog.isMammal(); //false boolean isSnakeMammal = snake.isMammal(); //false Can I do it in Java?

    Read the article

  • How do I add a Rigid body and a box collider component to a Texture2D?

    - by gamenewdev
    I am making a snake game. I'm basing it on a basic tutorial game, which does no collision detection, wall checking or different levels. All snake head, piece, food, even the background is made of Texture2D. I want the head of the snake to detects 2D collisions with them, but Rect.contains isn't working. I'd prefer to detect collisions by onTriggerEnter() for which I need to add BoxCollider to my snakeHead.

    Read the article

  • What programming language is this?

    - by Richard M.
    I recently stumbled over a very odd source listing on a rather old programming-related site (lost it somewhere in my browser history as I didn't care about it at first). I think that this is part of a simple (console-based?) snake game. I searched and searched but didn't find a language that looked somwhat like this. This seems like a mix of Python, Ruby and C++. What the hell? What programming-language is the below source listing written in? Maybe you can figure it out? my Snake.hasProps { length parts xDir yDir } & hasMethods { init: length = 0 parts[0].x,y = 5 move: parts[ 0 ].x,y.!add xDir | yDir # Move the head map parts(i,v): parts[ i ] = parts[ i + 1 ] checkBiteSelf checkFeed checkBiteSelf: part } my SnakePart.hasProps { x y } fork SnakePart to !Feed my Game.hasProps { frameTime = 30 } & hasMethods { init: mainloop mainloop: sys.util.sleep frameTime Snake.move Field.getInput -> Snake.xDir | Snake.yDir Field.reDraw with Snake & Feed & Game # For FPS } main.isMethod { game.init }

    Read the article

  • How would I be able to get a game over screen using the pause function?

    - by Joachim Velzel
    I am having problems with my snake game, when the snake collides with itself it draws a "game over" image in the background, but only while it's colliding with itself. I want it to behave like the pause function, so that as soon as the snake collides with itself it draws an image on the screen and stops the game play. And then how would you be able to restart or to quit the game? I just have this for the detection at the moment: if (snakeHeadRectangle.Intersects(snakeBodyRectangleArray[bodyNumber])) { spriteBatch.Draw(textureGameOver, gameOverPosition, Color.White); } Thanks

    Read the article

  • pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

    - by kamziro
    So I've been getting some mysterious uninitialized values message from valgrind and it's been quite the mystery as of where the bad value originated from. Seems that valgrind shows the place where the unitialised value ends up being used, but not the origin of the uninitialised value. ==11366== Conditional jump or move depends on uninitialised value(s) ==11366== at 0x43CAE4F: __printf_fp (in /lib/tls/i686/cmov/libc-2.7.so) ==11366== by 0x43C6563: vfprintf (in /lib/tls/i686/cmov/libc-2.7.so) ==11366== by 0x43EAC03: vsnprintf (in /lib/tls/i686/cmov/libc-2.7.so) ==11366== by 0x42D475B: (within /usr/lib/libstdc++.so.6.0.9) ==11366== by 0x42E2C9B: std::ostreambuf_iterator<char, std::char_traits<char> > std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::_M_insert_float<double>(std::ostreambuf_iterator<char, std::char_traits<char> >, std::ios_base&, char, char, double) const (in /usr/lib/libstdc++.so.6.0.9) ==11366== by 0x42E31B4: std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::do_put(std::ostreambuf_iterator<char, std::char_traits<char> >, std::ios_base&, char, double) const (in /usr/lib/libstdc++.so.6.0.9) ==11366== by 0x42EE56F: std::ostream& std::ostream::_M_insert<double>(double) (in /usr/lib/libstdc++.so.6.0.9) ==11366== by 0x81109ED: Snake::SnakeBody::syncBodyPos() (ostream:221) ==11366== by 0x810B9F1: Snake::Snake::update() (snake.cpp:257) ==11366== by 0x81113C1: SnakeApp::updateState() (snakeapp.cpp:224) ==11366== by 0x8120351: RoenGL::updateState() (roengl.cpp:1180) ==11366== by 0x81E87D9: Roensachs::update() (rs.cpp:321) As can be seen, it gets quite cryptic.. especially because when it's saying by Class::MethodX, it sometimes points straight to ostream etc. Perhaps this is due to optimization? ==11366== by 0x81109ED: Snake::SnakeBody::syncBodyPos() (ostream:221) Just like that. Is there something I'm missing? What is the best way to catch bad values without having to resort to super-long printf detective work?

    Read the article

  • Please Help me add up the elements for this structure in Scheme/Lisp

    - by kunjaan
    I have an input which is of this form: (((lady-in-water . 1.25) (snake . 1.75) (run . 2.25) (just-my-luck . 1.5)) ((lady-in-water . 0.8235294117647058) (snake . 0.5882352941176471) (just-my-luck . 0.8235294117647058)) ((lady-in-water . 0.8888888888888888) (snake . 1.5555555555555554) (just-my-luck . 1.3333333333333333))) (context: the word denotes a movie and the number denotes the weighted rating submitted by the user) I need to add all the quantity and return a list which looks something like this ((lady-in-water 2.5) (snake 2.5) (run 2.25) (just-myluck 2.6)) How do I traverse the list and all the quantities? I am really stumped. Please help me. Thanks.

    Read the article

  • Android Bitmap.createBitmap returns negative mHeight

    - by Hai Bi
    Modifying the Snake example. An exception was created from the bitmap class. So I debug the original Snake, and found that in TileView there is a function loadTile, Bitmap bitmap = Bitmap.createBitmap(mTileSize, mTileSize, Bitmap.Config.ARGB_8888); after the above assignment, the bitmap had -1 for mHeight and mWidth. Then how does the Snake even work? I am just use the Eclipse and the virtual machine, not a real android phone.

    Read the article

  • mouse and mousepad not working properly

    - by snake
    Ubuntu 12.04 LTS Samsung Q35 The mouse pad has stopped working, only the buttons work. The external mouse is also behaving very oddly, the mouse pointer works, but the button is not working properly, it has to be pressed many times or held down to select anything, and when anything that I select behaves as though the mouse is being clicked all the screen, settings will keep changing, the page will scroll, sliders will move up and down, tabs will toggle etc, so everything is unusable with the mouse, cannot even use the browser as it keeps scrolling the page up and down. I have tested the mouse on another computer, and it works fine. Please bear in mind that I am also a complete Linux novice, I installed Ubuntu on an old laptop for my kids, that is the limit of my experience.

    Read the article

  • How do I bind one TabControl to the TabItems of another TabControl in WPF?

    - by joebeazelman
    I've defined the following TabControl called TabControl1: <TabControl> <TabItem Header="Cheese"> The Cheese Tab </TabItem> <TabItem Header="Pepperoni"> The Pepperoni Tab </TabItem> <TabItem Header="Mushrooms"> The Mushrooms Tab </TabItem> </TabControl> I've defined another TabControl, TabControl2 which is dynamically loaded from an add-in or plugin: <TabControl> <TabItem Header="Anchovies"> The AnchoviesTab </TabItem> <TabItem Header="Jalepenos"> The Jalepenos Tab </TabItem> <TabItem Header="Rattle Snake"> The Rattle Snake Tab </TabItem> </TabControl> After TabControl1 binds to TabControl2 after the "Cheese" item, TabControl1 should look like this: <TabControl> <TabItem Header="Cheese"> The Cheese Tab </TabItem> <TabItem Header="Anchovies"> The AnchoviesTab </TabItem> <TabItem Header="Jalepenos"> The Jalepenos Tab </TabItem> <TabItem Header="Rattle Snake"> The Rattle Snake Tab </TabItem> <TabItem Header="Pepperoni"> The Pepperoni Tab </TabItem> <TabItem Header="Mushrooms"> The Mushrooms Tab </TabItem> </TabControl>

    Read the article

  • Visual Studio 2008 Installer, Custom Action. Breakpoint not firing.

    - by Snake
    Hi, I've got an installer with a custom action project. I want the action to fire at install. The action fires, when I write something to the event log, it works perfectly. But I really need to debug the file since the action is quite complicated. So I've got the following installer class: namespace InstallerActions { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration.Install; using System.Diagnostics; using System.IO; [RunInstaller(true)] // ReSharper disable UnusedMember.Global public partial class DatabaseInstallerAction : Installer // ReSharper restore UnusedMember.Global { public DatabaseInstallerAction() { InitializeComponent(); } public override void Install(IDictionary stateSaver) { base.Install(stateSaver); System.Diagnostics.Debugger.Launch(); System.Diagnostics.Debugger.Break(); // none of these work Foo(); } private static void Foo() { } } } The installer just finalizes without warning me, it doesn't break, it doesn't ask me to attach a debugger. I've tried debug and release mode. Am I missing something? Thanks -Snake

    Read the article

  • Implementing movement on a grid

    - by Dvole
    I have a simple snake game, where I have other NPC snakes on the field. How do I calculate the movement of those other snakes so that they did not hit walls, and each other? So far I have it like this: I check for current coordinates and when there is a wall nearby I change direction to some other one. And so on, this way the snakes never collide the walls. But not actually colliding other snakes, how do I prevent this? I figured I could probe for the direction I'm heading and if there is anything there I would change direction too, but there is a set of situation where this won't work, for example if another snake will block off all exits later.

    Read the article

1 2 3 4 5  | Next Page >