Warning! It seems that you are using Dodona within another webpage, so not everything may work properly. Let your teacher know so that he can solve the problem by adjusting a setting in the learning environment. In the meantime, you can click this link to open Dodona in a new window.
Warning! The page was not fully loaded, probably because of a network issue. It could be that not all functionalities work as expected. Please try reloading the page.
Csharp exercise
Snakes and ladders
Sign in to hand in your solution and get feedback.
// Snakes and ladders program
using System;
using System.Collections.Generic;
class Submission
{
// -------------------------
// Globals
// -------------------------
static Random random_generator = new Random();
// -------------------------
// Subprograms
// -------------------------
static void Play(int[] board, int[] players)
{
int current_player = 0;
bool game_won = false;
while (!game_won)
{
int player_square = players[current_player];
Console.WriteLine();
Console.WriteLine("------------------------------------");
Console.WriteLine($"Player {current_player + 1}, it's your turn.");
Console.WriteLine($"You are on square {player_square}");
Console.WriteLine("Press Enter to roll the dice.");
Console.ReadLine();
int dice = random_generator.Next(1, 7);
Console.WriteLine($"You rolled a {dice}");
player_square += dice;
if (player_square > board.Length - 1)
{
player_square = board.Length - 1;
}
Console.WriteLine($"You moved to square {player_square}");
int board_square = board[player_square];
if (board_square < player_square)
{
Console.WriteLine("Oh no, you landed on a snake.");
player_square = board_square;
Console.WriteLine($"You are now on square {player_square}");
}
else if (board_square > player_square)
{
Console.WriteLine("Yay, you landed on a ladder.");
player_square = board_square;
Console.WriteLine($"You are now on square {player_square}");
}
if (player_square >= board.Length - 1)
{
game_won = true;
Console.WriteLine($"Player {current_player + 1} wins the game!");
}
else
{
players[current_player] = player_square;
Console.WriteLine("Press Enter for the next player to take their turn.");
Console.ReadLine();
current_player = (current_player + 1) % players.Length;
}
}
}
static int[] initialise_board(int squares)
{
int[] board = new int[squares + 1];
for (int square = 0; square <= squares; square++)
{
board[square] = square;
}
board[4] = 7;
board[6] = 15;
board[18] = 23;
board[19] = 2;
board[24] = 17;
return board;
}
static int[] Initialise_players()
{
int[] players = new int[2] { 1, 1 };
return players;
}
// -------------------------
// Main program
// -------------------------
public static void Main(string[] args)
{
int[] board = initialise_board(25);
int[] players = Initialise_players();
Play(board, players);
}
}