|
Trouver une ressource
Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !
DEMO VYPTHON : SYSTEME À AGENTS AVEC LES ABEILLES
Information sur la source
Description
Ce petit script montre comment on peut coder un système à base d'agents (ici des abeilles). Seuls les aspects 3D sont traités, pas le comportement (qui ici est très frustre). Vpython est suffisamment puissant pour la gestion de millier d'éléments graphique simultanés sans ralentissement.
Source
- #-------------------------------------------------------------------------------
- # Name: Bee.pyw
- # Purpose:
- #
- # Author: Zorg724
- #
- # Created: 03/11/2007
- # Copyright: (c) Zorg724 2007
- # Licence: <your licence>
- #-------------------------------------------------------------------------------
- #!/usr/bin/env python
- # -*- coding: ISO-8859-15 -*-
- # <<tierces>>
- from visual import *
- # <<Built in>>
- from random import Random
- # <<project>>
-
-
- class Object3D:
- """
- this class is a 3d Object abstract class
- """
- sourceRandom = Random()
-
- OBJECT_NUMBER = 0
- def __init__(self):
-
- self.idName = "obj ID: " +str(Object3D.OBJECT_NUMBER) + " / "
- self.form = frame() # frame from VISUAL to design the form of the animat
- self.internObjectList =[] # contain all the primitive object of the form
- # use to change visibility, etc ..
- self.scale = 0 # relative scale of the form to draw it
- self.i = 0 # X poisiton into the Matrix 3D
- self.j = 0 # Y poisiton into the Matrix 3D
- self.k = 0 # Z poisiton into the Matrix 3D
-
- Object3D.OBJECT_NUMBER += 1 # count of object
-
- def addObjectInForm(self,anObject):
- """
- addObjectInForm(anObject) : use to add to the frame (form) a primitive visual object
- and complete self.internObjectList list
- """
- anObject.frame = self.form
- self.internObjectList.append(anObject)
-
- def setPositionInMatrix3D(self,i,j,k):
- """
- set the i,j,k value in the 3d Matrix with correspond to the x,y,z values
- """
- self.i = i
- self.j = j
- self.k = k
-
- def getPositionInMatrix3D(self):
- """
- get the i,j,k value in the 3d Matrix with correspond to the x,y,z values
- return a tuple (i,j,k)
- """
- return (self.i, self.j , self.k)
-
- def setPosition(self, position = array([0,0,0])):
- """
- setPosition(self, position=array([0,0,0]): set the forme at the place position
- default : 0,0,0
- """
- self.form.pos = position
-
- def getPosition(self):
- """
- getPosition : return the current object position
- """
- return self.form.pos
-
- def setvisibility(self,visibilityState):
- """
- setvisibility(self,visibilityState): modify the visibility State
- visibilityState = 0 : form not visibile
- visibilityState = 1 : form visibile
- """
- if visibilityState == 0 :
- for object in self.form.objects:
- object.visible = 0
- else:
- for obj in self.internObjectList:
- obj.visible = 1
-
- def draw(self,scale = 1):
- """
- Draw the form with primitive of Visual or others (complete the self.form attribute)
- scale =1 (default), if change, the form dimension are multiply by 'scale'
- """
- self.scale = scale
- #default form: a sphere
- self.addObjectInForm( sphere(radius = 0.5, color = color.red) )
-
- def redraw(self):
- """
- redraw the form if needed (change color,position ..)
- """
- self.moveInternForm()
-
-
- def moveInternForm(self):
- """
- move intern form of the object ( like legs or wings ... )
- """
- #~ print "move Intern Form"
- pass
-
-
- def getId(self):
- """
- return the idName of the object
- """
- return str(self.idName)
-
-
-
- class Animat(Object3D):
- """
- this class represents an abstract animat
- it accept an behaviour in order to know its own behaviour
- """
- ANIMAT_NUMBER = 0
- def __init__(self):
- """
- Init an animat
- """
- Object3D.__init__(self)
- Animat.ANIMAT_NUMBER += 1 #count of animat
-
- #Name of the class and id
- self.idName += " " +" animat : " + str(Animat.ANIMAT_NUMBER) + " / " #name for Animat's identifier
-
- self.fieldOfView = 1 #by default the fiel of view is one ceil around the animat
- #local view if fieldOfView = 1, no view if fieldOfView = 0,
- #global view if fieldOfView = max of the 3d Matrix
-
- self.trajectory = curve(radius = 0 ,color = color.white) #trajectory associated to the animat
- self.behaviour = None
-
- def changeDirection(self,direction):
- """
- move the axe of the form to turn to the direction of the motion
- """
- self.form.axis = direction
-
- def move(self,**args):
- """
- move : move in the world.Change position, interaction management ...
- the animat is not redraw. It move only in the world representation
- """
- args['animat'] = self
- if(self.behaviour != None):
- self.behaviour.execute(args) #delegation to behaviour to compute the action to do
-
- def setBehaviour(self,abehaviour):
- """
- setBehaviour: set the behaviour to know how to interact with others objects
- """
- self.behaviour = abehaviour
-
-
- class Bee(Animat):
- """
- Represente une abeille num?rique
- """
- #wings attributes
- WingsState_In = 0
- WingsState_Out = 1
- WingsState_Stop = 2
- BeeId = 0
-
- def __init__( self,
- iD = 0,
- drawLabel = 0,
- drawVelocityVector = 0,
- drawTrajectoryTrace = 0):
-
- Animat.__init__(self)
-
- self.wingsState = Bee.WingsState_In
- self.idName += str(self.__class__) + " : " + str(Bee.BeeId)
- self.form.name = self.idName
- #~ print "--Bee: self.idName : " + self.idName
-
- Bee.BeeId += 1
- #~ print "self.forme.name " + self.forme.name
- self.Direction = (Animat.sourceRandom.random(),Animat.sourceRandom.random(),Animat.sourceRandom.random())
-
- def getId(self):
- """
- return the id of the animal
- """
- return str(self.idName)
-
- def draw(self,scale = 1):
-
- colorBee =[Animat.sourceRandom.random(),Animat.sourceRandom.random(),Animat.sourceRandom.random()]
- #body
- b1 = sphere( pos = (0.28, 0, 0), radius = 0.2, color = color.yellow)
- b2 = sphere( pos = (0.6, 0, 0), radius = 0.2, color = color.black)
- b3 = sphere( pos = (0.7, 0, 0), radius = 0.2, color = color.yellow)
- b4 = sphere( pos = (0.8, 0, 0), radius = 0.2, color = color.black)
-
- #eye
- e1 = sphere( pos = (0, 0.05, -0.08), radius = 0.20, color = color.black)
- e2 = sphere( pos = (0, 0.05, 0.07), radius = 0.20, color = color.black)
-
- #Wing_IN
- self.wing1 = curve( pos=[(0.25,0,0), (0.7,0.3,-0.7), (2,0.5,-0.9),(0.7,0.3,0),(0.25,0,0) ], color = color.black)
- self.wing2 = curve( pos=[(0.25,0,0), (0.7,0.3,0.7), (2,0.5,0.9),(0.7,0.3,0),(0.25,0,0) ], color = color.black)
-
- #Wing_OUT
- self.wing3 = curve( pos=[(0.25,0,0), (0.7,0.3,-0.3), (2,0.5,-0.6),(0.7,0.3,0),(0.25,0,0) ], color = color.black)
- self.wing4 = curve( pos=[(0.25,0,0), (0.7,0.3,0.3), (2,0.5,0.6),(0.7,0.3,0),(0.25,0,0) ], color = color.black)
-
- self.addObjectInForm(b1); self.addObjectInForm(b2);
- self.addObjectInForm(b3); self.addObjectInForm(b4);
- self.addObjectInForm(e1); self.addObjectInForm(e2);
- self.addObjectInForm(self.wing1); self.addObjectInForm(self.wing2);
- self.addObjectInForm(self.wing3); self.addObjectInForm(self.wing4);
-
- #definition du vecteur vitesse
- def setVelocity(self,vx,vy,vz):
- self.form.velocity = vector(vx,vy,vz)
- #la fourmis est dirig?e le long de son vecteur vitesse
- self.form.axis = self.form.velocity
-
- def moveInternForm(self):
- self.moveWings()
-
- def moveWings(self):
- #deux mouvements: \/ = out puis || = init
- #~ O O
-
- if self.wingsState == Bee.WingsState_In:
- #~ print "IN"
- self.wing1.visible = false
- self.wing2.visible = false
- self.wing3.visible = true
- self.wing4.visible = true
- self.wingsState = Bee.WingsState_Out
-
- elif self.wingsState == Bee.WingsState_Out :
- #~ print "OUT"
- self.wing1.visible =true
- self.wing2.visible =true
- self.wing3.visible =false
- self.wing4.visible =false
-
- self.wingsState = Bee.WingsState_In
- else:
- #arret pas de mouvement
- pass
-
-
- def move2(self,g = 9.81, dt =0.01):
-
- self.moveInternForm()
- limitWorld =50
-
- self.form.pos += vector(0.2*sin(self.Direction[0]+ self.Direction[2]),
- 0.2*cos(self.Direction[1]+ self.Direction[2]),
- self.Direction[2])
-
- if self.form.y < 1 or self.form.y > limitWorld:
- self.form.velocity.y = - self.form.velocity.y
-
- if self.form.x< -limitWorld or self.form.x >limitWorld:
- self.form.velocity.x = - self.form.velocity.x
-
- if self.form.z< -limitWorld or self.form.z >limitWorld:
- self.form.velocity.z = - self.form.velocity.z
- self.form.axis = self.form .velocity
-
-
-
- if __name__ == '__main__':
- scene.background =color.white
- scene.fullscreen =1
- scene.autoscale = 0
- sourceRandom = Random()
- longueurMonde = 50
- theGround = box(pos=(0,0,0), length = 2*longueurMonde, height=0.01, width = 2* longueurMonde, color =[0,0.5,0])
- LongueurMaxHerbe = 10
- for numCylindre in range(1,longueurMonde* 50):
- cylinder(pos =(longueurMonde *Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1]),
- 0,
- longueurMonde*Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1])),
- axis = (LongueurMaxHerbe*Animat.sourceRandom.random(),
- LongueurMaxHerbe*Animat.sourceRandom.random(),
- LongueurMaxHerbe*Animat.sourceRandom.random()),
- color = [0 ,Animat.sourceRandom.random(),0],
- radius =0.1* Animat.sourceRandom.random())
-
-
- listAbeille = []
- nbAbeilles = 100
- for abeil in range (0,nbAbeilles):
- abeille = Bee()
- abeille.draw()
- abeille.setPosition(array([2*Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1]),
- 2*Animat.sourceRandom.random(),
- 3*Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1])]))
-
- abeille.setVelocity(-0.005*Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1]),
- -0.03*Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1]),
- 0.1*Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1]))
-
- listAbeille.append(abeille)
-
-
- while(1):
- rate(200)
- for abeil in listAbeille:
- abeil.move2()
#-------------------------------------------------------------------------------
# Name: Bee.pyw
# Purpose:
#
# Author: Zorg724
#
# Created: 03/11/2007
# Copyright: (c) Zorg724 2007
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
# -*- coding: ISO-8859-15 -*-
# <<tierces>>
from visual import *
# <<Built in>>
from random import Random
# <<project>>
class Object3D:
"""
this class is a 3d Object abstract class
"""
sourceRandom = Random()
OBJECT_NUMBER = 0
def __init__(self):
self.idName = "obj ID: " +str(Object3D.OBJECT_NUMBER) + " / "
self.form = frame() # frame from VISUAL to design the form of the animat
self.internObjectList =[] # contain all the primitive object of the form
# use to change visibility, etc ..
self.scale = 0 # relative scale of the form to draw it
self.i = 0 # X poisiton into the Matrix 3D
self.j = 0 # Y poisiton into the Matrix 3D
self.k = 0 # Z poisiton into the Matrix 3D
Object3D.OBJECT_NUMBER += 1 # count of object
def addObjectInForm(self,anObject):
"""
addObjectInForm(anObject) : use to add to the frame (form) a primitive visual object
and complete self.internObjectList list
"""
anObject.frame = self.form
self.internObjectList.append(anObject)
def setPositionInMatrix3D(self,i,j,k):
"""
set the i,j,k value in the 3d Matrix with correspond to the x,y,z values
"""
self.i = i
self.j = j
self.k = k
def getPositionInMatrix3D(self):
"""
get the i,j,k value in the 3d Matrix with correspond to the x,y,z values
return a tuple (i,j,k)
"""
return (self.i, self.j , self.k)
def setPosition(self, position = array([0,0,0])):
"""
setPosition(self, position=array([0,0,0]): set the forme at the place position
default : 0,0,0
"""
self.form.pos = position
def getPosition(self):
"""
getPosition : return the current object position
"""
return self.form.pos
def setvisibility(self,visibilityState):
"""
setvisibility(self,visibilityState): modify the visibility State
visibilityState = 0 : form not visibile
visibilityState = 1 : form visibile
"""
if visibilityState == 0 :
for object in self.form.objects:
object.visible = 0
else:
for obj in self.internObjectList:
obj.visible = 1
def draw(self,scale = 1):
"""
Draw the form with primitive of Visual or others (complete the self.form attribute)
scale =1 (default), if change, the form dimension are multiply by 'scale'
"""
self.scale = scale
#default form: a sphere
self.addObjectInForm( sphere(radius = 0.5, color = color.red) )
def redraw(self):
"""
redraw the form if needed (change color,position ..)
"""
self.moveInternForm()
def moveInternForm(self):
"""
move intern form of the object ( like legs or wings ... )
"""
#~ print "move Intern Form"
pass
def getId(self):
"""
return the idName of the object
"""
return str(self.idName)
class Animat(Object3D):
"""
this class represents an abstract animat
it accept an behaviour in order to know its own behaviour
"""
ANIMAT_NUMBER = 0
def __init__(self):
"""
Init an animat
"""
Object3D.__init__(self)
Animat.ANIMAT_NUMBER += 1 #count of animat
#Name of the class and id
self.idName += " " +" animat : " + str(Animat.ANIMAT_NUMBER) + " / " #name for Animat's identifier
self.fieldOfView = 1 #by default the fiel of view is one ceil around the animat
#local view if fieldOfView = 1, no view if fieldOfView = 0,
#global view if fieldOfView = max of the 3d Matrix
self.trajectory = curve(radius = 0 ,color = color.white) #trajectory associated to the animat
self.behaviour = None
def changeDirection(self,direction):
"""
move the axe of the form to turn to the direction of the motion
"""
self.form.axis = direction
def move(self,**args):
"""
move : move in the world.Change position, interaction management ...
the animat is not redraw. It move only in the world representation
"""
args['animat'] = self
if(self.behaviour != None):
self.behaviour.execute(args) #delegation to behaviour to compute the action to do
def setBehaviour(self,abehaviour):
"""
setBehaviour: set the behaviour to know how to interact with others objects
"""
self.behaviour = abehaviour
class Bee(Animat):
"""
Represente une abeille num?rique
"""
#wings attributes
WingsState_In = 0
WingsState_Out = 1
WingsState_Stop = 2
BeeId = 0
def __init__( self,
iD = 0,
drawLabel = 0,
drawVelocityVector = 0,
drawTrajectoryTrace = 0):
Animat.__init__(self)
self.wingsState = Bee.WingsState_In
self.idName += str(self.__class__) + " : " + str(Bee.BeeId)
self.form.name = self.idName
#~ print "--Bee: self.idName : " + self.idName
Bee.BeeId += 1
#~ print "self.forme.name " + self.forme.name
self.Direction = (Animat.sourceRandom.random(),Animat.sourceRandom.random(),Animat.sourceRandom.random())
def getId(self):
"""
return the id of the animal
"""
return str(self.idName)
def draw(self,scale = 1):
colorBee =[Animat.sourceRandom.random(),Animat.sourceRandom.random(),Animat.sourceRandom.random()]
#body
b1 = sphere( pos = (0.28, 0, 0), radius = 0.2, color = color.yellow)
b2 = sphere( pos = (0.6, 0, 0), radius = 0.2, color = color.black)
b3 = sphere( pos = (0.7, 0, 0), radius = 0.2, color = color.yellow)
b4 = sphere( pos = (0.8, 0, 0), radius = 0.2, color = color.black)
#eye
e1 = sphere( pos = (0, 0.05, -0.08), radius = 0.20, color = color.black)
e2 = sphere( pos = (0, 0.05, 0.07), radius = 0.20, color = color.black)
#Wing_IN
self.wing1 = curve( pos=[(0.25,0,0), (0.7,0.3,-0.7), (2,0.5,-0.9),(0.7,0.3,0),(0.25,0,0) ], color = color.black)
self.wing2 = curve( pos=[(0.25,0,0), (0.7,0.3,0.7), (2,0.5,0.9),(0.7,0.3,0),(0.25,0,0) ], color = color.black)
#Wing_OUT
self.wing3 = curve( pos=[(0.25,0,0), (0.7,0.3,-0.3), (2,0.5,-0.6),(0.7,0.3,0),(0.25,0,0) ], color = color.black)
self.wing4 = curve( pos=[(0.25,0,0), (0.7,0.3,0.3), (2,0.5,0.6),(0.7,0.3,0),(0.25,0,0) ], color = color.black)
self.addObjectInForm(b1); self.addObjectInForm(b2);
self.addObjectInForm(b3); self.addObjectInForm(b4);
self.addObjectInForm(e1); self.addObjectInForm(e2);
self.addObjectInForm(self.wing1); self.addObjectInForm(self.wing2);
self.addObjectInForm(self.wing3); self.addObjectInForm(self.wing4);
#definition du vecteur vitesse
def setVelocity(self,vx,vy,vz):
self.form.velocity = vector(vx,vy,vz)
#la fourmis est dirig?e le long de son vecteur vitesse
self.form.axis = self.form.velocity
def moveInternForm(self):
self.moveWings()
def moveWings(self):
#deux mouvements: \/ = out puis || = init
#~ O O
if self.wingsState == Bee.WingsState_In:
#~ print "IN"
self.wing1.visible = false
self.wing2.visible = false
self.wing3.visible = true
self.wing4.visible = true
self.wingsState = Bee.WingsState_Out
elif self.wingsState == Bee.WingsState_Out :
#~ print "OUT"
self.wing1.visible =true
self.wing2.visible =true
self.wing3.visible =false
self.wing4.visible =false
self.wingsState = Bee.WingsState_In
else:
#arret pas de mouvement
pass
def move2(self,g = 9.81, dt =0.01):
self.moveInternForm()
limitWorld =50
self.form.pos += vector(0.2*sin(self.Direction[0]+ self.Direction[2]),
0.2*cos(self.Direction[1]+ self.Direction[2]),
self.Direction[2])
if self.form.y < 1 or self.form.y > limitWorld:
self.form.velocity.y = - self.form.velocity.y
if self.form.x< -limitWorld or self.form.x >limitWorld:
self.form.velocity.x = - self.form.velocity.x
if self.form.z< -limitWorld or self.form.z >limitWorld:
self.form.velocity.z = - self.form.velocity.z
self.form.axis = self.form .velocity
if __name__ == '__main__':
scene.background =color.white
scene.fullscreen =1
scene.autoscale = 0
sourceRandom = Random()
longueurMonde = 50
theGround = box(pos=(0,0,0), length = 2*longueurMonde, height=0.01, width = 2* longueurMonde, color =[0,0.5,0])
LongueurMaxHerbe = 10
for numCylindre in range(1,longueurMonde* 50):
cylinder(pos =(longueurMonde *Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1]),
0,
longueurMonde*Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1])),
axis = (LongueurMaxHerbe*Animat.sourceRandom.random(),
LongueurMaxHerbe*Animat.sourceRandom.random(),
LongueurMaxHerbe*Animat.sourceRandom.random()),
color = [0 ,Animat.sourceRandom.random(),0],
radius =0.1* Animat.sourceRandom.random())
listAbeille = []
nbAbeilles = 100
for abeil in range (0,nbAbeilles):
abeille = Bee()
abeille.draw()
abeille.setPosition(array([2*Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1]),
2*Animat.sourceRandom.random(),
3*Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1])]))
abeille.setVelocity(-0.005*Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1]),
-0.03*Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1]),
0.1*Animat.sourceRandom.random()*Animat.sourceRandom.choice([-1,1]))
listAbeille.append(abeille)
while(1):
rate(200)
for abeil in listAbeille:
abeil.move2()
Conclusion
Pour augmenter la vitesse sur l'aspect des collision, il faut utiliser un moteur physique comme Pyode (binding ver Open Dynamic Engine).
Fichier Zip
Pour les "Membres Club", vous pouvez télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !
Télécharger le zip
Sources du même auteur
Sources de la même categorie
Sources en rapport avec celle ci
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
Qu'est ce que le python permet de réaliser!! [ par Mansuz ]
Mansuz Salut! J'aurais aimé savoir ce qui peut être réalisé en Python. Par exemple Flash c'est les petites anims, des jeux funs. Le C pour fair des a
affichage des images sur python [ par amina22 ]
salut,je sais qu'on peut afficher les images .gif avec python mais je veux savoir si on peut afficher les images(jpeg,jpg,..) et les vidéos si oui et
charger un fichier avec python [ par amina22 ]
salut,je suis débutante en python et je dois créer une interface qui permet de télécharger un fichier quelconque et de l affichermes taches sont :1.c
python [ par tattou_j ]
Bonjour,Je suis entrain de travailler sur mon pfe, est ce que quelqu'un peut m'aider et m'envoyer des codes en python sur eclipse concernant l'envoi d
Gestion de sessions en python [ par Cab2lhak ]
Bonjour,Je dois réaliser un module de gestion de sessions en python pour un Framework. Mais je métrise pas bien le langage Python, pouvez vous m'aider
existe -t-il un équivalent de la fonction "call" sous Python? [ par Veust ]
Bonjour, je suis en train d'ecrire un code sous python qui d'une part doit rentrer des donner dans une liste(jusque là facile) et d'autre part créer u
Python er Threads [ par dirthangel ]
Salut a tous je suis programmeur perl, j'aimerais savoir si les threads en python sont stable ? car c'est un vraie problème en Perl merci !!!
Note logiciel Python [ par Panthouffle ]
Salut, je cherche un site Internet qui donne un avis des utilisateurs sur le logiciel Python, une note de la part des utilisateurs pour un travail en
Script Python pour html [ par aera group ]
Bonjour, je uis actuelement au chapitre 17 du tutoriel de Gérard Swinnen : Apprendre à programmer avec Python (téléchargable sur http://www.cifen.ulg.
myTetrisGame : un tutoriel Python sympa [ par ibocal ]
Bonjour à tous (toutes),J'ai l'immense plaisir de vous informer que je mets à votre dispositionun petit tutoriel sympathique, qui utilise le prétexte
|
Téléchargements
Logiciels à télécharger sur le même thème :
|