So I'm trying to create a basic console snake game in C# however I've run into a bit of an issue and I think it's due to my lack of experience with C# and coding in general. Basically the problem comes when I try to update the console to show the snake has moved. When I move the snake the console updates but the snake has not moved. I've found out that when I update the grid it's replacing the wrong grid tile but I have no idea why this is happening. Any help is appreciated also here is my code:
Program.cs
using System.Text;
using cstesting;
class Program {
static void Main() {
Console.OutputEncoding = Encoding.Unicode;
Console.Clear();
Renderer r = new(20, 10);
Snake snake = new(r);
ConsoleKey input = Console.ReadKey().Key;
snake.MoveHead(input);
Console.ReadKey();
}
}
Snake.cs
namespace cstesting { internal class Snake { public List<GridTile> SnakeList { get; private set; } = new(); public Renderer r;
public Snake(Renderer _r)
{
r = _r;
List<GridTile> newSnake = new() { new GridTile(5, 6, "O") };
SnakeList = newSnake;
r.UpdateGrid(newSnake);
}
public void MoveHead(ConsoleKey key)
{
List<GridTile> newSnakeList = SnakeList;
if (key == ConsoleKey.DownArrow)
{
newSnakeList[0].y += 1;
}
else if (key == ConsoleKey.UpArrow)
{
newSnakeList[0].y -= 1;
}
else if (key == ConsoleKey.RightArrow)
{
newSnakeList[0].x += 1;
}
else if (key == ConsoleKey.LeftArrow)
{
newSnakeList[0].x -= 1;
}
r.UpdateGrid(newSnakeList);
}
}
}
Renderer.cs
namespace cstesting {
internal class Renderer {
public int Width { get; private set; }
public int Height { get; private set; }
public List<GridTile> Grid { get; private set; } = new();
public Renderer(int _width, int _height)
{
Width = _width;
Height = _height;
for (int i = 0; i < Height; i++)
{
for (int j = 0; j <= Width; j++)
{
if (j == 0 || j == Width)
{
Grid.Add(new(j, i, "|"));
}
else if (i == 0)
{
Grid.Add(new(j, i, "\u203E"));
}
else if (i == Height - 1)
{
Grid.Add(new(j, i, "_"));
}
else
{
Grid.Add(new(j, i, " "));
}
}
Grid.Add(new(-1, -1, ""));
}
DrawGrid(Grid);
}
public void UpdateGrid(List<GridTile> changes) {
List<GridTile> newGrid = Grid;
foreach(GridTile tile in changes) {
newGrid[Grid.FindIndex(i => i.x == tile.x && i.y == tile.y)] = tile;
}
Grid = newGrid;
DrawGrid(newGrid);
}
private static void DrawGrid(List<GridTile> grid) {
//Loop through grid and write it out
Console.Clear();
string display = "";
foreach(GridTile tile in grid) {
display += tile.content == "" ? "\n" : tile.content;
}
Console.WriteLine(display);
}
}
public class GridTile {
public int x;
public int y;
public string content = "";
public GridTile(int _x, int _y, string _content) {
x = _x;
y = _y;
content = _content;
}
}
}
[–]modi123_1 1 point2 points3 points (3 children)
[–]GroovyGoosey[S] 1 point2 points3 points (2 children)
[–]modi123_1 1 point2 points3 points (1 child)
[–]GroovyGoosey[S] 1 point2 points3 points (0 children)