-2

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

我已经尝试过更改我的变量,它们是如何设置的,以及我想不出的任何东西都非常烦人。我也不能让它成为我的图表,但这不是我的首要任务。

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
4

3 回答 3

1

看起来您需要分配计算结果。

这会执行计算,但不会分配和存储结果。

u1WIN +1

大概你的意思是这样的:

u1WIN = u1WIN +1
于 2019-04-12T17:31:25.653 回答
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

从函数返回后你会做一些事情- return == Done - 以后什么都不会发生

    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

或许多其他可能性。

于 2019-04-12T17:33:34.393 回答
0

修复错误(全局、返回、添加)后 - 请参阅我的第一个答案,您可以稍微重构代码并使用一些 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 increment 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
于 2019-04-12T18:26:47.163 回答