提问人:Eja 提问时间:3/11/2023 更新时间:3/11/2023 访问量:32
Ruby 中的输入是唯一一个在循环中运行的输入
Input in Ruby being the only one ran in loop
问:
我一直在尝试用 Ruby 编写一个基于井字游戏的火柴盒学习 AI,所以我首先创建了基本游戏。但是每次我重新实现游戏时,都会发生相同的错误。我不确定是否有特定的部分在做这件事,所以我将展示整个事情。无论如何,当数组中的所有值都为真时,游戏就应该结束了。(不要担心输赢的东西,我稍后会实现它。取而代之的是,程序只是输入用户,不停地,不停地输入。它不打印任何东西,即使我把打印语句作为测试,它甚至没有打印这些。done
game = Array.new(9, " ")
done = Array.new(9, false)
gameplay = true
while gameplay
input = gets.to_i
if !done.include?(false)
puts "game over!"
gameplay = false
break
end
if input < 0 || input > 8
puts "Put a number from 0 to 8!"
next
end
if(!done[input])
game[input] = "o"
done[input] = true
else
puts "That spot is filled!"
next
end
while true
cmove = rand 9
if done[cmove] == true
next
else
game[cmove] = "x"
done[cmove] = true
puts "The computer chose #{cmove}."
break
end
end
puts "#{game[0]}|#{game[1]}|#{game[2]}"
puts "#{game[3]}|#{game[4]}|#{game[5]}"
puts "#{game[6]}|#{game[7]}|#{game[8]}"
end
我希望程序说“游戏结束”,被第一个 if 语句捕获。
**我试过的:**
- 休息一下,再看一遍代码
- put put 语句来查看错误问题所在。
- 使用 ChatGPT(它是添加 !done.include?(假))
- 重新制作程序
答:
0赞
Siim Liiser
3/11/2023
#1
在进行最后一步之前,您正在检查游戏是否完成。
让我们来看看最后一步会发生什么。
game = Array.new(9, " ")
done = Array.new(9, false)
gameplay = true
while gameplay
# done is 8/9 true, 1/9 false
input = gets.to_i
if !done.include?(false) # done still has 1 false in it, this is skipped.
puts "game over!"
gameplay = false
break
end
if input < 0 || input > 8
puts "Put a number from 0 to 8!"
next
end
if(!done[input]) # You chose a valid move.
game[input] = "o"
done[input] = true # done is updated, now it's 100% full of true
else
puts "That spot is filled!"
next
end
while true
cmove = rand 9
if done[cmove] == true # Since done is full, computer will always reach this case
next # and repeat. It will loop here forever.
else
game[cmove] = "x"
done[cmove] = true
puts "The computer chose #{cmove}."
break
end
end
puts "#{game[0]}|#{game[1]}|#{game[2]}"
puts "#{game[3]}|#{game[4]}|#{game[5]}"
puts "#{game[6]}|#{game[7]}|#{game[8]}"
end
在移动后添加游戏完成检查。
game = Array.new(9, " ")
done = Array.new(9, false)
gameplay = true
while gameplay
input = gets.to_i
if input < 0 || input > 8
puts "Put a number from 0 to 8!"
next
end
if(!done[input])
game[input] = "o"
done[input] = true
else
puts "That spot is filled!"
next
end
if !done.include?(false)
puts "game over!"
gameplay = false
break
end
while true
cmove = rand 9
if done[cmove] == true
next
else
game[cmove] = "x"
done[cmove] = true
puts "The computer chose #{cmove}."
break
end
end
puts "#{game[0]}|#{game[1]}|#{game[2]}"
puts "#{game[3]}|#{game[4]}|#{game[5]}"
puts "#{game[6]}|#{game[7]}|#{game[8]}"
end
下一个:循环我的函数有问题吗?
评论