简体   繁体   English

简单的函数问题。 尝试制作一个简单的掷骰子比赛游戏,跟踪他们掷骰子时的位置

[英]Simple Function Problem. Trying to make a simple dice roll race game that tracks the position when they roll the dice

Trying to figure out why the program won't run.试图找出程序无法运行的原因。 This is the error code I am getting: update_position (random_roll_1, random_roll_2) builtins.NameError: name 'random_roll_1' is not defined这是我得到的错误代码:update_position (random_roll_1, random_roll_2) builtins.NameError: name 'random_roll_1' is not defined

I thought I had all the correct parameters but I guess not.我以为我有所有正确的参数,但我想没有。 Any help would be really appreciated任何帮助将非常感激

import random
from random import randint
#both of the players are able to roll out their turs

this is the function where the players can roll their dice and receive a random number这是玩家可以掷骰子并接收随机数的功能

def roll_die(p1_move,p2_move):
     if p1_move is True:
          input('Press enter to roll the die for player 1')
          random_roll_1 = randint(1,6)
          random_roll_1 = str(random_roll_1)
          print('Player 1 rolled ' + random_roll_1)
          random_roll_1 = int(random_roll_1)
          return random_roll_1
     
     elif p2_move is true:
          input('Press enter to roll the die for player 2')
          random_roll_2 = randint(1,6)
          random_roll_2 = str(random_roll_2)
          print('Player 2 rolled ' + random_roll_2)
          random_roll_2 = int(random_roll_2)
          return random_roll_2
          

This part updates the position on where each player is after it rolls the dice.这部分更新每个玩家在掷骰子后所处的位置。 The players have to roll exactly 8 in order to win.玩家必须精确地掷出 8 点才能获胜。 Anything higher than that will cause the player to stay in its position高于此值的任何值都会导致玩家停留在其位置上

def update_position(random_roll_1, random_roll_2):
     player_1_position = 0
     player_2_position = 0
     max_score = 8
     if player_1_position < max_score:
          if player_1_position + random_roll_1 > 8: 
               print('The roll was too high, player 1 stays in the same spot')
          else:
               player_1_position += random_roll_1
               print('Player 1 moved up ' + random_roll_1 + ' spots!')
          return player_1_position 
     
     elif player_2_position < max_score:
          if player_2_position + random_roll_2 > 8:
               print(' The roll was too high, player 2 stays in the same spot')
          else:
               player_2_position += random_roll_2
               print('Player 2 moved up ' + random_roll_2 + ' spots!')
          return player_2_position
      

this function checks to see if one of the players hit 8 as their score #checks to see if any of the players have managed to reach the end of the game def check_game_over(player_1_position, player_2_position): if player_1_position == 8: print('Player 1 has won!') print('Thank you for playing!') continue_game = False return continue_game此函数检查是否有一名玩家打到 8 作为他们的得分 #checks 以查看是否有任何玩家已经设法到达游戏结束 def check_game_over(player_1_position, player_2_position): if player_1_position == 8: print('玩家 1 赢了!') print('感谢您玩游戏!') continue_game = False return continue_game

     elif player_2_position == 8:
          print('Player 2 has won!')
          print('Thank you for playing!')
          continue_game = False 
          return continue_game      

This function is what controls who's turn it is.此功能是控制轮到谁的功能。 I added in the roll dice function along with the update spot function as it would be easier to include them in one whole function together.我添加了掷骰子功能以及更新点功能,因为将它们一起包含在一个整体功能中会更容易。 This is where I am getting my problem.这就是我遇到问题的地方。

#random_roll_1,random_roll_2, player_1_position, player_2_position
#change the turn over to the next player 
def opponent():
     p1_move = True 
     p2_move = False
     if p1_move is True:
          roll_die (p1_move, p2_move)
          update_position (random_roll_1, random_roll_2)
          p1_move = False
          p2_move = True
          return p1_move, p2_move
     
     elif p2_move is True:
          roll_die(p1_move, p2_move)
          update_position (random_roll_1, random_roll_2)
          p1_move = True 
          p2_move = False
          return p1_move, p2_move

This function basically shows the user which location they are currently sitting at.此功能主要向用户显示他们当前所在的位置。

def display_state (player_1_position, player_2_position, p1_move, p2_move): 
     if p1_move is True:
          player_1_position = str(player_1_position)
          print('Player 1 is in ' + player_1_position + ' spot')
          player_1_position = int(player_1_position)
     
     elif p2_move is True:
          player_2_position = str(player_2_positon)
          print('Player 2  is in ' + player_2_position + ' spot')
          player_2_position = int(player_2_position)
     

Not entirely sure if this function is right at all because I still don't understand main functions completely so not sure if this main function works不完全确定这个函数是否正确,因为我仍然不完全理解 main 函数所以不确定这个 main 函数是否有效

def main():
     #display instructions 
     continue_game = True
     while continue_game:
          opponent()
          display_state (player_1_position, player_2_position, p1_move, p2_move)
          check_game_over(player_1_position, player_2_position)

main() 

So there are a few errors in your program above.所以你上面的程序有一些错误。 The runtime error you stated above is caused when you try to pass 2 variables into the update_position function before they have been defined.当您尝试在定义之前将 2 个变量传递到update_position函数时,会导致上述运行时错误。

roll_die (p1_move, p2_move)
## random_roll_1 and random_roll_2 have not been defined
update_position (random_roll_1, random_roll_2) 

However, before you deal with this error, there is a key programming concept to understand.但是,在处理此错误之前,需要了解一个关键的编程概念。
Global and Local variables.全局局部变量。
A Global variable is one which the entire program can use.全局变量是整个程序都可以使用的变量。 They are normally defined at the top of your program:它们通常在程序的顶部定义:

p1_move = True
p2_move = False

def roll_die(): ...
def main(): ...
etc

A Local variable is one which can only be used inside of the function it was created in.局部变量是一种只能在创建它的函数内部使用的变量。

def foo():
    x = 10
    y = 5
    return x + y

In this example, the variables x and y are local variables and cannot be used in other functions of your program (as they only exist inside the function foo ).在这个例子中,变量 x 和 y 是局部变量,不能在程序的其他函数中使用(因为它们只存在于函数foo )。 One thing to note, in the case where you pass a variable as a functional argument, then modify that variable in the function without returning the modified variable.需要注意的一件事是,在将变量作为函数参数传递的情况下,然后在函数中修改该变量而不返回修改后的变量。 That variable will only be modified inside that function, no where else.该变量只会在该函数内被修改,其他地方不会。 This is true for primitive data types (variables not passed by reference).这适用于原始数据类型(不是通过引用传递的变量)。

def foo(z):
    z += 1

z = 5
foo(z)
print(z)

In this example, the output would be 5, not 6 as the modified z variable in the function foo has not been returned.在此示例中,输出将是 5,而不是 6,因为函数foo修改后的 z 变量尚未返回。

For this reason alone, global variables may seem like the better option, however in general global variables are a bad idea and it is recommended that you stick to using local variables.仅出于这个原因,全局变量似乎是更好的选择,但通常全局变量是一个坏主意,建议您坚持使用局部变量。

More information about Global and Local variables .有关全局和局部变量的更多信息。

With this knowledge, some of your errors may seem more obvious.有了这些知识,你的一些错误可能看起来更明显。 For example, in your function roll_die , you define 2 variables random_roll_1 and random_roll_2 .例如,在您的函数roll_die ,您定义了 2 个变量random_roll_1random_roll_2 However you try to use these variables in other functions, update_position for example.但是,您尝试在其他函数中使用这些变量,例如update_position
I realise that you have tried to return each random_roll variable independently from the roll_die function, however you do not store these returned values.我意识到您已经尝试独立于roll_die函数返回每个 random_roll 变量,但是您没有存储这些返回值。

# Original
roll_die (p1_move, p2_move)

# Correctly returned
random_roll = roll_die(p1_move, p2_move)

In the next line, you then try to use both random_roll_1 and random_roll_2 variables, even though you only know 1 of those variables at that stage.在下一行中,您尝试同时使用random_roll_1random_roll_2变量,即使在那个阶段您只知道其中 1 个变量。

# Original
update_position (random_roll_1, random_roll_2)

# Possible Correction
update_position(random_roll)

You would then have to redefine the update_position function, thinking about each player's go as if it happened one after another, and not both at the same time.然后,您必须重新定义 update_position 函数,将每个玩家的下棋视为一个接一个地发生,而不是同时发生。

I would also like to emphasize the importance of reducing the amount of duplicate code in your program.我还想强调减少程序中重复代码数量的重要性。
Your opponent function could instead be written as:你的opponent函数可以写成:

def opponent(p1_move, p2_move):
    random_roll = roll_die(p1_move, p2_move)
    update_position(random_roll)

    p1_move = not p1_move
    p2_move = not p2_move
    return p1_move, p2_move

This refactoring has changed a few details, most importantly, the use of the not .这次重构改变了一些细节,最重要的是not的使用。
This operator will turn True->False and False->True.此运算符将变为 True->False 和 False->True。 For example, if p1_move is false, not p1_move is True.例如,如果p1_move为假,则not p1_move为真。

In addition, the function has parameters p1_move, p2_move , as these variables will be required in other parts of your program, you should define them outside of this functions scope , and pass them as arguments into your other functions.此外,该函数具有参数p1_move, p2_move ,因为这些变量在程序的其他部分是必需的,您应该在此函数范围之外定义它们,并将它们作为参数传递给其他函数。 And don't forget to store the return values!并且不要忘记存储返回值!

Just to note, this function refactoring is an example of how to reduce duplicate code, and is designed to be used with your modified program.请注意,此函数重构是如何减少重复代码的示例,旨在与您修改后的程序一起使用。

There are a few more modifications required to make your program run, but I will let you work them out for yourself.要使您的程序运行,还需要进行一些修改,但我会让您自己解决。

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

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