我已经快要完成这个简单的游戏了,但是我无论如何也想不出如何用def函数来保存分数。因为每次滚动时,由于def中的得分=0,它将重置为0。我试着去掉它,但它一直说它找不到分数的变量。我对编码比较陌生,所以请告诉我一种保存分数的方法,或者阻止它重置的方法。以下是Python的一些代码(问题出在#Roll中)
#Roll#
import random
def roll(player):
score = 0
score2 = 0
if player == 1:
print("Rolling for",P1,"...")
dice1 = (random.randrange(1,7))
dice2 = (random.randrange(1,7))
dietotal = dice1 + dice2
score = score + dietotal
dice(dice1)
dice(dice2)
print("Your score so far is", score,)
else:
print("Rolling for",P2,"...")
dice1 = (random.randrange(1,7))
dice2 = (random.randrange(1,7))
dietotal = dice1 + dice2
score2 = score2 + dietotal
dice(dice1)
dice(dice2)
print("Your score so far is", score2,)#Accounts#
password = 'wrong'
print("Welcome to the dice game!")
P1 = input("What is player 1's name?")
while password != 'right':
password = input("What is the password?")
if password == 'password':
print("Ok", P1,"welcome!")
password = 'right'
else:
print("Password is invalid, try again")
P2 = input("What is player 2's name?")
while password != 'wrong':
password = input("What is the password?")
if password == 'password':
print("Ok", P2,"welcome!")
password = 'wrong'
else:
print("Password is invalid, try again") #Game#
rounds = 0
while rounds != 5:
print("Its your turn to roll", P1,)
start = input("Enter roll when you want to")
while start != 'roll':
print("This is invalid")
start = input("Enter roll when you want to")
else:
roll(1)
print("Its your turn to roll", P2,)
start = input("Enter roll when you want to")
while start != 'roll':
print("This is invalid")
start = input("Enter roll when you want to")
else:
roll(2)
rounds = rounds + 1发布于 2021-04-22 05:14:46
试着让你的roll函数返回结果。在#Roll#中,将return score和return score2放在包含打印语句的位置,然后删除打印语句。
在#Game#中进行以下更改:
定义vars分数和score2
Change roll(1) -> score=score + roll(1)打印(“您到目前为止的分数是”,score,)
和
Change roll(2) -> score2=score2 + roll(2)打印(“你到目前为止的分数是”,score2,)
https://stackoverflow.com/questions/67203480
复制相似问题