RPG Game - Indexing

RPG Game - Indexing

Postby Vrixon » Sat May 14, 2016 2:44 pm

Code: Select all
#Meeting an enemy - Attack / Defend Option
def encounter(enemy):
    print(name,"encountered a",enemy,".","What do you do?")

encounter([0]) #First enemy - Want to spawn a dummy from list, how?

So I am making an encounter function, which in it has an enemy variable with a list. What I was planning is that when I call encounter() is that I can pick a certain enemy from the list or pick a random one. But I have one problem which is that [0] isn't the dummy enemy and instead is [0]. It prints (Name) encountered a [0]... Instead of (Name) encountered a dummy...

Could someone help as to how choose an enemy from the list?
Last edited by micseydel on Sat May 14, 2016 6:22 pm, edited 1 time in total.
Reason: Initial post lock. Removed redundant tags. Cleaned up title a bit.
Posts: 1
Joined: Sat May 14, 2016 2:34 pm

Re: RPG Game - Indexing

Postby ichabod801 » Sat May 14, 2016 9:23 pm

To choose a random enemy from a list, use the choice function in the random module:

Code: Select all
import random
enemies = ['Ghost', 'Warrior', 'Zombie', 'Skeleton']
enemy = random.choice(enemies)

To choose an option randomly if one is not provided, I generally use a false default:

Code: Select all
def encounter(enemy = ''):
    if not enemy:
        enemy = random.choice(['Ghost', 'Warrior', 'Zombie', 'Skeleton'])
    # handle enemy

With your method of providing an index, you might do this:

Code: Select all
def encounter(enemy_index):
    enemies = ['Dummy','Ghost','Warrior','Zombie','Skeleton']
    enemy = enemies[enemy_index]
    if enemy == 'Dummy':
        enemy = random.choice(enemies[1:])
    # handle enemy

It's clunkier, but it works. Note how I used three variable names (enemy, enemies, and enemy_index). In the code you posted you have the parameter enemy. Then you assign a local variable also named enemy. When you do that you overwrite whatever parameter was passed.

Note that defining the possible enemies within the encounter function is probably a bad idea. If you need to know what the possible enemies are elsewhere, you would have to define it there too. Then you have two definitions of the same thing floating around, which could lead to changing one and not the other, which could cause problems. It's better to have a way that functions like encounter can get the list of valid enemies from a single place.
Due to the reasons discussed here we will be moving to python-forum.io on October 1st, 2016.
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.
Posts: 688
Joined: Sat Feb 09, 2013 12:54 pm
Location: Outside Washington DC

Return to Game Development

Who is online

Users browsing this forum: No registered users and 2 guests