//-------------------------------------- //Functions public void Initialize() { //initialize random Global.rand = new Random(); snakeHead = new TablePos(15, 15); snakeTail.Clear(); snakeTail.Add(new TablePos(15, 16)); //fill level with empty cells for (int r = 0; r < Global.kLevelRows; r++) { for (int c = 0; c < Global.kLevelColumns; c++) { levelData[r, c] = "cell_empty"; } } //add snake head and tail to level levelData[snakeHead.row, snakeHead.column] = "snake_head"; levelData[snakeTail[0].row, snakeTail[0].column] = "snake_tail"; snakeHeadDir = Direction.Up; //place first food placeFood(); }
public void MoveSnake() { snakeDir = snakeHeadDir; var raise = false; //check forward cell var dir = new TablePos(); switch (snakeDir) { case Direction.Up: dir.column--; break; case Direction.Down: dir.column++; break; case Direction.Left: dir.row--; break; case Direction.Right: dir.row++; break; } if (snakeHead.row + dir.row >= Global.kLevelRows || snakeHead.row + dir.row < 0 || snakeHead.column + dir.column >= Global.kLevelColumns || snakeHead.column + dir.column < 0) { m_game.LoseGame(); return; } string dirCell = levelData[snakeHead.row + dir.row, snakeHead.column + dir.column]; switch (dirCell) { case "cell_food": raise = true; break; case "cell_empty": raise = false; break; default: m_game.LoseGame(); return; } //delete last tail if is not eating if (!raise) { TablePos lastPos = snakeTail[snakeTail.Count - 1]; levelData[lastPos.row, lastPos.column] = "cell_empty"; snakeTail.RemoveAt(snakeTail.Count - 1); } else { placeFood(); } //turn head into tail snakeTail.Insert(0, new TablePos(snakeHead.row, snakeHead.column)); //move head snakeHead.column += dir.column; snakeHead.row += dir.row; levelData[snakeHead.row, snakeHead.column] = "snake_head"; //redraw tail for (int i = 0; i < snakeTail.Count; i++) { if (i < snakeTail.Count - 1) { levelData[snakeTail[i].row, snakeTail[i].column] = "snake_body"; } else { levelData[snakeTail[i].row, snakeTail[i].column] = "snake_tail"; } } }