Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Tweeted twitter.com/StackCodeReview/status/1449933519673831431
Became Hot Network Question
deleted 27 characters in body
Source Link
  1. I need to be able to move my token.
  2. The token starts in the square 1.
  3. If the token is on squearedsquare 1 and is moved by 3 then the token is on square 4.
  4. A player can win the game.
  5. The first in reachwho reaches the square 100 is the winner.
  6. You can't over-square the board. If you do it your position will be remind toremain the previous onesame. (97 + 4 = 97)
  7. The moves are based inon a roll dice between 1 and 6.
  8. The player rollrolls the dice, then movemoves the token.

Keeping all this in mind as I did this.

using System;
using System.Collections.Generic;

namespace Snakes_and_ladders
{
    class CBoard
    {
        private int[] board;
        List<CPlayer> players = new List<CPlayer>();

        public int[] Board { get => board; }
        public CBoard()
        {
            // Se crea unA tablero100-cell deboard 100is celdascreated porby defectodefault. 
            board = new int[100];
            Array.Clear(board, 0, board.Length);
        }

        /*
        */ FuncionFunction parato crearcreate Ladders yand Snakes.Se 
 changes the value
      * Se cambia el// valorof delthe array enin elthe index [i-1] siendobeing i lathe key del diccionario.of the
        *// eldictionary.the valorvalue quethat seis guardasaved enin esethat index correspondecorresponds
 al valor del tablero donde se 
  // to the value of the board *where moverathe elplayer jugadormoves enin casocase deof
 caer en dicho     // falling into said Index.
        * //
        *// Ex: Key => 2, ValorValue => 10 implica queimplies existethat unathere escalerais quea valadder desdethat
 la celda 
      // goes from *cell 1 a lato celdacell 9 del tablero.
      of the */board.
        private void createSnakesOrLadders(Dictionary<int, int> dataDict)
        {
            foreach (KeyValuePair<int, int> data in dataDict)
            {
                board[data.Key - 1] = data.Value - 1;
            }
        }
 

        /*  Sobrecarga/ deDefault constructor por defectooverload
        *// Creates Creaan unA boardx deL AxLboard +by añadiradding escalerasladders yand serpientessnakes.
        */
        public CBoard(int altura, int largo,
            Dictionary<int, int> ladders = null, Dictionary<int, int> snakes = null)
        {

            // ComoAt minimoa esminimum, necesarioa un2x2 tableroboard deis 2x2necessary.
            if (altura < 2 || largo < 2)
                throw new Exception("La"The alturaheight yand largolength necesitaneed serto albe menosat mayorleast agreater than 1.");

            // TamañoInitial inicialsize delof numerothe denumber of ladders yand snakes enon elthe tableroboard.
            int ladderSize = 0;
            int snakesSize = 0;

            // SiIf elthe tableroboard nois esnot null, guardamoswe elsave numerothe realactual denumber of ladders yand snakes.
            if (!(ladders is null))
                ladderSize = ladders.Count;

            if (!(snakes is null))
                snakesSize = snakes.Count;

            // CreamosWe elcreate tablerothe board, conwith valoresvalues aset to 0.
            board = new int[altura * largo];
            Array.Clear(board, 0, board.Length);

            // Si elIf tamañothe total delsize numeroof dethe number of ladders yand snakes es menoris queless lathan mitadhalf delthe tableroboard
            // Se crean los ladders yand snakes enare elcreated tableroon the board. SinoIf not, sethe lanzaexception lais excepcionthrown.
            if ((ladderSize * 2) + (snakesSize * 2) / 2 < board.Length)
            {
                if (!(ladders is null))
                    createSnakesOrLadders(ladders);

                if (!(snakes is null))
                    createSnakesOrLadders(snakes);
            }
            else
            {
                throw new Exception("La suma"The total desum of Snakes yand Ladders no puede superarcannot elexceed 50% delof tablerothe board.");
            }
        }
    }
}

using System;
using System.Threading;

namespace Snakes_and_ladders
{
    class CPlayer
    {
        int[] board;
        private int position = 0;
        private string nickName = null;
        private int diceResult = 0;
        private bool winner = false;

        public int Position { get => position + 1; }
        public int DiceResult { get => diceResult;  }
        public string NickName { get => nickName; }
        public bool Winner { get => winner; }


        public CPlayer(string nickName, CBoard board) {
            this.nickName = nickName;
            this.board = board.Board;
        }

        public void Roll()
        {
            // Se espereWait 30 milisegundos para cambiarmilliseconds lato semillachange delthe random seed.
            Random rnd = new Random();
            Thread.Sleep(30);
            diceResult = rnd.Next(1, 7);
        }

        public void Move()
        {
            // Move the player N dice cells.
            if (position + diceResult < board.Length)
                if (board[position + diceResult] == 0)
                    position = position + diceResult;
                else
                    position = board[diceResult + position];

            if (position == board.Length - 1)
                winner = true;
        }
    }
}
  1. I need to be able to move my token.
  2. The token starts in the square 1.
  3. If the token is on squeared 1 and is moved 3 then the token is on square 4.
  4. A player can win the game.
  5. The first in reach the square 100 is the winner.
  6. You can't over-square the board. If you do it your position will be remind to the previous one. (97 + 4 = 97)
  7. The moves are based in a roll dice between 1 and 6.
  8. The player roll the dice, then move the token.

Keeping all this in mind I did this.

using System;
using System.Collections.Generic;

namespace Snakes_and_ladders
{
    class CBoard
    {
        private int[] board;
        List<CPlayer> players = new List<CPlayer>();

        public int[] Board { get => board; }
        public CBoard()
        {
            // Se crea un tablero de 100 celdas por defecto. 
            board = new int[100];
            Array.Clear(board, 0, board.Length);
        }

        /*
        * Funcion para crear Ladders y Snakes. 
         * Se cambia el valor del array en el index [i-1] siendo i la key del diccionario. 
        * el valor que se guarda en ese index corresponde al valor del tablero donde se 
         * movera el jugador en caso de caer en dicho Index.
        * 
        * Ex: Key => 2, Valor => 10 implica que existe una escalera que va desde la celda 
         * 1 a la celda 9 del tablero.
        */
        private void createSnakesOrLadders(Dictionary<int, int> dataDict)
        {
            foreach (KeyValuePair<int, int> data in dataDict)
            {
                board[data.Key - 1] = data.Value - 1;
            }
        }
 

        /*  Sobrecarga de constructor por defecto
        *  Crea un board de AxL + añadir escaleras y serpientes.
        */
        public CBoard(int altura, int largo,
            Dictionary<int, int> ladders = null, Dictionary<int, int> snakes = null)
        {

            // Como minimo es necesario un tablero de 2x2.
            if (altura < 2 || largo < 2)
                throw new Exception("La altura y largo necesita ser al menos mayor a 1.");

            // Tamaño inicial del numero de ladders y snakes en el tablero.
            int ladderSize = 0;
            int snakesSize = 0;

            // Si el tablero no es null, guardamos el numero real de ladders y snakes.
            if (!(ladders is null))
                ladderSize = ladders.Count;

            if (!(snakes is null))
                snakesSize = snakes.Count;

            // Creamos el tablero, con valores a 0.
            board = new int[altura * largo];
            Array.Clear(board, 0, board.Length);

            // Si el tamaño total del numero de ladders y snakes es menor que la mitad del tablero
            // Se crean los ladders y snakes en el tablero. Sino, se lanza la excepcion.
            if ((ladderSize * 2) + (snakesSize * 2) / 2 < board.Length)
            {
                if (!(ladders is null))
                    createSnakesOrLadders(ladders);

                if (!(snakes is null))
                    createSnakesOrLadders(snakes);
            }
            else
            {
                throw new Exception("La suma total de Snakes y Ladders no puede superar el 50% del tablero.");
            }
        }
    }
}

using System;
using System.Threading;

namespace Snakes_and_ladders
{
    class CPlayer
    {
        int[] board;
        private int position = 0;
        private string nickName = null;
        private int diceResult = 0;
        private bool winner = false;

        public int Position { get => position + 1; }
        public int DiceResult { get => diceResult;  }
        public string NickName { get => nickName; }
        public bool Winner { get => winner; }


        public CPlayer(string nickName, CBoard board) {
            this.nickName = nickName;
            this.board = board.Board;
        }

        public void Roll()
        {
            // Se espere 30 milisegundos para cambiar la semilla del random.
            Random rnd = new Random();
            Thread.Sleep(30);
            diceResult = rnd.Next(1, 7);
        }

        public void Move()
        {
            // Move the player N dice cells.
            if (position + diceResult < board.Length)
                if (board[position + diceResult] == 0)
                    position = position + diceResult;
                else
                    position = board[diceResult + position];

            if (position == board.Length - 1)
                winner = true;
        }
    }
}
  1. I need to be able to move my token.
  2. The token starts in the square 1.
  3. If the token is on square 1 and is moved by 3 then the token is on square 4.
  4. A player can win the game.
  5. The first who reaches the square 100 is the winner.
  6. You can't over-square the board. If you do it your position will remain the same. (97 + 4 = 97)
  7. The moves are based on a roll dice between 1 and 6.
  8. The player rolls the dice, then moves the token.

Keeping all this in mind as I did.

using System;
using System.Collections.Generic;

namespace Snakes_and_ladders
{
    class CBoard
    {
        private int[] board;
        List<CPlayer> players = new List<CPlayer>();

        public int[] Board { get => board; }
        public CBoard()
        {
            // A 100-cell board is created by default.
            board = new int[100];
            Array.Clear(board, 0, board.Length);
        }

        // Function to create Ladders and Snakes.Se changes the value
        // of the array in the index [i-1] being i the key of the
        // dictionary.the value that is saved in that index corresponds
        // to the value of the board where the player moves in case of
        // falling into said Index.
        //
        // Ex: Key => 2, Value => 10 implies that there is a ladder that
        // goes from cell 1 to cell 9 of the board.
        private void createSnakesOrLadders(Dictionary<int, int> dataDict)
        {
            foreach (KeyValuePair<int, int> data in dataDict)
            {
                board[data.Key - 1] = data.Value - 1;
            }
        }

        // Default constructor overload
        // Creates an A x L board by adding ladders and snakes.
        public CBoard(int altura, int largo,
            Dictionary<int, int> ladders = null, Dictionary<int, int> snakes = null)
        {

            // At a minimum, a 2x2 board is necessary.
            if (altura < 2 || largo < 2)
                throw new Exception("The height and length need to be at least greater than 1.");

            // Initial size of the number of ladders and snakes on the board.
            int ladderSize = 0;
            int snakesSize = 0;

            // If the board is not null, we save the actual number of ladders and snakes.
            if (!(ladders is null))
                ladderSize = ladders.Count;

            if (!(snakes is null))
                snakesSize = snakes.Count;

            // We create the board, with values set to 0.
            board = new int[altura * largo];
            Array.Clear(board, 0, board.Length);

            // If the total size of the number of ladders and snakes is less than half the board
            // ladders and snakes are created on the board. If not, the exception is thrown.
            if ((ladderSize * 2) + (snakesSize * 2) / 2 < board.Length)
            {
                if (!(ladders is null))
                    createSnakesOrLadders(ladders);

                if (!(snakes is null))
                    createSnakesOrLadders(snakes);
            }
            else
            {
                throw new Exception("The total sum of Snakes and Ladders cannot exceed 50% of the board.");
            }
        }
    }
}

using System;
using System.Threading;

namespace Snakes_and_ladders
{
    class CPlayer
    {
        int[] board;
        private int position = 0;
        private string nickName = null;
        private int diceResult = 0;
        private bool winner = false;

        public int Position { get => position + 1; }
        public int DiceResult { get => diceResult;  }
        public string NickName { get => nickName; }
        public bool Winner { get => winner; }


        public CPlayer(string nickName, CBoard board) {
            this.nickName = nickName;
            this.board = board.Board;
        }

        public void Roll()
        {
            // Wait 30 milliseconds to change the random seed.
            Random rnd = new Random();
            Thread.Sleep(30);
            diceResult = rnd.Next(1, 7);
        }

        public void Move()
        {
            // Move the player N dice cells.
            if (position + diceResult < board.Length)
                if (board[position + diceResult] == 0)
                    position = position + diceResult;
                else
                    position = board[diceResult + position];

            if (position == board.Length - 1)
                winner = true;
        }
    }
}
Source Link
Sharki
  • 189
  • 6

Snakes and Ladders OOP

I've created a simple Snakes and Ladders game. The goal is improving my knowledge about OOP.There are some basic rules.

  1. I need to be able to move my token.
  2. The token starts in the square 1.
  3. If the token is on squeared 1 and is moved 3 then the token is on square 4.
  4. A player can win the game.
  5. The first in reach the square 100 is the winner.
  6. You can't over-square the board. If you do it your position will be remind to the previous one. (97 + 4 = 97)
  7. The moves are based in a roll dice between 1 and 6.
  8. The player roll the dice, then move the token.

Keeping all this in mind I did this.

Class CBoard.cs

using System;
using System.Collections.Generic;

namespace Snakes_and_ladders
{
    class CBoard
    {
        private int[] board;
        List<CPlayer> players = new List<CPlayer>();

        public int[] Board { get => board; }
        public CBoard()
        {
            // Se crea un tablero de 100 celdas por defecto. 
            board = new int[100];
            Array.Clear(board, 0, board.Length);
        }

        /*
        * Funcion para crear Ladders y Snakes. 
        * Se cambia el valor del array en el index [i-1] siendo i la key del diccionario. 
        * el valor que se guarda en ese index corresponde al valor del tablero donde se 
        * movera el jugador en caso de caer en dicho Index.
        * 
        * Ex: Key => 2, Valor => 10 implica que existe una escalera que va desde la celda 
        * 1 a la celda 9 del tablero.
        */
        private void createSnakesOrLadders(Dictionary<int, int> dataDict)
        {
            foreach (KeyValuePair<int, int> data in dataDict)
            {
                board[data.Key - 1] = data.Value - 1;
            }
        }


        /*  Sobrecarga de constructor por defecto
        *  Crea un board de AxL + añadir escaleras y serpientes.
        */
        public CBoard(int altura, int largo,
            Dictionary<int, int> ladders = null, Dictionary<int, int> snakes = null)
        {

            // Como minimo es necesario un tablero de 2x2.
            if (altura < 2 || largo < 2)
                throw new Exception("La altura y largo necesita ser al menos mayor a 1.");

            // Tamaño inicial del numero de ladders y snakes en el tablero.
            int ladderSize = 0;
            int snakesSize = 0;

            // Si el tablero no es null, guardamos el numero real de ladders y snakes.
            if (!(ladders is null))
                ladderSize = ladders.Count;

            if (!(snakes is null))
                snakesSize = snakes.Count;

            // Creamos el tablero, con valores a 0.
            board = new int[altura * largo];
            Array.Clear(board, 0, board.Length);

            // Si el tamaño total del numero de ladders y snakes es menor que la mitad del tablero
            // Se crean los ladders y snakes en el tablero. Sino, se lanza la excepcion.
            if ((ladderSize * 2) + (snakesSize * 2) / 2 < board.Length)
            {
                if (!(ladders is null))
                    createSnakesOrLadders(ladders);

                if (!(snakes is null))
                    createSnakesOrLadders(snakes);
            }
            else
            {
                throw new Exception("La suma total de Snakes y Ladders no puede superar el 50% del tablero.");
            }
        }
    }
}

Class CPlayer.cs

using System;
using System.Threading;

namespace Snakes_and_ladders
{
    class CPlayer
    {
        int[] board;
        private int position = 0;
        private string nickName = null;
        private int diceResult = 0;
        private bool winner = false;

        public int Position { get => position + 1; }
        public int DiceResult { get => diceResult;  }
        public string NickName { get => nickName; }
        public bool Winner { get => winner; }


        public CPlayer(string nickName, CBoard board) {
            this.nickName = nickName;
            this.board = board.Board;
        }

        public void Roll()
        {
            // Se espere 30 milisegundos para cambiar la semilla del random.
            Random rnd = new Random();
            Thread.Sleep(30);
            diceResult = rnd.Next(1, 7);
        }

        public void Move()
        {
            // Move the player N dice cells.
            if (position + diceResult < board.Length)
                if (board[position + diceResult] == 0)
                    position = position + diceResult;
                else
                    position = board[diceResult + position];

            if (position == board.Length - 1)
                winner = true;
        }
    }
}

Program.cs

using System;
using System.Collections.Generic;

namespace Snakes_and_ladders
{
    class Program
    {
        static void Main(string[] args)
        {
            // Ladders
            Dictionary<int, int> ladderDicctionary = new Dictionary<int, int>()
            {
                {2, 38}, {7, 14}, {8, 31}, {16, 26}, {21, 42},
                {28, 84}, {36, 44}, {51, 67}, {71, 91}, {78, 98}, {87, 94}
            };

            // Snakes
            Dictionary<int, int> snakesDicctionary = new Dictionary<int, int>()
            {
                {15, 5}, {48, 10}, {45, 24}, {61, 18}, {63, 59},
                {73, 52}, {88, 67}, {91, 87}, {94, 74}, {98, 79}
            };

            CBoard customBoard = new CBoard(10, 10, ladderDicctionary, snakesDicctionary);

            // Board by default.
            CBoard board = new CBoard();

            List<CPlayer> players = new List<CPlayer>();

            int n_players = 0;
            do
            {
                Console.Write("Enter the number of players: ");
                n_players = Convert.ToInt32(Console.ReadLine());

                if(n_players <= 1)
                    Console.WriteLine("The total of players need to be 2 or more.");

            } while (n_players <= 1);
            

            for(int i=1; i < n_players + 1; i++)
            {
                Console.Write("Enter the name for the player {0}: ", i);
                string nickName = Console.ReadLine();

                players.Add(new CPlayer(nickName, customBoard));
            }

            string pressed = "";
            int count = 0;

            do
            {
                if (count >= n_players)
                    count = 0;

                CPlayer currentPlayer = players[count];
                Console.WriteLine("It's the player {0}'s turn", currentPlayer.NickName);
                Console.WriteLine("Press R to Roll the die or A to abort the game.");
                pressed = Console.ReadLine();

                if(pressed.Equals("R", StringComparison.CurrentCultureIgnoreCase)) {

                    Console.WriteLine("--------------------------------");

                    currentPlayer.Roll();
                    Console.WriteLine("Dice's result: {0} ", currentPlayer.DiceResult);

                    int previousPosition = currentPlayer.Position;
                    currentPlayer.Move();
                    Console.WriteLine("You moved from cell [{0}] ====> to cell [{1}]", previousPosition, currentPlayer.Position);

                    if (currentPlayer.Winner)
                    {
                        Console.WriteLine("Player {0} won the game.", currentPlayer.NickName);
                        break;
                    }

                    Console.WriteLine("--------------------------------");
                    count++;
                }

            } while (!pressed.Equals("A", StringComparison.CurrentCultureIgnoreCase));

            Console.ReadLine();
        }
    }
}

Based on the code, I'd like to know what I could improve, what mistakes I did, what advice you'd give me, in a nutshell: How could I improve the code and be better at OOP. Thanks!