Python,”;如果第一次调用line,请执行其他操作;

Python,”;如果第一次调用line,请执行其他操作;,python,python-3.x,numbers,counter,adventure,Python,Python 3.x,Numbers,Counter,Adventure,因此,这个标题是不言自明的,但我会更详细地介绍。我正在创建一个文本相关的游戏,我将拥有数百万个区域。每次你进入一个新的区域,你都会得到一种与你以后再次进入同一个地方时唯一不同的反应,我需要找到一种方法: if len(line) == 1: do exclusive thing else: do normal thing 当然,我可以使用像“a=0”这样的计数器系统,但是我需要为我创建的每个区域创建一个单独的计数器,我不希望这样。您需要静态变量: 您可以只存储一个dict来跟踪

因此,这个标题是不言自明的,但我会更详细地介绍。我正在创建一个文本相关的游戏,我将拥有数百万个区域。每次你进入一个新的区域,你都会得到一种与你以后再次进入同一个地方时唯一不同的反应,我需要找到一种方法:

if len(line) == 1:
    do exclusive thing
else:
    do normal thing
当然,我可以使用像“a=0”这样的计数器系统,但是我需要为我创建的每个区域创建一个单独的计数器,我不希望这样。

您需要静态变量:


您可以只存储一个
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
从集合导入defaultdict
#使用defaultdict意味着任何键都将默认为0
房间访问量=默认DICT(int)
#让我们假设您之前曾访问过走廊、厨房和卧室,每次一次
房间访问次数['走廊]+=1
房间探访[“厨房”]+=1
房间访问次数['卧室]+=1
#现在你又在厨房里了
当前房间=‘厨房’

#当前房间=‘地下室’#在你的
房间
类上放置一个标志,指示它是否已经进入。如何进入?以及我的游戏的数据结构不同,它更像是一个故事模式的游戏。例如,在类上定义
访问=0
,并在你进入房间时增加它(
self.visions+=1
)。(使用计数器而不是旗帜可以给你很大的灵活性,如果你以后决定如果玩家去同一个房间十次,或者其他什么)谢谢!这真的帮了我的忙
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