Demo vypthon : systeme à agents avec les abeilles

Soyez le premier à donner votre avis sur cette source.

Vue 6 888 fois - Téléchargée 356 fois

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 / Exemple :


#-------------------------------------------------------------------------------
# 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).

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.