How to replace None value with values from dictionary?

Question:

I have an assignment to program a simple tower defense game through printing. So I assume I’m supposed to make use of the dictionary that I was given and replace the None variable in my nested list called field to spawn a ‘zombie’ in the game, but I’m not sure how to do that.

This is my code that just creates a grid:

import random

field = [ [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None] ]


zombie = {'shortform': 'ZOMBI',
          'name': 'Zombie',
          'maxHP': 15,
          'min_damage': 3,
          'max_damage': 6,
          'moves' : 1,
          'reward': 2
          }

num_rows=len(field)
num_columns=len(field[0])
row_indexes="ABCDE"

print(' {:^7}{:^5}{:^7}'.format('1','2','3'))
print(' ',end='')

for column in range(num_columns): 
    print('+-----',end='')
print('+')

for row in range(num_rows):
    print('{}'.format(row_indexes[row]), end='') # print row index
    for column in range(num_columns): #for each column,
        element = field[row][column]      
        if element is None:      #print spacings
            print('|     ' , end='') 
        else:                     #print monster name
            print('|' + element[0], end='')
    print('|') #end row

    print(' ', end='') #spacing for 2nd | row 
    for column in range(num_columns):
        element = field[row][column]
        if element is None:  #print spacing agn
            print('|     ' , end='')
        else:                     #print monster helth
            print('|' + element[1], end='')
    print('|') #end row

    print(' ', end='') #spacing for letter
    for column in range(num_columns):
        print('+-----', end = '')
    print('+')#end of row

row_spawn=random.randint(0,4)
field[row_spawn][5]=zombie.get('shortform')

This is how it should look like but the zombi spawning in a random lane:

screenshot

Asked By: pepega

||

Answers:

I didn’t change much in your code. Just moved most part of the code to a function.
In your code you create the field, then draw your field and THEN you change the field and add a zombie, but this field never gets printed.

At the code below you create a field and the zombie dict, then you wrap your whole code where drawing the field to a function which takes the field and zombie as input and returns the current state of the field and the zombi dict.

At the bottom I made a loop, where a zombie is spawned 5 times in a random row and a random column. Also I added a current_HP to the zombie dict, which decreases every round by 1 (just for demonstration).
In case a zombie gets spawned in a position where already a zombie is placed, the values just get overwritten.
When accessing the value of a dict, you use dict.get() preferred if you don’t know if that key exists, but since you create the dict you can just directly access it like dict[key].

If you have any question feel free to ask!

field = [ [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None] ]


zombie = {'shortform': 'ZOMBI',
          'name': 'Zombie',
          'current_HP': 15,
          'maxHP': 15,
          'min_damage': 3,
          'max_damage': 6,
          'moves' : 1,
          'reward': 2
          }

def draw(field):
    num_rows=len(field)
    num_columns=len(field[0])
    row_indexes="ABCDE"

    print(' {:^7}{:^5}{:^7}'.format('1','2','3'))
    print(' ',end='')

    for column in range(num_columns): 
        print('+-----',end='')
    print('+')

    for row in range(num_rows):
        print('{}'.format(row_indexes[row]), end='') # print row index
        for column in range(num_columns): #for each column,
            element = field[row][column]      
            if element is None:      #print spacings
                print('|     ' , end='') 
            else:                     #print monster name
                print('|' + element[0], end='')
        print('|') #end row

        print(' ', end='') #spacing for 2nd | row 
        for column in range(num_columns):
            element = field[row][column]
            if element is None:  #print spacing agn
                print('|     ' , end='')
            else:                     #print monster helth
                print('|' + element[1], end='')
        print('|') #end row

        print(' ', end='') #spacing for letter
        for column in range(num_columns):
            print('+-----', end = '')
        print('+')#end of row
    return field

for _ in range(5):
    row_spawn = random.randint(0,4)
    col_spawn = random.randint(0,6)
    
    #next you change at one position of the field the value to a tuple with [1] name [2] health
    field[row_spawn][col_spawn]=(zombie['shortform'], f"{zombie['current_HP']}/{zombie['maxHP']}")
    
    # now call the function with the updated field
    field, zombie = draw(field, zombie)
    
    # HP decreases every round
    zombie['current_HP'] -= 1

Answered By: Rabinzel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.