C# XNA Space Invaders issue -
i'm making space invaders clone using c# in xna 4.0 , i've run couple of issues. first when shoot of invaders on right-hand side column of array top one, invader moves off-screen until next column reaches predetermined limit; entire array moves down. want still detect remaining invader. i'm pretty sure issue following section of code, i'm not sure problem is.
(int rows = 4; rows > 0; rows--) // detects right-most invader (int cols = 10; cols > 0; cols--) { if (invaderarray[rows, cols] != null) { rightinvader = invaderarray[rows, cols]; break; } }
the second issue if destroy 1 row of invaders 'nullreferenceexception unhandled' notification on piece of code:
if (rightinvader.getxpos() > 800) // right edge limit { invaderdir = -1; (int rows = 0; rows < 5; rows++) (int cols = 0; cols < 11; cols++) { if (invaderarray[rows, cols] != null) { invaderarray[rows, cols].movevertical(8); } } }
again, not sure problem is. following code detecting remaining invader:
// detecting remaining invader bool invaderfound = false; (int rows = 0; rows < 5; rows++) (int cols = 0; cols < 11; cols++) { if (invaderarray[rows, cols] != null) { invaderfound = true; break; } }
any either issue appreciated.
so might suffering off 1 errors. looking @ code, looks use lot of 'magic' numbers everywhere. first step remove 4s, 10s, 5s, , 11s, , create public constants:
static readonly int numrows = 5; static readonly int numcolumns = 11;
now, first section of code never tests 0th row or column, leading of badness you're seeing. loops written as:
for (int rows = numrows - 1; rows >= 0; rows--) (int cols = numcols - 1; cols >= 0; cols--)
currently, loop never testing col or row 0.
edit: missed 'break' problem. easy way solve is:
bool found = false; (int rows = numrows - 1; rows >= 0 && !found; rows--) (int cols = numcols - 1; cols >= 0 && !found; cols--)
then set found true instead of breaking. way place nested loops inside function, , return when find want.
for example, found function written:
for (int rows = 0; rows < numrows ; rows++) (int cols = 0; cols < numcols; cols++) { if (invaderarray[rows, cols] != null) { return true; } } } return false;
Comments
Post a Comment