2

So here's what I want to do right now. Simply put I am currently working on a card game and the way I have the game pick the cards for the AI is like this:

  1. Make a list containing all the available cards, sorted by the damage (Lowest to highest). Let's call this list 'ai_list'

  2. Set the card that will be placed (enemy_card) to ai_list[index]. 'index' being the number I want to increase by one every time the function is run.

So I currently have the game execute in turns (player-enemy-player-enemy...), but the problem is that I don't know how to increase the index (set to 0 in the beginning) every time the function for the AI's card placing runs.

How can I do this?

Joshua Kim
  • 245
  • 1
  • 4
  • 13
  • 1
    Use a global variable. A local variable will reset every time the function is run. Many people (with good reason) frown on global variables, but they are often a natural way to keep track of a game state. – John Coleman Jan 16 '17 at 14:10
  • 2
    I copy-pasted your question's exact title into a Google search and the resulting duplicate question was in the top five results. You are expected to perform at least a few seconds of research before posting a new question. – TigerhawkT3 Jan 16 '17 at 14:28

2 Answers2

10

Seems like you want to count the number of times a function is being called. You can use a very simple decorator for that:

def count(func):
    def wrapper(*args, **kwargs):
        wrapper.counter += 1    # executed every time the wrapped function is called
        return func(*args, **kwargs)
    wrapper.counter = 0         # executed only once in decorator definition time
    return wrapper

@count
def func():
    pass

print(func.counter)
# 0
func()
print(func.counter)
# 1
func()
print(func.counter)
# 2
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

why not using a global? something like:

index = 0
def func(..)

     global index
     index+=1
yosi
  • 25
  • 4