我怎样才能让我的t-to-to游戏以平局结束? [英] How do I make it possible for my ti-tac-toe game to end in a tie?
本文介绍了我怎样才能让我的t-to-to游戏以平局结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在ruby中写了一个井字游戏程序。一切都在发挥作用,除了游戏不能以平局结束。有什么建议吗?
这是我的代码:
I wrote a tic-tac-toe program in ruby. Everything is working except that the game can't end in a tie. Any suggestions?
Here is my code:
class Game
def initialize
@board=Array.new
@board[1]="1 __|"
@board[2]="__"
@board[3]="|__"
@board[4]="\n2 __|"
@board[5]="__"
@board[6]="|__"
@board[7]="\n3 |"
@board[8]=" "
@board[9]="| "
@turn="o"
@win_status = false
end
def turn
@turn
end
def show_board
puts " 1 2 3"
@board.each do |i|
print i
end
puts ""
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
if y==1 && x==1 && !@board[1].match(/[xy]/)
@board[1]="1 _"+@turn+"|"
elsif y==2 && x==1 && !@board[2].match(/[xy]/)
@board[2]="_"+@turn
elsif y==3 && x==1 && !@board[3].match(/[xy]/)
@board[3]="|_"+@turn
elsif y==1 && x==2 && !@board[4].match(/[xy]/)
@board[4]="\n2 _"+@turn+"|"
elsif y==2 && x==2 && !@board[5].match(/[xy]/)
@board[5]="_"+@turn
elsif y==3 && x==2 && !@board[6].match(/[xy]/)
@board[6]="|_"+@turn
elsif y==1 && x==3 && !@board[7].match(/[xy]/)
@board[7]="\n3 "+@turn+"|"
elsif y==2 && x==3 && !@board[8].match(/[xy]/)
@board[8]=" "+@turn
elsif y==3 && x==3 && !@board[9].match(/[xy]/)
@board[9]="| "+@turn+" \n"
else
puts "You either entered an invalid coordinate or a a taken square. Please enter another coordinate"
make_move
end
end
def win_combo
return [[@board[1][4] + @board[2][1] + @board[3][2]], [@board[4][5] + @board[5][1] + @board[6][2]], [@board[7][5] + @board[8][1] + @board[9][2]],[@board[1][4] + @board[4][5] + @board[7][5]], [@board[2][1] + @board[5][1] + @board[8][1]], [@board[3][2] + @board[6][2] + @board[9][2]], [@board[1][4] + @board[5][1] + @board[9][2]], [@board[3][2] + @board[5][1] + @board[7][5]]]
end
def check_win
#if some row or column or diagonal is "xxx" or "ooo" then set @win_status = true
self.win_combo.each do |arr|
str = arr.join
if str == "xxx"
puts "\nX Wins!"
return true
elsif str == "ooo"
puts "\nO Wins!"
return true
end
end
return false
end
<pre lang="vb">g = Game.new
while g.check_win != true
g.show_board
g.set_turn
g.make_move
end
end
推荐答案
我认为你需要在check_win函数之后再添加一个子句
I think you need to add one more clause to check_win function after
if str == "xxx"
puts "\nX Wins!"
return true
elsif str == "ooo"
puts "\nO Wins!"
return true
else
#check for empty slots left
#if empty slot count = 0
# then game draw
# return true
#end
end
我的主要语言不是ruby,因此无法编写代码:)。
My primary language is not ruby so can't write code for that :).
这篇关于我怎样才能让我的t-to-to游戏以平局结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文