Reputation: 33
I'm doing a school project and I've chosen to make a snake game in C#. I'm almost done with the game, but there is one last thing I would like to add and that is to have no collision when the snake hits one og th edges. So instead of the snake dying I want it to come out on the other end of the screen (as it was on the original game). Here's my code for when the snake hits the edge.
//Get maximum X and Y Pos
int maxXPos = pbCanvas.Size.Width / Settings.Width;
int maxYPos = pbCanvas.Size.Height / Settings.Height;
//Detect collission with game borders.
if (Snake[i].X < 0 || Snake[i].Y < 0
|| Snake[i].X >= maxXPos || Snake[i].Y >= maxYPos)
{
Die();
}
I know that the Die();
is not supposed to be there, but I can't figure out what I should write there instead. I'm writing in Visual Studio 2010 by the way.
Upvotes: 1
Views: 1152
Reputation: 424
I believe that this should be used as you will always deal with only one collision:
//Get maximum X and Y Pos
int maxXPos = pbCanvas.Size.Width / Settings.Width;
int maxYPos = pbCanvas.Size.Height / Settings.Height;
//Detect collission with game borders.
if (Snake[i].X < 0 ){
Snake[i].X = maxXPos;
}
else if(Snake[i].Y < 0){
Snake[i].Y = maxYPos;
}
else if(Snake[i].X >= maxXPos){
Snake[i].X = 0;
}
else if(Snake[i].Y >= maxYPos){
Snake[i].Y = 0;
}
Upvotes: 1
Reputation: 119
You can use the modulus %
operator for this:
Snake[i].X = (Snake[i].X + maxXPos) % maxXPos;
Snake[i].Y = (Snake[i].Y + maxYPos) % maxYPos;
Say for example maxXPos == 10
, when the X
becomes -2
, this will make it 8
.
And when X
becomes 11
, this will make it 1
.
Upvotes: 3
Reputation: 4928
I'm assuming you also have min positions stored somewhere?
int maxXPos = pbCanvas.Size.Width / Settings.Width;
int maxYPos = pbCanvas.Size.Height / Settings.Height;
// Detect collission with game borders.
if (Snake[i].X < 0) { Snake[i].X = maxXPos; }
if (Snake[i].X > maxXPos 0) { Snake[i].X = 0; }
if (Snake[i].Y < 0) { Snake[i].Y = maxXPos; }
if (Snake[i].Y > maxYPos 0) { Snake[i].Y = 0; }
Upvotes: 0
Reputation: 37113
I suppose you have to handle each of the four cases and set the coordinates of the snake to the "opposite" location:
if(Snake[i].X < 0) Snake[i].X = maxXPos;
else if(Snake[i].X >= maxXPos) Snake[i].X = 0;
else if(Snake[i].Y < 0) Snake[i].Y = maxYPos;
else if(Snake[i].Y >= maxYPos) Snake[i].Y = 0;
The else
-statements instead of simple if
avoid that you make unnecessary comparisons when there already was some hit on any of the previos conditions.
Upvotes: 1