我写了一个用户与用户的井字游戏程序。代码中有一个 while 循环,使它一遍又一遍地运行。但是,当有人获胜时,这个循环不会中断。有什么建议么?
这是我的代码:
class Game
def initialize
@board=Array.new
@board[1]="__|"
@board[2]="__"
@board[3]="|__"
@board[4]="\n__|"
@board[5]="__"
@board[6]="|__"
@board[7]="\n |"
@board[8]=" "
@board[9]="| "
@turn="x"
@win_status = false
end
def win_status
return @win_status
end
def show_board
@board.each do |i|
print i
end
end
def set_turn #switches turns
if @turn == "x"
@turn = "o"
else @turn == "o"
@turn = "x"
end
end
def make_move
puts "Enter x coordinate"
x=gets.to_i
puts "Enter y coordinate"
y=gets.to_i
@board[1]="_"+@turn+"|" if y==1 && x==1
@board[2]="_"+@turn if y==2 && x==1
@board[3]="|_"+@turn if y==3 && x==1
@board[4]="\n_"+@turn+"|" if y==1 && x==2
@board[5]="_"+@turn if y==2 && x==2
@board[6]="|_"+@turn if y==3 && x==2
@board[7]="\n "+@turn+"|" if y==1 && x==3
@board[8]=" "+@turn if y==2 && x==3
@board[9]="|"+@turn+" \n" if y==3 && x==3
end
def win_combo
@win_combo = [*[@board[1][1] + @board[2][1] + @board[3][2]], [@board[4][2] + @board[5][1] + @board[6][2]], [@board[7][1] + @board[8][1] + @board[9][1]],[@board[1][1] + @board[4][2] + @board[7][1]], [@board[2][1] + @board[5][1] + @board[8][1]], [@board[3][2] + @board[6][2] + @board[9][1]], [@board[1][1] + @board[5][1] + @board[9][1]], [@board[3][2] + @board[5][1] + @board[7][1]]]
end
def check_win
#if some row or column or diagonal is "xxx" or "ooo" then set @win_status = true
@win_combo.each do |str|
if str == "xxx" or str == "ooo"
@win_status = true
end
end
puts @win_status
end
end
g = Game.new
while g.win_status != true
g.set_turn
g.make_move
g.show_board
g.win_combo
g.check_win
end