항목 게임 재미 파이썬 목록

빠른 시작 파이썬 프로그래밍 연습 프로젝트 제목, 증언 및 최적화에 오신 것을 환영합니다!
당신은 재미있는 비디오 게임을 만들 수 있습니다. 선수 목록 항목에 대한 데이터 구조 모델링을위한 단어입니다
코드입니다. 키가 항목의 목록을 설명하는 문자열이고, 값은 정수 값은 얼마나 많은 플레이어 오브젝트의 표시이며,
제품을. 예를 들어, 사전 값 { '로프'1 ' 토치': 6 '금화'42 '검'1 '화살표': 12} 재생을 의미
집 로프 토치 (6), (42) 금화 등등.
가능한 모든 항목리스트를 받아 아래와 같다 displayInventory ()라는 함수를 적는다

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))
displayInventory(stuff)

결과 :

Inventory:
1 rope
6 torch
42 gold coin
1 dagger
12 arrow
Total number of items: 62

사전에 기능 목록이 재미 항목에 대한 게임 목록은
기차 전리품이 표현 문자열과 같은 목록을 정복 가정 :
dragonLoot = [ '골드 코인', '단검', '골드 코인', '골드 코인', '루비' ]
재고가있는 함수 addToInventory (재고, addedItems)라는 이름의 매개 변수 쓰기
항목의 플레이어의 목록 (이전 항목과 동일)를 나타내는 사전이다, addedItems 인수는 목록입니다
단지 dragonLoot처럼.
addToInventory () 함수는 항목의 업데이트 된 목록을 나타내는 사전을 반환해야합니다. 열 것을 알
테이블에 여러 개의 동일한 항목을 포함 할 수 있습니다. 코드는 다음과 같습니다

def addToInventory(inventory, addedItems):
# your code goes here

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

새로운 코드 :

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))
#displayInventory(stuff)

def addToInventory(inventory, addedItems):
# your code goes here
    for i in addedItems:
        if i in inventory.keys():
            inventory[i] += 1
        else:
            inventory.setdefault(i,1)
    return inventory
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

결과 :

Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48

추천

출처blog.51cto.com/xxy12345/2425053