python - 无法在python中动态更改变量(分数)
问题描述
我的程序目标:一个骰子游戏,每次玩家准备好时掷两次骰子。如果两个数字相等,玩家得到+5分。否则,-1 分。我的麻烦:我的程序不能改变分数。它最初设置为 0。但每次它只有-1或+5。它必须不断减少或增加。我也尝试了全局变量。这是我的代码:
from random import randint
# this function returns two random numbers in list as dice result.
def roll_dice():
dice1 = randint(1, 7)
dice2 = randint(1, 7)
rolled_dice = [dice1, dice2]
return rolled_dice
# game function is all the game, if player is ready.
def game():
score = 0
rolled_dice = roll_dice()
print(rolled_dice)
if rolled_dice[0] != rolled_dice[1]:
score -= 1
elif rolled_dice[0] == rolled_dice[1]:
score += 5
print(f"score is {score}")
#also my code in pycharms, not asking if I want to continue game. but ignore it I it bothers you, I can figure it out.
#help here also if you can.. :)
conti = input("continue?")
if conti == 'y':
game()
else:
quit()
# this is the whole program.
def main():
ready = input("ready? (y/n)")
if ready == 'y':
game()
elif ready == 'n':
quit()
else:
print("type only y/n")
main()
我很感激任何帮助。
解决方案
重置发生是因为每次用户键入y以继续游戏时,您都会继续调用game()函数。您可以将game()函数更改为循环,这将解决您的问题:
def game():
score = 0
while True:
rolled_dice = roll_dice()
print(rolled_dice)
if rolled_dice[0] != rolled_dice[1]:
score -= 1
else: # you can change here to else, because being equals is the complement of the first if clause
score += 5
print(f"score is {score}")
conti = input("continue?")
if conti == 'n':
break
推荐阅读
- php - PHP - 尽管没有添加文件,但 ZipArchive 关闭返回 true
- php - SQL - 将日期时间与当前时间进行比较
- vhdl - Quartus 17.1 中使用的 Quartus 14.1 加密文件
- docker - 在 Oracle VM VirtualBox 上为 Docker 配置 corp 代理
- c# - EF Core FindAsync 仅返回根对象
- batch-file - How to reduce value of variable in batch?
- sql - MongoDB中的3个表连接
- java - Trouble generating random -1 through +1 in Java
- c# - Random distribution of boys and girls into groups c#
- c# - Adding prolog list elements to listbox items in c#