当我需要给我其他东西时,为什么它将返回0?

时间:2019-04-12 17:26:30

标签: python-3.x pychart

我为学校建立了这个程序。它仍在进行中,但我在路上碰到了一块肿,我就把他的头发扯掉了。

我已经尝试更改我的变量,如何设置变量,以及让我无所适从的超级烦人。 我也无法制作图表,但这不是我的首要任务。

def compare(u1, u2):
    if u1 == u2:
      return("It's a tie!")
      TIE = TIE +1

    elif u1 == 'rock':
        if u2 == 'scissors':
            return("{0} wins with Rock!".format(user1))
            u1WIN +1
        else:
            return("{0} wins with Paper!".format(user2))
            u2WIN +1
    elif u1 == 'scissors':
        if u2 == 'paper':
            return("{0} wins with scissors!".format(user1))
            u1WIN +1
        else:
            return("{0} wins with rock!".format(user2))
            u2WIN +1
    elif u1 == 'paper':
        if u2 == 'rock':
            return("{0} wins with paper!".format(user1))
            u1WIN +1
        else:
            return("{0} wins with scissors!".format(user2))
            u2WIN +1
    else:
        return("Invalid input! some one has not entered rock, paper or scissors, try again.")
        sys.exit()
#this is so frustrating! i cant get my variables to change!
#the winner should be getting points, but they arent. and its so annoying!! it always returns 0 no matter what. i am about this || close to giving up on it. 
x = 0
u1WIN = x
u2WIN = x
TIES = x
play = 3
while play >= 0:
  if play == 0:
    break
  else:

    user1_answer = getpass.getpass("{0}, do you want to choose rock, paper or scissors? ".format(user1))
    user2_answer = getpass.getpass("{0}, do you want to choose rock, paper or scissors? ".format(user2))
    print(compare(user1_answer, user2_answer))
    play = play +-1



print('player 1\'s wins', u1WIN)
print ('player 2\'s wins', u2WIN)
print('number of ties', TIES)
user_scores = [u1WIN, u2WIN, TIES]
wins = ['user1', 'user2', 'ties']
colors = ['blue', 'green', 'red']
plt.pie(user_scores, labels=wins, colors=colors, startangle=90, autopct='%.1f%%')
plt.show()

i expected to get an output that matches the amount of times won, unfortunately, it always comes out as 0

3 个答案:

答案 0 :(得分:1)

您似乎需要分配计算结果。

这将执行计算,但是结果并未分配和存储。

u1WIN +1

这可能是您的意思:

u1WIN = u1WIN +1

答案 1 :(得分:1)

问题:

使用全局变量而不提供它们 或从函数中返回它们

def compare(u1, u2): 
    if u1 == u2:
      return("It's a tie!")
      TIE = TIE +1     # this adds one to the _global_ TIE's value  and stores it into 
                       # a _local_ TIE: your global is not modified at all

您要做的事情之后从函数返回-返回==完成-事情将永远不会发生

    if u2 == 'scissors':
        return("{0} wins with Rock!".format(user1))
        u1WIN +1              # wont ever happen

您添加变量而不将值存储回来:

u1WIN +1              # adds one and forgets it immerdiately because you do not reassign.

请勿使用全局变量:

def compare(u1,u2):
    """Returns 0 if u1 and u2 equal, returns 1 if u1 > u2 else -1"""
    if u1 == u2:
        return 0
    elif u1 > u2: 
        return 1
    else:
        return -1 

并在主程序中处理结果...或

def compare(u1,u2):
    """Returns (0,1,0) if u1 and u2 equal, returns (1,0,0) if u1 > u2 else (0,0,1)"""
    return (u1 > u2, u1 == u2, u1 < u2) # True == 1, False == 0

或其他许多可能性。

答案 2 :(得分:0)

更正了错误(全局变量,返回,添加)之后-参见my 1st answer,您可以重新构建代码并使用一些python功能:

游戏结构示例:

from enum import IntEnum
from sys import platform
import os

if platform.startswith("linux"):
    clear = lambda: os.system('clear')
else:
    clear = lambda: os.system('cls')

class G(IntEnum):
    """Represents our states in a meaningful way"""
    Rock = 1
    Scissor = 2
    Paper = 3 
    QUIT = 4

def get_gesture(who):
    """Gets input, returns one of G's "state" enums.
    Loops until 1,2,3 or a non-int() are provided."""
    g = None
    while True:
        choice = input(who + " pick one: Rock (1) - Scissor (2) - Paper (3): ")
        clear()
        try:
            g = int(choice)
            if g == G.Rock:
                return G.Rock
            elif g == G.Scissor:
                return G.Scissor
            elif g == G.Paper:
                return G.Paper
        except:
            return G.QUIT

def check(one,two):
    """Prints a message and returns: 
    0 if player 1 won,     1 if player 2 won,    2 if it was a draw"""
    if (one, two) in {(1,2) , (2,3) , (3,1)}:
        print("Player 1 wins with {} against {}".format(one.name, two.name)) 
        return 0
    elif (two, one) in {(1,2) , (2,3) , (3,1)}:
        print("Player 2 wins with {} against {}".format(two.name, one.name))
        return 1
    else:
        print("Draw: ", one.name, two.name)
        return 2

游戏:

player1 = None
player2 = None
total = [0,0,0]   # P1 / P2 / draws counter in a list

while True:
    player1 = get_gesture("Player 1")
    if player1 != G.QUIT:
        player2 = get_gesture("Player 2")
    if G.QUIT in (player1,player2):
        print("You quit.")
        break

    # the result (0,1,2) of check is used to increament the total score index
    total[ check(player1, player2) ] += 1

print("Player 1 wins: ",total[0])
print("Player 2 wins: ",total[1])
print("Draws:         ",total[2])

输出:

Player 1 pick one: Rock (1) - Scissor (2) - Paper (3): 1
Player 2 pick one: Rock (1) - Scissor (2) - Paper (3): 1
Draw:  Rock Rock

Player 1 pick one: Rock (1) - Scissor (2) - Paper (3): 2
Player 2 pick one: Rock (1) - Scissor (2) - Paper (3): 2
Draw:  Scissor Scissor

Player 1 pick one: Rock (1) - Scissor (2) - Paper (3): 3
Player 2 pick one: Rock (1) - Scissor (2) - Paper (3): 3
Draw:  Paper Paper

Player 1 pick one: Rock (1) - Scissor (2) - Paper (3): 1
Player 2 pick one: Rock (1) - Scissor (2) - Paper (3): 2
Player 1 wins with Rock against Scissor

Player 1 pick one: Rock (1) - Scissor (2) - Paper (3): Q
You quit.

Player 1 wins:  1
Player 2 wins:  0
Draws:          3