2
while answer  == 'Y':
    roll = get_a_roll()
    display_die(roll)
    if roll == first_roll:
        print("You lost!")
    amount_won = roll
    current_amount = amount_earned_this_roll + amount_won
    amount_earned_this_rol = current_amoun
    print("You won $",amount_won)
    print(  "You have $",current_amount)
    print("")
    answer = input("Do you want to go again? (y/n) ").upper()


if answer == 'N':
    print("You left with $",current_amount)
else:
    print("You left with $",current_amount)

使用此循环的目的是在游戏中,掷骰子,并且根据您的掷骰数获得奖励,除非您掷出与您的第一个掷骰相匹配的掷骰。现在,如果发生这种情况,我需要停止循环,并且我知道使用 break 语句很容易实现这一点,但是,我被告知不允许使用 break 语句。如果roll == first_roll,我还能如何让循环终止?

4

6 回答 6

5

你可以:

  • 使用标志变量;您已经在使用一个,只需在此处重用它:

    running = True
    while running:
        # ...
        if roll == first_roll:
            running = False
        else:
            # ...
            if answer.lower() in ('n', 'no'):
                running = False
            # ...
    
  • 从函数返回:

    def game():
        while True:
            # ...
            if roll == first_roll:
                return
            # ...
            if answer.lower() in ('n', 'no'):
                return
            # ...
    
  • 引发异常:

    class GameExit(Exception):
        pass
    
    try:
        while True:
            # ...
            if roll == first_roll:
                raise GameExit()
            # ...
            if answer.lower() in ('n', 'no'):
                raise GameExit()
            # ...
    except GameExit:
        # exited the loop
        pass
    
于 2013-11-04T17:56:21.087 回答
1

获得一些奖励积分和关注,使用生成器函数。

from random import randint

def get_a_roll():
    return randint(1, 13)

def roll_generator(previous_roll, current_roll):
    if previous_roll == current_roll:
        yield False
    yield True

previous_roll = None 
current_roll = get_a_roll()

while next(roll_generator(previous_roll, current_roll)):
    previous_roll = current_roll
    current_roll = get_a_roll()
    print('Previous roll: ' + str(previous_roll))
    print('Current roll: ' + str(current_roll))
print('Finished')
于 2013-11-04T18:12:05.610 回答
1

false如果要退出循环,可以使用将设置的变量。

cont = True
while cont:
    roll = ...
    if roll == first_roll:
        cont = False
    else:
        answer = input(...)
        cont = (answer == 'Y')
于 2013-11-04T17:56:54.783 回答
0

continue允许吗?break它可能与(两者都是受控类型gotocontinue返回循环顶部而不是退出它)太相似,但这里有一种使用它的方法:

while answer  == 'Y':
    roll = get_a_roll()
    display_die(roll)
    if roll == first_roll:
        print("You lost!")
        answer = 'N'
        continue
    ...

如果当你输了,answer被硬编码为“N”,这样当你返回顶部重新评估条件时,它是假的并且循环终止。

于 2013-11-04T18:01:26.520 回答
0
import random


# Select highest score

def highest_score(list_of_scores):
    m_score = 0

    m_user = 1

    for user in list_of_scores:

        if m_score <= list_of_scores.get(user):
            m_score = list_of_scores.get(user)

            m_user = user

    return m_score, m_user


# -----------------------------------------------------------------------------------------------------------------------------------------------


# Get the dice value

def dice_value():
    d1 = random.randint(1, 6)
    return d1


# -------------------------------------------------------------------------------------------------------------------------------------------------


# Prints the game instructions such as opening message and the game rules


print(
    "\n**************************************************************************************************************\n")

print("                                          Welcome To OVER 12!\n")

print("                                           << GAME RULES >> ")

print(
    "______________________________________________________________________________________________________________\n")

print("   <<< Each player rolls a single dice and can choose to roll again (and again) if they choose")

print("   <<< Their total is the sum of all their rolls")

print("   <<< The target is 12, if they go over twelve they score zero")

print("   <<< Once a player decides to stay the next player takes their turn")

print("   <<< DO FOLLOW THE INSRUCTIONS PROPERLY (Use ONLY Yes/No) ")

print(
    "______________________________________________________________________________________________________________\n")

# ---------------------------------------------------------------------------------------------------------------------------------------------------


game_over = True

player_score = {}

game_started = False

while game_over:

    exit_game = input('Exit The Game (Yes/No)? ')
    # The Player Can Either Start The Game Saying Yes or Exit The Game Without Starting By Saying No

    if exit_game == 'Yes':

        game_over = False




    else:

        game_started = True

        no_of_players = int(input('\n<< How Many Players Are Playing ? '))

        for player in range(1, no_of_players + 1):

            print(f'\n   Now playing player {player}')

            continue_same_player = True
            # If The Same Player Needs To Play
            total_score = 0

            while continue_same_player:

                d2 = dice_value()

                total_score = total_score + d2

                if total_score >= 12:
                    print('\nSorry..!, Your Total Score Is OVER 12, You Get ZERO!!')

                    total_score = 0

                print(f'\n   Dice Turned Value Is: {d2}')

                print(f'   Your Total Score is: {total_score}')

                same_player = input('\n<< Continue With The Same Player (Yes/No)? ')

                if same_player == 'No':
                    # If The Player Needs To Be Changed
                    player_score[player] = total_score

                    continue_same_player = False

                    print(f'\nPlayer {player} Total Score Is {total_score}')
                    break

# --------------------------------------------------------------------------------------------------------------------------------------------------


if game_started:
    u1 = highest_score(player_score)
    # Display The Highest User Score

    print(f'\n    << Highest Score User Is: {u1[1]} ')
    # The Most Scored Player Is Being Calculated
    print(f'\n    << Player Highest Score Is: {u1[0]}')

print(
    '\n   Good Bye....! \n   Thank You For Playing OVER 12.. \n   See You Again!!')  # Prints The Ending Message For the Players
于 2020-09-01T06:44:00.863 回答
0

解释:您定义了一个 end_game 函数,该函数在最后执行您想要的操作,然后结束代码

#do this 
def end_game()
    if answer == 'N':
        print("You left with $",current_amount)
    else:
        print("You left with $",current_amount)
        exit()
while answer  == 'Y':
    roll = get_a_roll()
    display_die(roll)
    if roll == first_roll:
        print("You lost!")
        end_game()
    amount_won = roll
    current_amount = amount_earned_this_roll + amount_won
    amount_earned_this_rol = current_amoun
    print("You won $",amount_won)
    print(  "You have $",current_amount)
    print("")
    answer = input("Do you want to go again? (y/n) ").upper()
    
于 2021-03-17T00:19:21.830 回答