Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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
Add Comment
Please, Sign In to add comment