繁体   English   中英

我想知道为什么我的程序没有在我的 while 循环中停止

[英]I want to know why my program is not stopping in my while loop

伙计们,我有以下问题 - 编写一个程序来玩以下简单的游戏。 玩家从 $100 开始。 每一轮都会抛硬币,玩家必须猜测正面或反面。 玩家每猜对一次就赢 9 美元,每猜错一次就输 10 美元。 当玩家用完钱或获得 200 美元时,游戏结束。

我的程序实际上正在运行。 然而,当玩家点数低于零时,我的程序仍在运行,这不是我所期望的。 我需要知道在我的 if 语句中是否有什么可以做的,或者当我有很多条件时是否有更简单的方法来进行陈述。

import random

list=['heads','tails']
def game():
    p1=100
    p2=100
    while (p1>0 or p2>0)and(p1<200 or p2<200):
        x=random.choice(list)
        x1=input('digit your guess player1 - ')
        x2=input('digit your guess player2 - ')
        if x1==x:
            p1+=30
        else:
            p1=p1-40
        if x2==x:
            p2+=30
        else:
            p2=p2-40
    return p1,p2
print(game())

我希望程序返回分数并在任何玩家分数高于 200 或低于 0 时结束

将 while 条件更改为:

while p1>0 and p2>0 and p1<200 and p2<200

但在以下情况下更具可读性:

while 0<p1<200 and 0<p2<200

如果我考虑您的原始问题,问题在于您要返回玩家拥有的任何当前值,而不是您应该记住最后一个分数,如果您希望游戏停止的条件发生,则返回最后一个分数。 这将确保只返回有效分数

import random

list=['heads','tails']
def game():
    player=100
    last_score = 0

    #Conditions to break while loop
    while player > 0 and player < 200:

        #Keep track of last score
        last_score = player

        #Get choice from player, and increase/decrease score
        x=random.choice(list)
        x1=input('digit your guess player1 - ')
        if x1 == x:
            player += 9
        else:
            player -= 10

    #Return last score
    return last_score

print(game())

将此想法扩展到 2 人游戏也将解决您的问题!

import random

list=['heads','tails']

def game():
    p1=100
    p2=100
    last_scores = 0,0


    # Conditions to break while loop
    while (0<p1<200) and(0<p2<200):

        # Keep track of last score
        last_scores = p1,p2

        # Get choice from player, and increase/decrease score
        x=random.choice(list)
        x1=input('digit your guess player1 - ')
        x2=input('digit your guess player2 - ')

        if x1==x:
            p1+=30
        else:
            p1=p1-40
        if x2==x:
            p2+=30
        else:
            p2=p2-40

    return last_scores

print(game())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM