【发布时间】:2015-04-19 17:20:58
【问题描述】:
我正在制作一个石头剪刀布游戏,但遇到了decisioncycle() 的问题。我正在尝试做的是要求用户在usercycle() 中输入一个选项,让计算机在gamecycle() 中生成一个随机选项,然后确定谁赢得了这一轮并通过输赢计数跟踪每个结果.它似乎在随机决定何时工作。
import random
class rpsgame:
rps= ["rock", "paper","scissors"]
wincount=0
losecount=0
def usercycle(self):
userchoice = input("rock, paper, scissor.....")
print("SHOOT")
return userchoice
def gamecycle(self):
computerchoice = random.choice(rpsgame.rps)
return computerchoice
def decisioncycle(self):
if rpsgame.usercycle(self) == rpsgame.rps[0] and rpsgame.gamecycle(self) == rpsgame.rps[1]:
print("paper beats rock, you lose!")
rpsgame.losecount +=1
elif rpsgame.usercycle(self) == rpsgame.rps[1] and rpsgame.gamecycle(self) == rpsgame.rps[0]:
print("paper beats rock, you win!")
rpsgame.wincount+=1
elif rpsgame.usercycle(self) == rpsgame.rps[0] and rpsgame.gamecycle(self) == rpsgame.rps[2]:
print("rock beats scissors, you win!")
rpsgame.wincount+=1
elif rpsgame.usercycle(self) == rpsgame.rps[2] and rpsgame.gamecycle(self) == rpsgame.rps[0]:
print("rock beats scissors, you lose!")
rpsgame.losecount+=1
elif rpsgame.usercycle(self) == rpsgame.rps[1] and rpsgame.gamecycle(self) == rpsgame.rps[2]:
print("scissors beats paper, you lose!")
rpsgame.losecount+=1
elif rpsgame.usercycle(self) == rpsgame.rps[2] and rpsgame.gamecycle(self) == rpsgame.rps[1]:
print("scissors beats paper, you win!")
rpsgame.wincount+=1
elif rpsgame.usercycle(self) == rpsgame.gamecycle(self):
print("it's a tie!!!")
print("wins {}, losses {}".format(rpsgame.wincount, rpsgame.losecount))
while True:
rg = rpsgame()
rg.usercycle()
rg.gamecycle()
rg.decisioncycle()
我认为我的问题在于决策周期()。这是我在课堂上的第一次尝试,因为游戏正在使用全局变量,但我在这里读到,这对于未来来说是一种不好的做法。
【问题讨论】:
-
在决策周期中,每个 if/elif 语句都像是一个单独的游戏回合,我认为这不是您真正想要的。
-
没错,当我像这样在没有使用全局变量的类的情况下编写它时,它按预期工作。我到底错过了什么?
-
在决定游戏结果的任何函数中,您应该只调用 usercycle 和 gamecycle 一次,并将结果分配给 2 个变量。然后使用这些变量进行比较。
-
这行得通,但我仍然不完全理解为什么它首先与全局变量一起工作,这本身就是一个教训。我可能应该远离全局变量...
-
不,因为 computerchoice 和 userchoice 是 gamecycle 和 usercycle 函数的本地。它们不存在于这些功能之外。如果您希望它们成为 rpsgame 的属性,则必须在它们前面加上 self,例如
self.computerchoice.