Guest User

Untitled

a guest
Feb 19th, 2018
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. # Ruby implementation of Lab 7 for 1005ICT (Java Programming) at Griffith Univeristy.
  2. # Why? To practice learning Ruby
  3.  
  4. class GameBoard
  5.  
  6. attr_accessor :board
  7.  
  8. def initialize(row, col)
  9. @board = Array.new(row) { |row| Array.new(col, 0) }
  10. end
  11.  
  12. def reset_board
  13. @board.each { |row| row.fill(0) }
  14. end
  15.  
  16. def board_value(row, col)
  17. puts "Value of board at #{ row },#{ col } is #{ @board[row][col] }"
  18. end
  19.  
  20. def make_move(row, col, player)
  21. if row < @board.size and col < @board[row].size and @board[row][col] == 0
  22. @board[row][col] = player
  23. end
  24. end
  25.  
  26. def print_board
  27. puts " #{ (0...@board.size).to_a.join(' ') }"
  28. @board.collect { |row| puts "#{ @board.index(row) }: #{ row.join(' ') }" }
  29. end
  30.  
  31. def random_move(player)
  32. make_move(rand(@board.size), rand(@board.size), player)
  33. end
  34.  
  35. # Plays for a specified number of games with the specified number of players. Each
  36. # player takes their turn in succession and performs a random move
  37. def play_random_game(games, players)
  38. player = players
  39. (1..games).to_a.each do |game|
  40. if player != 0
  41. random_move(player)
  42. player -= 1
  43. else
  44. player = players
  45. end
  46. end
  47. end
  48.  
  49. end
  50.  
  51. # Let's play a game!
  52.  
  53. board = GameBoard.new(10, 10) # Instantiate GameBoard
  54. board.make_move(19, 19, 8) # Attempt to place at player at an invalid position
  55. board.play_random_game(100, 6) # Play 100 games with 6 players
  56. board.board_value(7, 5) # Print which player is at this position on the board to stdout
  57. board.print_board # Print board to stdout
Add Comment
Please, Sign In to add comment