2010-11-12 125 views
8

我试图让这个岩石纸剪刀游戏返回一个布尔值,如设置player_wins为True或False,具体取决于玩家是否获胜,或者重新构造这些代码,以便它不使用while循环。 我来自世界各地的系统管理员,所以如果这是写错了风格,请温柔一点。 我已经尝试了一些东西,并且我理解TIMTOWTDI,并且会喜欢一些输入。初学者问题:从Python中的函数返回布尔值

谢谢。

import random 

global player_wins 
player_wins=None 

def rps(): 

    player_score = 0 
    cpu_score = 0 

    while player_score < 3 and cpu_score < 3: 

     WEAPONS = 'Rock', 'Paper', 'Scissors' 

     for i in range(0, 3): 
      print "%d %s" % (i + 1, WEAPONS[i]) 

     player = int(input ("Choose from 1-3: ")) - 1 
     cpu = random.choice(range(0, 3)) 

     print "%s vs %s" % (WEAPONS[player], WEAPONS[cpu]) 
     if cpu != player: 
      if (player - cpu) % 3 < (cpu - player) % 3: 
      player_score += 1 
      print "Player wins %d games\n" % player_score 
      else: 
      cpu_score += 1 
      print "CPU wins %d games\n" % cpu_score 
     else: 
      print "tie!\n" 
rps() 

我试图做这样的事情:

print "%s vs %s" % (WEAPONS[player], WEAPONS[cpu]) 
    if cpu != player: 
     if (player - cpu) % 3 < (cpu - player) % 3: 
     player_score += 1 
     print "Player wins %d games\n" % player_score 
     if player_score == 3: 
      return player_wins==True 
     else: 
     cpu_score += 1 
     print "CPU wins %d games\n" % cpu_score 
     if cpu_score == 3: 
      return player_wins==False 
    else: 
     print "tie!\n" 
+1

什么布尔值应返回领带? – 2010-11-12 15:10:22

+0

因为它在while循环内部,所以关系只是在开始时将你转储回去。 REMATCH! – matt 2010-11-12 15:14:11

+0

我认为这不是一个好的项目来获得正确的编程理解? – matt 2010-11-12 15:19:48

回答

24

忽略重构问题,您需要了解函数和返回值。你根本不需要全球化。永远。你可以这样做:

def rps(): 
    # Code to determine if player wins 
    if player_wins: 
     return True 

    return False 

然后,只需赋值给变量这一功能外,像这样:

player_wins = rps() 

将分配返回值(True或False)的功能你刚刚打过电话。


的意见后,我决定要补充的是习惯用法,这将是更好的表述为:

def rps(): 
    # Code to determine if player wins, assigning a boolean value (True or False) 
    # to the variable player_wins. 

    return player_wins 

pw = rps() 

这种分配的player_wins布尔值(函数内)到pw变量外功能。

+1

啊,我现在看到了。我明白了,谢谢。我会更新这篇文章以反映解决方案。 – matt 2010-11-12 15:22:56

+2

这段代码伤害了我的眼睛......它应该是'return player_wins' – 2010-11-12 15:25:58

+0

当然,Rafe,但这不会为说明的目的而清楚。 – syrion 2010-11-12 15:29:56

2

让您使用 '返回' 关键字试过吗?

def rps(): 
    return True