Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

python - Dice roll sum game

Okay, I'm at a loss. I am trying to make a game where you roll a die as many times as you like, but if the sum of your rolls is greater than or equal to 14, you lose. (note I'm pretty new to programing, so sorry if it's pretty bad.) The issue is that the code keeps on running, as in it keeps on asking the user for input" even if the sum of "your_list" is greater than 14.

import random
your_list = []


def dice_simulate():
    number = random.randint(1,6)
    print(number)
    while(1):
       flag = str(input("Do you want to dice it up again:Enter 1 and if not enter    0"))
       if flag == '1':
         number = random.randint(1,6)
         your_list.append(number)
         print(number)
         print (your_list)
       elif sum(your_list) >= 14:
         print ('you lose')
       else:
         print("ending the game")
         return

dice_simulate() 
question from:https://stackoverflow.com/questions/65599719/dice-roll-sum-game

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add the condition for winning and return in this case. Also, add return to the condition where you lose.

Additional changes to improve the code:

  • Remove the useless first dice roll (which does not get counted in your case).

  • Declare your_list in the smallest scope possible (here, inside the function).

  • Improve the prompt.

import random

def dice_simulate():
    your_list = []
    while(1):
       flag = str(input("Roll the dice (y/n)? "))
       if flag == 'y':
         number = random.randint(1,6)
         your_list.append(number)
         print(number)
         print (your_list)
         list_sum = sum(your_list)
         if list_sum > 14:
             print ('you lose')
             return
         elif list_sum == 14:
             print ('you win')
             return
       else:
         print("ending the game")
         return

dice_simulate()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...