En consacrant quelques heures à peine à ChatGPT pour en tester les possibilités dans deux domaines qui n'ont strictement rien à voir (l'informatique avec la génération de code, la sociologie avec la génération d'une analyse des réponses à un questionnaire), j'ai été fasciné par les résultats qu'il est possible d'en tirer.
Sans doute, il faut exercer sa vigilance sur ces résultats. Mais que de temps gagné pour du moins disposer d'une solide base de travail ! C'est tout particulièrement vrai pour ce qui concerne le code, comme le montre ici, dans de multiples cas, le toujours très pédagogue Mosh Hamedani, ou encore ici, dans le cas d'une application, le non moins pédagogue Nick White.
Mise à jour du 22/02/2023 : Petite précision apportée sur ma référence à la citation de The King's Speech pour échapper à la confusion du moment, nombre d'utilisateurs de ChatGPT, mais plus encore de Bing, ayant sombré dans l'anthropomorphisme, et condamnant ces outils à ce titre.
Mise à jour du 15/02/2023 : L'exemple de mon jeu d'aventure peut induire en erreur, parce que ChatGPT a généré un programme entier. Je précise qu'il ne faut pas s'attendre à ce que l'outil fasse ainsi tout à votre place. Je reviendrai sur ce sujet en poussant plus loin cet exemple dans un prochain article. En attendant, n'oubliez pas de tester ChatGPT !
Une aventure en intelligence artificielle
Pour m'en tenir au code, puisque c'est le sujet sur ce blog, voici ce que j'ai demandé à ChatGPT, rejouant approximativement la scène d'un des premiers programmes que je me souviens d'avoir écrit sur une calculatrice Casio :
Write a program for a short adventure game. Write in Python. The game must be text based. The user and the creatures in this game have those attributes: life points, strength. The user has to explore a world until he finds a treasure, at which point the game ends. If the player dies during the exploration, the game starts over.
The world is a square grid which side is 200 squares. The user is placed at a random location on the grid where there is no monster and no treasure. A random number of monsters between 50 and 100 are generated. Each monster is placed a random location on the grid where there is no monster, no treasure and no player. The treasure is placed at a random location on the grid where there is no player and no monster.
To explore the world, the player must be asked one of the following direction: north, south, east or west. If the direction leads the player outside the grid, the player must not be moved and must be asked again a direction.
If the player move to a square where there is monster, he must fight this monster. If he kills the monster, he earns experience points related to the strength of the monster and he can keep on exploring the world. If he is killed, he has to start the game again.
Et voici le code qu'il a généré, que j'invite chacun à tester :
import random
# Constants
GRID_SIZE = 200
MIN_MONSTERS = 50
MAX_MONSTERS = 100
# Player attributes
player_life = 100
player_strength = random.randint(1, 10)
player_position = [random.randint(0, GRID_SIZE - 1), random.randint(0, GRID_SIZE - 1)]
# Monster attributes
num_monsters = random.randint(MIN_MONSTERS, MAX_MONSTERS)
monsters = []
for i in range(num_monsters):
monster = {}
monster['life'] = random.randint(1, 100)
monster['strength'] = random.randint(1, 10)
monster['position'] = [random.randint(0, GRID_SIZE - 1), random.randint(0, GRID_SIZE - 1)]
monsters.append(monster)
# Treasure attributes
treasure_position = [random.randint(0, GRID_SIZE - 1), random.randint(0, GRID_SIZE - 1)]
# Game loop
while True:
print("You are currently at", player_position)
print("Choose a direction to move (north, south, east, west):")
direction = input().lower()
# Check if direction is valid
if direction == "north":
if player_position[1] > 0:
player_position[1] -= 1
else:
print("You cannot move in that direction.")
continue
elif direction == "south":
if player_position[1] < GRID_SIZE - 1:
player_position[1] += 1
else:
print("You cannot move in that direction.")
continue
elif direction == "east":
if player_position[0] < GRID_SIZE - 1:
player_position[0] += 1
else:
print("You cannot move in that direction.")
continue
elif direction == "west":
if player_position[0] > 0:
player_position[0] -= 1
else:
print("You cannot move in that direction.")
continue
else:
print("Invalid direction.")
continue
# Check if player encounters a monster
for monster in monsters:
if player_position == monster['position']:
print("You have encountered a monster!")
while True:
print("Do you want to fight the monster? (yes or no)")
fight = input().lower()
if fight == "yes":
while monster['life'] > 0 and player_life > 0:
monster['life'] -= player_strength
player_life -= monster['strength']
print("Monster life:", monster['life'])
print("Your life:", player_life)
if player_life > 0:
print("You have defeated the monster.")
break
else:
print("You have been defeated by the monster.")
player_life = 100
player_position = [random.randint(0, GRID_SIZE - 1), random.randint(0, GRID_SIZE - 1)]
break
elif fight == "no":
print("You have decided to run away.")
break
else:
print("Invalid choice.")
continue
# Check if player finds the treasure
if player_position == treasure_position:
print("You have found the treasure!")
break
Si ChatGPT s'interrompt lorsqu'il génère du code, comme cela a été le cas ici, il suffit de saisir quelque chose comme "continue" ou "finish your answer".
Ce code ne fait pas tout ce que j'ai demandé, mais il fonctionne. Cela étant, lors de précédentes générations, ChatGPT a généré du code plus complet. L'effet d'avoir demandé plusieurs fois la même chose, car j'ai été confronté à plusieurs plantages - sans compter des interruptions que j'ai à tort considérées comme tels, le temps que je comprenne comment lui dire de continuer -, ChatGPT en ayant déduit que je n'étais satisfait ? Bah ! au minimum, c'est une excellente base :
Ce qui est bluffant, c'est que ChatGPT exploite le contexte de la conversation, ce qui signifie qu'il est possible de poursuivre en lui demandant de modifier ce code, notamment en fonction de nouveaux besoins qui se font jour. Ainsi, je lui ai demandé, en français cette fois qui plus est :
Avant la boucle principale, ajoute des instructions pour afficher la liste des monstres et leurs coordonnées.
ChatGPT a tout regénéré, mais j'aurais pu lui demander de ne générer que ce qu'il fallait. Toutefois, commentaires aidant, voici les instructions qu'il m'a suffit de reprendre :
# Display list of monsters and their coordinates
print("List of Monsters:")
for i, monster in enumerate(monsters):
print(f"Monster {i + 1}: {monster}")

