I wrote a rather simple program in Python. Here is the code:
import pygame
import time
from math import *
from random import *
from pygame.locals import *
def mutateBrain(brain):
a = 0
for element in brain:
brain[a][0] = element[0] + (1 * (0.5 - random()))
brain[a][1] = element[1] + (1 * (0.5 - random()))
a = a + 1
return brain;
def generateFirstBrain():
genbrain = []
h = 0;
while randint(0,5) != 0:
asd = [2 * random(), 2 * random()]
genbrain.insert(h, asd)
h = h + 1
return genbrain
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
screen.fill(pygame.Color(255,255,255))
pygame.draw.rect(screen,(255,0,0),(310,0,30,30))
movesa = generateFirstBrain()
movesb = generateFirstBrain()
movesc = generateFirstBrain()
cola = (255,255,0)
colb = (255,0,255)
colc = (0,255,255)
while 1:
movesa = mutateBrain(movesa)
movesb = mutateBrain(movesb)
movesc = mutateBrain(movesc)
step = 0
acurrentx = 320
acurrenty = 240
bcurrentx = 320
bcurrenty = 240
ccurrentx = 320
ccurrenty = 240
totalsn = 0
if (len(movesa) >= len(movesb)) and (len(movesa) >= len(movesc)):
totalsn = len(movesa)
elif (len(movesb) >= len(movesa)) and (len(movesb) >= len(movesc)):
totalsn = len(movesb)
else:
totalsn = len(movesc)
for g in range(totalsn):
screen.fill(pygame.Color(255,255,255))
pygame.draw.rect(screen,(255,0,0),(305,0,30,30))
try:
acurrentx = acurrentx + 1 - movesa[step][0]
acurrenty = acurrenty + 1 - movesa[step][1]
except IndexError:
acurrentx = acurrentx
try:
bcurrentx = bcurrentx + 1 - movesb[step][0]
bcurrenty = bcurrenty + 1 - movesb[step][1]
except IndexError:
bcurrentx = bcurrentx
try:
ccurrentx = ccurrentx + 1 - movesc[step][0]
ccurrenty = ccurrenty + 1 - movesc[step][1]
except IndexError:
ccurrentx = ccurrentx
pygame.draw.rect(screen,cola,(acurrentx,acurrenty,4,4))
pygame.draw.rect(screen,colb,(bcurrentx,bcurrenty,4,4))
pygame.draw.rect(screen,colc,(ccurrentx,ccurrenty,4,4))
pygame.display.flip()
time.sleep(0.01);
step = step + 1
dista = sqrt((acurrentx - 240) ** 2 + (acurrenty) ** 2)
distb = sqrt((bcurrentx - 240) ** 2 + (bcurrenty) ** 2)
distc = sqrt((ccurrentx - 240) ** 2 + (ccurrenty) ** 2)
if(dista<=distb and dista<=distc):
print("a")
movesl = movesa
elif(distb<=dista and distb<=distc):
print("b")
movesl = movesb
else:
print("c")
movesl = movesc
movesa = mutateBrain(movesl)
movesb = mutateBrain(movesa)
movesc = mutateBrain(movesb)
movesa = mutateBrain(movesa)
time.sleep(0.01)
movesb = mutateBrain(movesb)
time.sleep(0.01)
movesc = mutateBrain(movesc)
while 1:
pygame.display.flip()
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
exit(0)
Here, at the end of the first while loop, movesl always gets the same value no matter how many times I run the mutateBrain function. But it changes so there should be a problem with the random. Could somene please help me with this? Thanks.
Aucun commentaire:
Enregistrer un commentaire