Created
September 3, 2008 10:14
-
-
Save tatey/8566 to your computer and use it in GitHub Desktop.
Solution to Lab 7 for 1005ICT in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Ruby implementation of Lab 7 for 1005ICT (Java Programming) at Griffith Univeristy. | |
# Why? To practice learning Ruby | |
class GameBoard | |
attr_accessor :board | |
def initialize(row, col) | |
@board = Array.new(row) { |row| Array.new(col, 0) } | |
end | |
def reset_board | |
@board.each { |row| row.fill(0) } | |
end | |
def board_value(row, col) | |
puts "Value of board at #{ row },#{ col } is #{ @board[row][col] }" | |
end | |
def make_move(row, col, player) | |
if row < @board.size and col < @board[row].size and @board[row][col] == 0 | |
@board[row][col] = player | |
end | |
end | |
def print_board | |
puts " #{ ([email protected]).to_a.join(' ') }" | |
@board.collect { |row| puts "#{ @board.index(row) }: #{ row.join(' ') }" } | |
end | |
def random_move(player) | |
make_move(rand(@board.size), rand(@board.size), player) | |
end | |
# Plays for a specified number of games with the specified number of players. Each | |
# player takes their turn in succession and performs a random move | |
def play_random_game(games, players) | |
player = players | |
(1..games).to_a.each do |game| | |
if player != 0 | |
random_move(player) | |
player -= 1 | |
else | |
player = players | |
end | |
end | |
end | |
end | |
# Let's play a game! | |
board = GameBoard.new(10, 10) # Instantiate GameBoard | |
board.make_move(19, 19, 8) # Attempt to place at player at an invalid position | |
board.play_random_game(100, 6) # Play 100 games with 6 players | |
board.board_value(7, 5) # Print which player is at this position on the board to stdout | |
board.print_board # Print board to stdout |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment