编辑:我发现了,这是一个非常明显的错误(我使用winLoseDraw()而不是分配给它的变量...)
我将此代码作为创建不使用任何if语句的剪刀石头布游戏的挑战。由于某些原因,while循环无法正常工作(尽管我在C ++中多次使用这种代码)。
从本质上讲,如果一切顺利,程序将执行以下操作:创建一个包含所有可能组合的数组([计算机获胜] [计算机失败] [平局]),一个数组
1.为计算机获取一个随机数(对于石头,纸张,剪刀,可以为0、1、2。)
2.要求玩家输入石头,纸或剪刀。
3.创建一个[计算机,播放器]的数组。
4.检查谁赢了。
我尝试打印,尽管它确实找到了正确的组合,但是由于某种原因,winLoseDraw()中的while循环运行了三次。
import random
true = True
false = False
rock = "ROCK"
paper = "PAPER"
sissors = "SISSORS"
possibleHands = [rock, paper, sissors]
possibleCombinations = [ [[paper, rock], [rock, sissors], [sissors, paper]],
[[sissors, rock], [paper, sissors], [rock, paper]],
[[rock, rock], [sissors, sissors], [paper, paper]]
]
results = ['WIN', 'LOST', 'DRAWED']
def getRandomHandComp():
x = random.randint(0, 2)
handComp = possibleHands[x]
return handComp
def getHandPlayer():
x = input("please choose: 0 = rock, 1 = paper, 2 = sissors ")
while (x != '1') and (x != '0') and (x!= '2'):
x = input("Invalid! please choose: 0 = rock, 1 = paper, 2 = sissors")
handPlayerNum = int(x)
handPlayer = possibleHands[handPlayerNum]
return handPlayer
def winLoseDraw():
comp = getRandomHandComp()
player = getHandPlayer()
match = [comp, player]
found = false
number1 = 0
number2 = 0
while (not found) and (number1 < 3):
while (not found) and (number2 < 3):
found = possibleCombinations[number1][number2] == match
print(match)
print(possibleCombinations[number1][number2])
print(found)
number2 += 1
print(found)
number2 = 0
number1 += 1
number1 -= 1
result = results[number1]
return [result, comp, player]
gameOver = false
trueFalse = [false, true]
while not gameOver:
result = winLoseDraw()[0]
print('COMPUTER PLAYED ' + winLoseDraw()[1] + '!' + 'YOU PLAYED ' + winLoseDraw()[2] + '!')
print('YOU ' + result + '!')
x = input("Wanna continue? 0 = yes 1 = no")
while x != '1' and x != '0':
x = input("INVALID INPUT! Wanna continue? 0 = yes 1 = no")
gameOver = trueFalse[int(x)]
这是我得到的输出:
please choose: 0 = rock, 1 = paper, 2 = sissors 1
['ROCK', 'PAPER']
['PAPER', 'ROCK']
False
['ROCK', 'PAPER']
['ROCK', 'SISSORS']
False
['ROCK', 'PAPER']
['SISSORS', 'PAPER']
False
False
['ROCK', 'PAPER']
['SISSORS', 'ROCK']
False
['ROCK', 'PAPER']
['PAPER', 'SISSORS']
False
['ROCK', 'PAPER']
['ROCK', 'PAPER']
True
True
please choose: 0 = rock, 1 = paper, 2 = sissors 1
['SISSORS', 'PAPER']
['PAPER', 'ROCK']
False
['SISSORS', 'PAPER']
['ROCK', 'SISSORS']
False
['SISSORS', 'PAPER']
['SISSORS', 'PAPER']
True
True
please choose: 0 = rock, 1 = paper, 2 = sissors 1
['ROCK', 'PAPER']
['PAPER', 'ROCK']
False
['ROCK', 'PAPER']
['ROCK', 'SISSORS']
False
['ROCK', 'PAPER']
['SISSORS', 'PAPER']
False
False
['ROCK', 'PAPER']
['SISSORS', 'ROCK']
False
['ROCK', 'PAPER']
['PAPER', 'SISSORS']
False
['ROCK', 'PAPER']
['ROCK', 'PAPER']
True
True
COMPUTER PLAYED SISSORS!YOU PLAYED PAPER!
YOU LOST!
Wanna continue? 0 = yes 1 = no
我怀疑随机出现了问题(我已经在C ++中使用过这种代码,如果我记得的话,它可以按预期工作),但是我不太确定
非常感谢!