Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

most readable programming language to simulate 10,000 chutes and ladders game plays?

I'm wondering what language would be most suitable to simulate the game Chutes and Ladders (Snakes and Ladders in some countries). I'm looking to collect basic stats, like average and standard deviation of game length (in turns), probability of winning based on turn order (who plays first, second, etc.), and anything else of interest you can think of. Specifically, I'm looking for the implementation that is most readable, maintainable, and modifiable. It also needs to be very brief.

If you're a grown-up and don't spend much time around young kids then you probably don't remember the game that well. I'll remind you:

  • There are 100 squares on the board.
  • Each player takes turn spinning a random number from 1-6 (or throwing a dice).
  • The player then advances that many squares.
  • Some squares are at the base of a ladder; landing on one of these squares means the player gets to climb the ladder, advancing the player's position to a predetermined square.
  • Some squares are at the top of a slide (chute or snake); landing on one of these squares means the player must slide down, moving the player's position back to a predetermined square.
  • Whichever player gets to position 100 first is the winner.
like image 581
Landon Kuhn Avatar asked Nov 26 '22 21:11

Landon Kuhn


1 Answers

This is a bit rough, but it should work:

class Board
  attr_accessor :winner

  def initialize(players, &blk)
    @chutes, @ladders = {}, {}
    @players = players
    @move = 0
    @player_locations = Hash.new(0)
    self.instance_eval(&blk)
  end

  def chute(location)
    @chutes[location[:from]] = location[:to]
  end

  def ladder(location)
    @ladders[location[:from]] = location[:to]
  end

  def spin
    player = @move % @players
    die = rand(6) + 1
    location = (@player_locations[player] += die)

    if endpoint = @chutes[location] || endpoint = @ladders[location]
      @player_locations[player] = endpoint
    end

    if @player_locations[player] >= 100
      @winner = player
    end

    @move += 1
  end
end

num_players = 4

board = Board.new num_players, do
  ladder :from => 4, :to => 14
  ladder :from => 9, :to => 31
  # etc.
  chute :from => 16, :to => 6
  # etc.
end

until board.winner
  board.spin
end

puts "Player #{board.winner} is the winner!"
like image 95
Yehuda Katz Avatar answered Dec 15 '22 00:12

Yehuda Katz