2017-02-10 13 views
0

제목은 꽤 자명하지만 저는 더 자세히 설명 할 것입니다. 나는 텍스트에 의존하는 게임을 만들고 있는데, 나는 수백만 개의 영역을 가질 것이다. 그리고 나중에 다시 같은 장소에 온 것보다 새로운 영역을 입력 할 때마다, 당신은 한 번만 다른 반응을 맞이합니다, 나는 이것에 할 수있는 방법을 찾을 필요가 :파이썬은 "만약 처음에 라인이 불려지면 뭔가를하십시오"라고 말합니다.

if len(line) == 1: 
    do exclusive thing 
else: 
    do normal thing 

물론을 , "a = 0"과 같은 카운터 시스템을 사용할 수는 있지만 작성한 모든 단일 영역에 대해 별도의 카운터를 만들어야하며 필요하지 않습니다.

+1

가에 플래그를 넣어 사용하도록 아직 입력되었는지 여부를 나타내는 'Room'클래스입니다. – kindall

+0

어떻게 내 게임의 데이터 구조가 다른가? 더 많은 이야기 모드 게임 – DuckyQuack

+1

예를 들어 클래스에'visits = 0'을 정의하고 방에 들어가면 그것을 증가시킵니다 ('self.visits + = 1 '). (깃발이 아닌 카운터를 사용하면 나중에 플레이어가 같은 방에 10 번이나 가면 무엇인가가 발생할지 결정할 때 많은 유연성을 얻을 수 있습니다. – kindall

답변

1

당신은 단지 객실 방문을 추적하기 위해 하나의 dict를 저장할 수 있으며, 아마도 더 나은이 defaultdict

from collections import defaultdict 

#Using a defaultdict means any key will default to 0 
room_visits = defaultdict(int) 

#Lets pretend you had previously visited the hallway, kitchen, and bedroom once each 
room_visits['hallway'] += 1 
room_visits['kitchen'] += 1 
room_visits['bedroom'] += 1 

#Now you find yourself in the kitchen again 
current_room = 'kitchen' 
#current_room = 'basement' #<-- uncomment this to try going to the basement next 

#This could be the new logic: 
if room_visits[current_room] == 0: #first time visiting the current room 
    print('It is my first time in the',current_room) 
else: 
    print('I have been in the',current_room,room_visits[current_room],'time(s) before') 

room_visits[current_room] += 1 #<-- then increment visits to this room 
+0

감사합니다! 이것은 나의 문제를 정말로 도왔다. – DuckyQuack

0

당신은 정적 var에 필요합니다 What is the Python equivalent of static variables inside a function?

def static_var(varname, value): 
    def decorate(func): 
     setattr(func, varname, value) 
     return func 
    return decorate 

@static_var("counter", 0) 
def is_first_time(): 
    is_first_time.counter += 1 
    return is_first_time.counter == 1 

print(is_first_time()) 
print(is_first_time()) 
print(is_first_time())