python - Python program that simulates a full one player game of pig, starting at a totalscore of 0 and playing turn after turn until it reaches 100 points
问题描述
So here is a sample output:
- rolled a 2
- rolled a 1
Pigged out!
Turn score = 0
New total score = 0
- rolled a 1
Pigged out!
Turn score = 0
New total score = 0
- rolled a 6
- rolled a 6
- rolled a 6
- rolled a 5
Turn score = 23 #So on
New total score = 90
- rolled a 6
- rolled a 6
- rolled a 3
Turn score = 15
New total score = 105
And here is how I tried to solve it:
` import random
print("Well, hello there.")
score = 0
while(score<=100):
turn_score=0
while (turn_score<=20):
dice_value=random.randint(1,6)
if (dice_value==1):
print("Pigged out! Better luck next time!")
turn_score=0
break #to get out of the loop in case a roll rolls up
else:
print("-rolled a ",dice_value)
score+=dice_value
print("Score is ",turn_score)
score+=turn_score
print("Final score is: ",score)`
What I tried doing is first making an inner loop that will roll the dice, add the values(except if a 1 comes up, in which case the turn score would be 0) and present it as the turn score.
Then I thought of looping it as a whole till a total turn score of >=100 is reached.
Can someone explain where I went wrong here?
Here is the output I get when I run it:
Well, hello there.
-rolled a 3
Score is 0
-rolled a 2
Score is 0
-rolled a 6
Score is 0
Pigged out! Better luck next time!
Final score is: 11
-rolled a 6
Score is 0
-rolled a 4
Score is 0
-rolled a 5
Score is 0
-rolled a 2
Score is 0
-rolled a 2
Score is 0
-rolled a 4
Score is 0
-rolled a 2
Score is 0
-rolled a 3
Score is 0
-rolled a 4
Score is 0
-rolled a 4
Score is 0
Pigged out! Better luck next time!
Final score is: 47
-rolled a 6
Score is 0
-rolled a 5
Score is 0
-rolled a 6
Score is 0
-rolled a 5
Score is 0
-rolled a 6
Score is 0
Pigged out! Better luck next time!
Final score is: 75
-rolled a 3
Score is 0
-rolled a 2
Score is 0
-rolled a 6
Score is 0
-rolled a 6
Score is 0
-rolled a 4
Score is 0
-rolled a 2
Score is 0
Pigged out! Better luck next time!
Final score is: 98
-rolled a 6
Score is 0
-rolled a 4
Score is 0
-rolled a 2
Score is 0
-rolled a 3
Score is 0
Pigged out! Better luck next time!
Final score is: 113
解决方案
在你的else
街区,改变
score+=dice_value
至
turn_score += dice_value
您永远不会在循环中的任何点增加 turn_score,因此 while 循环仅在它滚动 1 并命中break
语句时才会结束。此外,在这条线到位后,您将增加score
可能会退出的转弯,这是不应该发生的。
推荐阅读
- android-studio - 发布规范.yaml 1.22.1
- python - 如何将逗号与单词分开(标记化)
- flutter - 更正 Flutter 中另一个滚动中的滚动行为
- hadoop - Hadoop 不在类路径/依赖项中,hdfs 不是有效的文件方案
- git - 如何在不丢失原始哈希码和我应该提交的代码的情况下恢复 git commit --amend -m?
- python - 我在以下程序中遇到错误,因为 KeyError Traceback(最近一次调用最后一次)
- javascript - Next.js 刷新页面中断 css classNames
- python-3.x - Microsoft MSAL Resource Owner Password Credentials(ROPC) Grant 授权是否支持 ClientConfidentialApplicaton 类获取 Token?
- javascript - 为什么 setState 会导致我的 React 应用程序进入无限循环?
- peoplesoft - 是否有一个列表或方法来查找所有具有不同名称但包含相同数据的字段?