2013-11-24 1 views
5

나는 방금 Python에서 Roguelike를 프로그래밍하기 위해 this tutorial을 완료했으며 지금은 어디로 가야할지, 다음에 무엇을해야 하는지를 알아 내려고 노력하고 있습니다.항목 및 해당 속성을 외부 파일에 저장하고 필요할 때 호출 할 수 있습니까? (Roguelike in Python을 프로그래밍 할 때)

내 처지는 코드가 복잡합니다. 나는 어딘가에, 예를 들어 항목을 저장하고 싶다. 생물; 기술; 그곳에는 수많은 재산이있는 곳이 있습니다.

현재이 코드는 모두 하나의 파일에 포함되어 있습니다.이 파일은 매우 커질 수 있으며 가장 기본적인 것입니다. 수준에 항목을 배치하는 기능을 지금과 같이 많은 같습니다, 나는 더 많은 항목을 추가 할 예정으로

def place_objects(room): 

    #Maximum number of items per room 
    max_items = from_dungeon_level([[1, 1], [2, 4]]) 

    #Chance of each item (by default they have a chance of 0 at level 1, which then goes up) 
    item_chances = {} 
    item_chances['heal'] = 35 
    item_chances['lightning'] = from_dungeon_level([[25, 4]]) 
    item_chances['fireball'] = from_dungeon_level([[25, 6]]) 
    item_chances['confuse'] = from_dungeon_level([[10, 2]]) 
    item_chances['sword'] = from_dungeon_level([[5, 4]]) 
    item_chances['shield'] = from_dungeon_level([[15, 8]]) 

    #Choose a random number of items 
    num_items = libtcod.random_get_int(0, 0, max_items) 

    for i in range(num_items): 
     #Choose random spot for this item 
     x = libtcod.random_get_int(0, room.x1+1, room.x2-1) 
     y = libtcod.random_get_int(0, room.y1+1, room.y2-1) 

     #Only place it if the tile is not blocked 
     if not is_blocked(x, y): 
      choice = random_choice(item_chances) 
      if choice == 'heal': 
       #Create a healing potion 
       item_component = Item(use_function=cast_heal) 
       item = Object(x, y, '~', 'Salve', libtcod.light_azure, item=item_component) 
      elif choice == 'lightning': 
       #Create a lightning bolt scroll 
       item_component = Item(use_function=cast_lightning) 
       item = Object(x, y, '#', 'Scroll of Lightning bolt', libtcod.light_yellow, item=item_component) 
      elif choice == 'fireball': 
       #Create a fireball scroll 
       item_component = Item(use_function=cast_fireball) 
       item = Object(x, y, '#', 'Scroll of Fireball', libtcod.light_yellow, item=item_component) 
      elif choice == 'confuse': 
       #Create a confuse scroll 
       item_component = Item(use_function=cast_confuse) 
       item = Object(x, y, '#', 'Scroll of Confusion', libtcod.light_yellow, item=item_component) 
      elif choice == 'sword': 
       #Create a sword 
       equipment_component = Equipment(slot='right hand', power_bonus=3) 
       item = Object(x, y, '/', 'Sword', libtcod.sky, equipment=equipment_component) 
      elif choice == 'shield': 
       #Create a shield 
       equipment_component = Equipment(slot='left hand', defense_bonus=1) 
       item = Object(x, y, '[', 'Shield', libtcod.sky, equipment=equipment_component) 

      objects.append(item) 
      item.send_to_back() 

,이 기능이 심각하게 긴 얻을 것이다 (레벨이 생성 될 때이 함수가 호출됩니다) 이 각각을 처리하는 데 필요한 모든 기능을 생성합니다. 이 작업을 main.py에서 꺼내 다른 곳에 저장하여 작업하기 쉽도록하고 싶지만 현재이 작업을 수행하는 방법을 모르겠습니다. 여기

시도하고 문제를 통해 생각하는 나의 시도입니다

내가 각 항목에 포함 된 속성의 번호와 항목 클래스를 포함하는 파일이 없습니다; (이름, 유형, 조건, 마법, 아이콘, 체중, 색깔, 설명, 장비 슬롯, 측면). 그런 다음 항목이 수행하는 기능을 에 저장하면 파일이 저장됩니까? 주 파일은이 다른 파일을 언제 호출해야하는지 어떻게 알 수 있습니까?

모든 항목 데이터를 외부 파일 (예 : XML 또는 기타)에 저장하고 필요할 때 읽을 수 있습니까?

이것은 분명히 항목 이상에 적용 할 수있는 내용입니다. 이것은 내가 원하는 것이 메인 루프와 더 나은 조직 구조 일 때 수천 줄의 코드를 휘두르는 모든 생물, 아이템 및 기타 오브젝트를 보유하고있는 정말 부 풀린 main.py가 없다면 정말 유용 할 것입니다.

답변

1

사람이 읽을 수있는 파일이 필요하지 않으면 Python의 pickle 라이브러리를 사용해보십시오. 이것은 파일에 쓰고 읽을 수있는 객체와 함수를 직렬화 할 수 있습니다.

class Equipment(Object): 

class Sword(Equipment): 

class Item(Object): 

class Scroll(Item): 
: 더 개선

game/ 
    main.py 
    objects/ 
     items.py 
     equipment.py 
     creatures.py 

, 예를 할 상속을 사용

조직의 측면에서

, 당신은 예를 들어, 당신의 주요 게임 루프에서 해당 클래스를 분리, 객체들 폴더를 가질 수있다

그러면 모든 설정이 완료됩니다. (예 : 이름, 파워 보너스)에 따라 다를 수 있습니다.

1

모든 아이템 데이터를 저장할 수 있습니까? 외부 파일 (예 : XML 또는 )에 저장하고 필요할 때 읽을 수 있습니까?

ConfigParser 모듈로이 작업을 수행 할 수 있습니다.

항목의 속성을 별도의 파일 (일반 텍스트 파일)에 저장할 수 있습니다. 자동으로 개체를 만들려면이 파일을 읽으십시오.

import ConfigParser 
from gameobjects import SwordClass 

config = ConfigParser.RawConfigParser() 
config.read('example.cfg') 

config_map = {'Sword': SwordClass} 
game_items = [] 

for i in config.sections(): 
    if i in config_map: 
     # We have a class to generate 
     temp = config_map[i]() 
     for option,value in config.items(i): 
      # get all the options for this sword 
      # and set them 
      setattr(temp, option, value) 
     game_items.append(temp) 
: 파일을 읽을 지금

import ConfigParser 

config = ConfigParser.RawConfigParser() 
config.add_section('Sword') 
config.set('Sword', 'strength', '15') 
config.set('Sword', 'weight', '5') 
config.set('Sword', 'damage', '10') 

# Writing our configuration file to 'example.cfg' 
with open('example.cfg', 'wb') as configfile: 
    config.write(configfile) 

: 여기 가이드로 문서에서 예제를 사용하는거야

관련 문제