这些是不完整的代码,但它至少应该更新游戏板,直到它填满并出错。我不知道为什么它没有更新电路板。它确实在注册我的输入以及计算机,因为游戏确实打印了我的坐标。有人可以帮我弄清楚我做错了吗?
class Board
attr_reader :grid
def initialize
@grid = Array.new(3) { Array.new(3) }
@human = HumanPlayer.new
@computer = ComputerPlayer.new
@game = Game.new
end
def place_mark(pos)
if (pos[0] < 0 || pos[0] > 2) || (pos[1] < 0 || pos[1] > 2)
puts "Invalid coordinates! Please try again!"
@game.play
elsif empty?(pos)
if @game.current_player == "human"
puts "Player 1 goes: #{pos}"
@grid[pos[0]][pos[1]] = 'X'
elsif @game.current_player == "computer"
puts "Computer goes: #{pos}"
@grid[pos[0]][pos[1]] = "O"
end
if winner
puts "Congratulations! #{@game.current_player} wins!"
else
@game.switch_players!
end
else
puts "Space Taken! Please Try Again!"
@game.play
end
end
def empty?(pos)
@grid[pos[0]][pos[1]].nil?
end
def winner
#Need to set winning combinations
false
end
def over?
false #for now, it will go until all spaces are filled. Still need to set end game condition.
end
end
class HumanPlayer
def display
p Board.new.grid
end
def get_move
puts "Please enter your the quadrant you wish to place your mark."
pos = gets.chomp.scan(/[0-9]/).map!(&:to_i)
Board.new.place_mark(pos)
end
end
class ComputerPlayer
def get_move
x = rand(3).round
y = rand(3).round
Board.new.place_mark([x,y])
end
end
class Game
@@turn_tracker = 0
def current_player
@@turn_tracker.even? ? "human" : "computer"
end
def switch_players!
@@turn_tracker += 1
play
end
def play_turn
if current_player == "human"
HumanPlayer.new.display
Board.new.place_mark(HumanPlayer.new.get_move)
elsif current_player == "computer"
ComputerPlayer.new.get_move
end
end
def play
play_turn until @@turn_tracker == 9 #Still need to set win conditions
end
end
board = Game.new
board.play
答案 0 :(得分:1)
你总是会产生一个新的棋盘,然后当然会再次使用起始位置:
class HumanPlayer
def display
p Board.new.grid
end
...
end
如果你想学点东西,我不会给你一个解决方案。