Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 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() 

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

1 Answer

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...