I am trying to create a snake game but my code is throwing exceptions and I can't figure out what it might be.
I am creating this snake game because I want to learn more c# since my teacher said that 4th quarter I get to choose what I want to do with my time.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace snake_game
{
class Program
{
static void Main(string[] args)
{
int xposition = 26;
int yposition = 26;
int LeftColumn = 1;
int rightcolumn = 50;
int topcolumn = 1;
int bottomcolumn = 50;
string[,] map = new string[51, 51];
map = buildWall(LeftColumn, rightcolumn, topcolumn,
bottomcolumn, map);
//places down the player and updates the map to tell where you are
Console.SetCursorPosition(xposition, yposition);
Console.Write((char)2);
map[xposition, yposition] = "player";
map = generateRandomApple(map, LeftColumn, rightcolumn,
topcolumn, bottomcolumn);
placeApple(map);
Console.ReadKey();
}
private static void placeApple(string[,] map)
{
//places down the apple
for (int x = 0; x < map.Length; x++)
{
for (int y = 0; y < map.Length; y++)
{
if (map[x, y].Equals("apple"))
{
Console.Write("a");
break;
}
}
}
}
private static string[,] generateRandomApple(string[,] map, int lc, int
rc, int tc, int bc)
{
Random rnd = new Random();
int xposition;
int yposition;
while (true)
{
//generates random cordinates to place down the apple
xposition = rnd.Next(lc, rc);
yposition = rnd.Next(tc, bc);
//sets the property that the apple wants to be at to the apple
if it isnt open in the map
if ((!map[xposition, yposition].Equals("the wall")) &&
(!map[xposition, yposition].Equals("player")))
{
map[xposition, yposition] = "apple";
break;
}
}
return map;
}
private static string[,] buildWall(int leftcolumn, int rightcolumn, int
topcolumn, int bottomcolumn, string[,] map)
{
//generates the left and right walls
for (int i = leftcolumn; i <= rightcolumn ; i++)
{
Console.SetCursorPosition(leftcolumn, i);
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write("#");
map[leftcolumn, i] = "the wall";
Console.SetCursorPosition(rightcolumn, i);
Console.Write("#");
map[rightcolumn, i] = "the wall";
}
//generates the top and bottom walls
for (int i = topcolumn; i <= bottomcolumn; i++)
{
Console.SetCursorPosition(i, topcolumn);
Console.Write("#");
map[i, topcolumn] = "the wall";
Console.SetCursorPosition(i, bottomcolumn);
Console.Write("#");
map[i, bottomcolumn] = "the wall";
}
return map;
}
}
}
It is supposed to set up the map but the if statement in the function getRandomApple
is throwing exceptions specifically the part that checks if the spot has the player in it, the exception it is throwing is saying that a
NullReferenEexception was being unhandled(object reference not set to an
instance of an object).
Can anyone help me figure out what might be throwing the exceptions? I would appreciate the help.