簡體   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