2014-10-25 5 views
-2

텍스트 기반 게임을 만들고 싶지만 이렇게하려면 여러 기능을 사용하고 손상, 무기 및 건강과 같은 값을 전달해야합니다.파이썬에서 변수를 전달하는 방법

내 코드에 "무기" "피해" "p1 n p2"를 전달할 수 있도록 허용하십시오. p1 n p2에 대한 매개 변수 사용을 시도했지만 조금 초보자입니다. 감사!


import random 

def main(): 
    print("Welcome to fight club!\nYou will be fighting next!\nMake sure you have two people ready to  play!") 
    p1=input("\nEnter player 1's name ") 
    p2=input("Enter player 2's name ") 
    print("Time to get your weapons for round one!\n") 
    round1(p1,p2) 

def randomweapons(p1,p2): 
    weapon=["Stick","Baseball bat","Golf club","Cricket bat","Knife",] 
    p1weapon=random.choice(weapon) 
    p2weapon=random.choice(weapon) 
    print(p1 +" has found a "+p1weapon) 
    print(p2 +" has found a "+p2weapon) 

def randomdamage(): 
    damage=["17","13","10","18","15"] 
    p1damage=random.choice(damage) 
    p2damage=random.choice(damage) 

def round1(p1,p2): 
    randomweapons(p1,p2) 

def round2(): 
    pass 
def round3(): 
    pass 
def weaponlocation(): 
    pass 

main() 
+2

어떤 문제가 있습니까? 예상되는 입출력은 무엇입니까? 또한 서식이 엉망입니다. 이 프로그램은 실행되지 않습니다. –

답변

1

몇 가지 옵션이 있습니다.

하나는 매개 변수로 값을 전달하고 다양한 함수에서 값을 반환하는 것입니다. 두 플레이어의 이름은 이미 main에서 round1까지 그리고 randomweapons에서 매개 변수로 전달됩니다. 다른 무엇이 전달되어야하는지 결정할 필요가 있습니다.

정보가 다른 방향 (호출 된 함수에서 호출자로 다시 전달되어야 함) 일 때 return을 사용해야합니다. 예를 들어, randomweapons은 함수를 호출 할 때 선택한 무기를 반환 할 수 있습니다(). 파이썬의 tuple-unpacking 문법 : w1, w2 = randomweapons(p1, p2)을 사용하여 함수의 반환 값을 변수 또는 여러 변수에 할당하여 호출 함수에 무기를 저장할 수 있습니다. 호출 함수는 그때부터 그 변수로 원하는대로 할 수 있습니다 (다른 함수로 전달하는 것을 포함하여).

또 다른 방법은 객체 지향 프로그래밍을 사용하는 것입니다. 함수가 일부 클래스 (예 : MyGame)에 정의 된 메소드 인 경우 다양한 데이터 조각을 클래스 인스턴스의 속성으로 저장할 수 있습니다. 메서드는 인스턴스를 자동으로 첫 번째 매개 변수로 전달합니다.이 매개 변수는 일반적으로 self입니다. 다음과 같이 될 수있는 것의 다소 과장된 예가 있습니다 :

class MyGame:   # define the class 
    def play(self): # each method gets an instance passed as "self" 
     self.p1 = input("Enter player 1's name ") # attributes can be assigned on self 
     self.p2 = input("Enter player 2's name ") 
     self.round1() 
     self.round2() 

    def random_weapons(self): 
     weapons = ["Stick", "Baseball bat", "Golf club", "Cricket bat", "Knife"] 
     self.w1 = random.choice(weapons) 
     self.w2 = random.choice(weapons) 
     print(self.p1 + " has found a " + self.w1) # and looked up again in other methods 
     print(self.p2 + " has found a " + self.w2) 

    def round1(self): 
     print("Lets pick weapons for Round 1") 
     self.random_weapons() 

    def round2(self): 
     print("Lets pick weapons for Round 2") 
     self.random_weapons() 

def main(): 
    game = MyGame() # create the instance 
    game.play()  # call the play() method on it, to actually start the game 
+0

각 플레이어마다 클래스가 있지만 OOP 방식이 올바른 방법이라는 데 동의합니다. –

관련 문제