> Tutorial
Variables are a fundamental concept in every programming language. They are storage locations that keep values in memory so you can reuse them.
Variables can hold several types of values:
12, 5.59"hello"True, FalseNone: the absence of a valueIn Python, you create a variable simply by assigning it a value with =. There's no keyword to write in front of it:
# We declare the enemy variable and assign it the value of Fight.getNearestEnemy()
enemy = Fight.getNearestEnemy()
To use the value stored in a variable, you simply write its name:
# We move toward the enemy
me.moveToward(enemy)
# We try to shoot at it!
me.useWeapon(enemy)
Here me is your own leek, obtained with Fight.me, and enemy is the nearest enemy, obtained with Fight.getNearestEnemy(). We then pass enemy to the moveToward and useWeapon methods.
Your code runs again from the top every turn, so a variable only lives for the duration of the turn. To keep a value from one turn to the next, define a turn() function: the code outside turn() runs only once (when the AI loads), while turn() runs again every turn. The global keyword lets turn() reassign a variable defined outside of it.
# Runs only once, when the AI loads
turn_count = 0
# Called every turn
def turn():
global turn_count
turn_count += 1
Fight.me.say(f"Turn {turn_count}")
In the rest of the tutorial, we'll mostly write simple AIs (without turn()) that run in full every turn.
What is a variable?
A value that changes often A place to store a value
Which code declares a variable named foo?
foo = 12 foo = "hello" let foo = 12 int foo = 12
me = Fight.me
# We take the pistol
me.setWeapon(Weapon.pistol) # Careful: this costs 1 TP
# We get the nearest enemy
enemy = Fight.getNearestEnemy()
# We move toward the enemy
me.moveToward(enemy)
# We try to shoot at it!
me.useWeapon(enemy)
Impossible de charger les données du jeu.
Vérifiez votre connexion et réessayez.