首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我想不出怎么把我做的骰子游戏的分数存起来。我应该改变什么?

我想不出怎么把我做的骰子游戏的分数存起来。我应该改变什么?
EN

Stack Overflow用户
提问于 2021-04-22 05:05:43
回答 1查看 63关注 0票数 0

我已经快要完成这个简单的游戏了,但是我无论如何也想不出如何用def函数来保存分数。因为每次滚动时,由于def中的得分=0,它将重置为0。我试着去掉它,但它一直说它找不到分数的变量。我对编码比较陌生,所以请告诉我一种保存分数的方法,或者阻止它重置的方法。以下是Python的一些代码(问题出在#Roll中)

#Roll#

代码语言:javascript
运行
复制
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#

代码语言:javascript
运行
复制
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#

代码语言:javascript
运行
复制
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
EN

回答 1

Stack Overflow用户

发布于 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,)

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67203480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档