def go_to(self, pos): player_pos = self.player.get_centre_pos() dist = general.distance(player_pos, pos) if dist < 10: ## We're there! self.player.vel = [0,0] self.player.acc = [0,0] self.gate_freq = 0 return True max_dist = math.sqrt(general.width**2 + general.height**2) gate_freq = (1.0*dist/max_dist) * 1 + 1 sin_old = math.sin((self.time)/180.0 * general.PI) self.time = self.time + 100 * gate_freq sin_new = math.sin((self.time)/180.0 * general.PI) if sin_old * sin_new <= 0: diff_x = pos[0] - player_pos[0] diff_y = pos[1] - player_pos[1] #self.player.vel[0] = diff_x / 20.0 #self.player.vel[1] = diff_y / 20.0 #return new_acc = [0,0] fire_acc = self.player.fire_acc if diff_x < 0: new_acc[0] = - fire_acc elif diff_x > 0: new_acc[0] = fire_acc if diff_y < 0: new_acc[1] = - fire_acc elif diff_y > 0: new_acc[1] = fire_acc self.player.acc[0] = new_acc[0] self.player.acc[1] = new_acc[1] #if dist < 20: # self.player.vel_threshold = general.PLAYER_VEL_LIMIT * dist / 100.0 #elif dist < 50: # self.player.vel_threshold = general.PLAYER_VEL_LIMIT * dist / 80.0 #elif dist < 100: # self.player.vel_threshold = general.PLAYER_VEL_LIMIT * dist / 30.0 #else: # self.player.vel_threshold = general.PLAYER_VEL_LIMIT if self.player.relax > 0.5: if dist < 100: self.player.vel_threshold = general.PLAYER_VEL_LIMIT * dist / 25.0 else: if dist < 100: self.player.vel_threshold = general.PLAYER_VEL_LIMIT * dist / 20.0
def go_to(self, pos): player_pos = self.player.get_centre_pos() dist = general.distance(player_pos, pos) if dist < 10: ## We're there! self.player.vel = [0, 0] self.player.acc = [0, 0] self.gate_freq = 0 return True max_dist = math.sqrt(general.width**2 + general.height**2) gate_freq = (1.0 * dist / max_dist) * 1 + 1 sin_old = math.sin((self.time) / 180.0 * general.PI) self.time = self.time + 100 * gate_freq sin_new = math.sin((self.time) / 180.0 * general.PI) if sin_old * sin_new <= 0: diff_x = pos[0] - player_pos[0] diff_y = pos[1] - player_pos[1] #self.player.vel[0] = diff_x / 20.0 #self.player.vel[1] = diff_y / 20.0 #return new_acc = [0, 0] fire_acc = self.player.fire_acc if diff_x < 0: new_acc[0] = -fire_acc elif diff_x > 0: new_acc[0] = fire_acc if diff_y < 0: new_acc[1] = -fire_acc elif diff_y > 0: new_acc[1] = fire_acc self.player.acc[0] = new_acc[0] self.player.acc[1] = new_acc[1] #if dist < 20: # self.player.vel_threshold = general.PLAYER_VEL_LIMIT * dist / 100.0 #elif dist < 50: # self.player.vel_threshold = general.PLAYER_VEL_LIMIT * dist / 80.0 #elif dist < 100: # self.player.vel_threshold = general.PLAYER_VEL_LIMIT * dist / 30.0 #else: # self.player.vel_threshold = general.PLAYER_VEL_LIMIT if self.player.relax > 0.5: if dist < 100: self.player.vel_threshold = general.PLAYER_VEL_LIMIT * dist / 25.0 else: if dist < 100: self.player.vel_threshold = general.PLAYER_VEL_LIMIT * dist / 20.0
def execute(self, GI): namesize = 20 #height in pixels for the speaker's name namepadding = 3 #pixels away from the edge of the box for the name placement dialogwidthfraction = .90 #the fraction of the width of the box that the lines of dialog take linesPerBox = 3 #how many lines of text in the box # if player is on the top half of the screen or exactly in the middle, make a text box on the bottom # otherwise, if player's on the bottom half, make it on the top. # and wait for an enter key press to go to the next line box = pg.Surface((int(GI.display.getWH()[0]*.80), int(GI.display.getWH()[1]*.25))) box.fill((96,123,139)) box.set_alpha(180) alph = (99,100,101) box.set_colorkey(alph) n3 = namepadding*3 x1 = 0 y1 = n3 x2 = namepadding y2 = namepadding x3 = n3 y3 = 0 y = .5*((x1**2+y1**2)*(x3-x2) + (x2**2+y2**2)*(x1-x3) + (x3**2+y3**2)*(x2-x1)) / (y1*(x3-x2)+y2*(x1-x3)+y3*(x2-x1)) radius = g.distance((y,y), (namepadding, namepadding)) for i in range(n3): for j in range(n3): if g.distance((i,j),(y,y)) > radius: box.set_at((i,j), alph) box.set_at((box.get_rect().width - i, j), alph) box.set_at((i, box.get_rect().height - j), alph) box.set_at((box.get_rect().width - i, box.get_rect().height - j), alph) enter = GI.font.text("PRESS ENTER", namesize) enter.place(box, (box.get_rect().width-namepadding-enter.getLength(), namepadding), center=False) # dialogLinesPerBox = (box.get_rect().height - namesize - namepadding*2) / dialogsize dialogsize = (box.get_rect().height - namesize - namepadding*3) / linesPerBox linesPx = [(int(box.get_rect().width*((1-dialogwidthfraction)/2)), int(namesize + namepadding*2))] for i in range(linesPerBox-1): linesPx.append((linesPx[i][0], int(linesPx[i][1]+dialogsize))) dialogWidth = int(box.get_rect().width*dialogwidthfraction) # make a space and ellipses space = GI.font.text(" ", dialogsize) ooo = GI.font.text("...", dialogsize) dialogLines = self.extra[1:] q = 0 while q < (len(dialogLines)): boxc = box.copy() boxc = pg.Surface(box.get_size()) boxc.set_colorkey(alph) boxc.fill(alph) speaker, words = dialogLines[q].split(":] ") if speaker == "%PLAYER": speaker = GI.player.getName() speaker = GI.font.text(speaker+":", namesize) speaker.place(boxc, (namepadding,namepadding), center=False) words = words.split(' ') for i in range(len(words)): words[i] = GI.font.text(words[i], dialogsize) line = 0 lines = [] word = 1 lines.append(words[0]) while word < len(words): # if (line != 0) and ((line-1)%linesPerBox == 0): # print line, linesPerBox, linesPerBox%line # this = lines[line].getLength() + space.getLength() + words[word].getLength() + ooo.getLength() # else: # this = lines[line].getLength() + space.getLength() + words[word].getLength() # if this <= dialogWidth: # if (line != 0) and ((line-1)%linesPerBox == 0): # lines[line] = lines[line].concatenate([space, words[word], ooo]) # else: # lines[line] = lines[line].concatenate([space, words[word]]) # else: # line+=1 # lines.append(words[word]) # word +=1 this = lines[line].getLength() + space.getLength() + words[word].getLength() if this <= dialogWidth: lines[line] = lines[line].concatenate([space, words[word]]) else: line+=1 lines.append(words[word]) word +=1 passback = speaker.getStr()+"] " for i in range(len(lines)): if i < linesPerBox: lines[i].place(boxc, linesPx[i], center=False) else: passback += lines[i].getStr() if i != len(lines)-1: passback+=" " if i >= linesPerBox: dialogLines.insert(q+1, passback) w = GI.display.getWH()[0] h = GI.display.getWH()[1] - GI.player.getBelt().getImg().get_height() if GI.playerOnTopHalf(): pos = ((w - boxc.get_rect().width) /2., h - boxc.get_rect().height-g.TILE_RES[1]*1.5) else: pos = ((w - boxc.get_rect().width) /2., g.TILE_RES[1]*1.5) GI.window.blit(box, pos) GI.window.blit(boxc, pos) GI.renderView() GI.clearWindow() gotEnter = False while not gotEnter: #wait only gets the first event that happens, so it's not a list evt = pg.event.wait() evt, trash0 = GI.dispatch([evt]) if len(evt) > 0: evt = evt[0] if evt.type == pg.KEYDOWN: if evt.dict['key'] == pg.K_RETURN: gotEnter = True break q+=1 GI.renderView()
def distance(self, creature1, creature2): return general.distance(creature1.get_centre_pos(), creature2.get_centre_pos())
def move(self, mv, dt, forceTurn = False): self.previousRect = self.getRect().copy() xmove, ymove = 0, 0 step = (self.pixStep*dt) direction = mv if "U" in direction: if ("L" in direction) or ("R" in direction): ymove -= step**.5 else: ymove -= step if "D" in direction: if ("L" in direction) or ("R" in direction): ymove += step**.5 else: ymove += step if "L" in direction: if ("U" in direction) or ("D" in direction): xmove -= step**.5 else: xmove -= step if "R" in direction: if ("U" in direction) or ("D" in direction): xmove += step**.5 else: xmove += step self.pos = (self.pos[0]+xmove, self.pos[1]+ymove) self.previousPixStepped = self.pixStepped+0 self.pixStepped += g.distance(self.pos, self.rect.topleft) self.rect = pg.Rect(self.pos, self.size) if forceTurn: x, y = self.getRect().center x = x - forceTurn[0] y = y - forceTurn[1] if abs(x)>abs(y): if x>0: trn = "L" else: trn = "R" else: if y>0: trn = "U" else: trn = "D" else: trn = self.overallDirection() #in cases of diagonal, choose U or D for d in trn: self.art = (self.udlrFacing[d][self.currentImg], self.udlrFacing_outline[d][self.currentImg]) self.facing = d if (d == "U") or (d == "D"): break while self.pixStepped >= self.pixStepSize: self.pixStepped -= self.pixStepSize self.currentImg = 0 if (self.currentImg == 3) else self.currentImg+1 self.previousArt = (self.art[0], self.art[1]) self.art = (self.udlrFacing[self.facing][self.currentImg], self.udlrFacing_outline[self.facing][self.currentImg])
def dispatch(self, events, dt=0): froze = False #some things are handled the same way in all states: for event in events: if event.type == pg.QUIT: self.pathFinder.terminate() sys.exit() # elif event.type == pg.KEYDOWN: # key = event.dict['key'] # elif event.type == pg.KEYUP: # key = event.dict['key'] # if key == pg.K_TAB: # self.tabPressed = False if self.state == "main-menu": pass elif self.state == "play": enterPressed = False for event in events: if event.type == pg.KEYDOWN: key = event.dict['key'] casted = False if key == pg.K_RETURN: enterPressed = True elif key == pg.K_TAB: if self.lockedOntoEnemy == None: if len(self.curEnemies) > 0: lock = 0 dist = g.distance(self.player.getRect().center, self.curEnemies[0].getRect().center) for i in range(len(self.curEnemies))[1:]: d = g.distance(self.player.getRect().center, self.curEnemies[i].getRect().center) if d<dist: lock = i+0 dist = d+0 self.lockedOntoEnemy = self.curEnemies[lock] else: self.lockedOntoEnemy = None elif key == pg.K_ESCAPE: self.state = "pause" #release player from any movements self.player.forgetMovement() #launches the menu into its last opened state (or player state if this is the first time opening it) # self.pmenu.changeState(self.pmenu.getState()) return 0, True #movement control elif key == pg.K_UP: self.player.movingDirection("U") elif key == pg.K_DOWN: self.player.movingDirection("D") elif key == pg.K_LEFT: self.player.movingDirection("L") elif key == pg.K_RIGHT: self.player.movingDirection("R") #casting of belt items elif key == pg.K_q: casted = self.player.cast(0) elif key == pg.K_w: casted = self.player.cast(1) elif key == pg.K_e: casted = self.player.cast(2) elif key == pg.K_r: casted = self.player.cast(3) elif key == pg.K_a: casted = self.player.cast(4) elif key == pg.K_s: casted = self.player.cast(5) elif key == pg.K_d: casted = self.player.cast(6) elif key == pg.K_f: casted = self.player.cast(7) if casted: #will be false if nothing is casted or an empty belt slot is used self.curAttacks.append(casted) elif event.type == pg.KEYUP: key = event.dict['key'] if key == pg.K_UP: self.player.stoppingDirection("U") elif key == pg.K_DOWN: self.player.stoppingDirection("D") elif key == pg.K_LEFT: self.player.stoppingDirection("L") elif key == pg.K_RIGHT: self.player.stoppingDirection("R") mv = self.player.overallDirection() def doEvent(evt, outline=False): self.state = "WE" evt.execute(self) if evt.getOneTime(): #remove the event and return to the "play" state self.eventForeground.remove(evt) if outline: #remove the red outline self.outlinedEvents.remove(evt) self.flipOutlines(self.outlinedEvents) self.state = "play" #release player from any movements self.player.forgetMovement() self.checkForImmediateEvents = True return True #froze = True ############################################ # Deal with immediate events ############### ############################################ if self.checkForImmediateEvents: im = self.eventForeground.immediates() if len(im)>0: for e in im: froze = doEvent(e) else: self.checkForImmediateEvents = False ############################################ ############################################ ############################################ ############################################ # Deal with "enter" ######################## ############################################ #enter overrides movements and triggers events if len(self.outlinedEvents)>0 and enterPressed: evt = self.outlinedEvents[0] froze = doEvent(evt, outline=True) ############################################ ############################################ ############################################ ############################################ # Move player ############################## ############################################ def mvPlayer(mv,dt): if self.lockedOntoEnemy is not None: self.player.move(mv, dt, forceTurn = self.lockedOntoEnemy.getRect().center) else: self.player.move(mv, dt) # Check if the movement is valid by making a smaller rectangle and seeing smallerRect=pg.Rect((0,0),(self.player.getRect().width*.87, self.player.getRect().height*.87)) smallerRect.center = self.player.getRect().center # corners = ( g.pix2tile(smallerRect.topleft), \ # g.pix2tile(smallerRect.topright), \ # g.pix2tile(smallerRect.bottomleft), \ # g.pix2tile(smallerRect.bottomright) ) corners = ( smallerRect.topleft, \ smallerRect.topright, \ smallerRect.bottomleft, \ smallerRect.bottomright ) validZs = self.player.getZ() validZs = [validZs+1, validZs, validZs-1] # If the movement is valid, move the player there highestZC = validZs[2] for c in corners: thisCBlocked = True for z in validZs: # if not self.collisionWithBlockedTile(c, z, player=False): if not self.collision_point(c, z, player=False): thisCBlocked = False if z > highestZC: highestZC = z break if thisCBlocked: self.player.undoMove() if len(mv)>1: for m in mv: # if mvPlayer(m, dt): # self.player.setZ(highestZC) # return True mvPlayer(m,dt) return False self.player.setZ(highestZC) return True # if not self.collisionWithBlockedRect(smallerRect, z, player = False): # couldntMove = False #try to to get a tile from the highest z the player is on #if nothing work your way down to lower zs the player's on # for z in playerZs: # atile = self.map.getTile(self.player.getRect().center, z) # if atile: # self.player.setZ(atile.getZ()) # return True # # else: # self.player.undoMove() # if len(mv)>1: # for m in mv: # if mvPlayer(m, dt): # return True # if couldntMove: # pass #implement sliding # ####################### # ####################### # #get rid of smallerRect ############################################ ############################################ ############################################ ############################################ ############################################ ############################################ def checkForEvents(): playerZs = self.player.getZ() playerZs = [playerZs+1, playerZs, playerZs-1] #tile the player's center pix is on for z in playerZs: tilePlayerOn = self.map.getTile(self.player.getRect().center, z) if tilePlayerOn: break #the events on that tile mustActivate = self.eventForeground.unlockedNotEnterableEventsOn([tilePlayerOn], playerZs) activateIfEnterOnTopOf = self.eventForeground.unlockedEnterableEventsOn([tilePlayerOn], playerZs) #the tile in front of the player (based on the way he faces) for z in playerZs: # will return false if there's no tile at those coords and z tileInFrontOfPlayer = self.map.getTile(self.player.getTilePixInFrontOf(), z) if tileInFrontOfPlayer: break #the events on that tile if tileInFrontOfPlayer: activateIfEnterInFrontOf = self.eventForeground.unlockedEnterableBlockedEventsOn([tileInFrontOfPlayer], playerZs) else: activateIfEnterInFrontOf = [] # turns on outlines for events self.flipOutlines(activateIfEnterOnTopOf+activateIfEnterInFrontOf) # activates an event with enter outside of this function return mustActivate ############################################ ############################################ ############################################ ############################################ ############################################ ############################################ # def triggerStandOns(dt, mustActivate): # #this loop triggers a chain of events that are stood on # self.state = "WE" # #release player from any movements # self.player.forgetMovement() # mustActivate[0].execute(self) # if mustActivate[0].getOneTime(): # self.eventForeground.remove(mustActivate[0]) # self.state = "play" # doit("UD", dt) # return dt ############################################ ############################################ ############################################ def doit(mv, dt): if (len(mv)>0): mvPlayer(mv, dt) if (len(mv)>0): mustActivate = checkForEvents() if (len(mv)>0) and (len(mustActivate)>0): for e in mustActivate: froze = doEvent(e, outline=False) return froze # triggerStandOns(dt, mustActivate) # froze = True froze = froze or doit(mv, dt) ############################################ ############################################ ############################################ #handle enemies rectInFrontOfPlayer = self.player.getRect().copy() if self.player.facing == "U": rectInFrontOfPlayer.top -= g.TILE_RES[1] elif self.player.facing == "D": rectInFrontOfPlayer.top += g.TILE_RES[1] elif self.player.facing == "L": rectInFrontOfPlayer.left -= g.TILE_RES[0] else: rectInFrontOfPlayer.left += g.TILE_RES[0] for e in self.curEnemies: atk = e.tick(dt) if atk: self.curAttacks.append(atk) #deal with players sword attack if rectInFrontOfPlayer.colliderect(e.getRect()): casted = self.player.cast(8) if casted: self.curAttacks.append(casted) ############################################ ############################################ ############################################ ############################################ ############################################ ############################################ #handle player animations (to come) and spell cool downs self.player.tick(dt) ############################################ ############################################ ############################################ ############################################ ############################################ ############################################ #handle attacks for a in self.curAttacks: keepA = a.tick(dt) if not keepA: self.curAttacks.remove(a) #cause damage to player # if a.getAlignment() != self.player.getAlignment() and a.getRect().colliderect(self.player.getRect()): if a.getRect().colliderect(self.player.getRect()) and (a.getZ() == self.player.getZ()): a.hit(self.player) if self.player.getCurStat('hp') <= 0: print "dead!!!!" self.dispatch([pg.event.Event(QUIT, {})]) #cause damage to enemies for e in self.curEnemies: # if a.getAlignment() != e.getAlignment() and a.getRect().colliderect(e.getRect()): if a.getRect().colliderect(e.getRect()) and (a.getZ() == e.getZ()): a.hit(e) if e.getCurrentHP() <= 0: self.curEnemies.remove(e) if self.lockedOntoEnemy == e: self.lockedOntoEnemy = None ############################################ ############################################ ############################################ elif self.state == "pause": if not self.cursr.visible: self.cursr.flipVisible() for event in events: if event.type == pg.KEYDOWN: key = event.dict['key'] if key == pg.K_ESCAPE: self.state = "play" # self.pmenu.clearall() if self.cursr.visible: self.cursr.flipVisible() return 0, True self.pmenu.dispatch(events) # elif event.type == pg.KEYUP: elif self.state == "WE": pass #it returns all events that are not executed in the general state return events, froze
def creaturesTest(rootNode1_acc, rootNode2_acc, showing=False, time_length=None, playing=False, online=False): """ Run the simulation (e.g., game) with all the creatures (e.g., players and balls). """ number_of_balls = 1 number_of_players = 10 number_of_skulls = 0 balls = list() players = list() skulls = list() if online: socket, isClient = tcp_connect(ip_address) if not playing: rootNode1_accx = rootNode1_acc[0] rootNode1_accy = rootNode1_acc[1] rootNode2_accx = rootNode2_acc[0] rootNode2_accy = rootNode2_acc[1] if showing: pygame.init() if showing: os.environ['SDL_VIDEO_CENTERED'] = '1' # if showing: pygame.mouse.set_visible(False) if showing: vis = general.getVisibleSize() window = pygame.display.set_mode( (int(vis[0]), int(vis[1])), pygame.DOUBLEBUF) # , pygame.FULLSCREEN) else: window = pygame.display.set_mode((100, 100)) fitness1 = 0 fitness2 = 0 if showing: pygame.display.set_caption('Genetic Soccer') general.surface = pygame.display.get_surface() field = Field() goal1 = field.getGoal1() goal2 = field.getGoal2() for i in xrange(0, number_of_balls): balls.append(Ball(surface=general.surface, radius=6, showing=showing)) for player_team in xrange(0, 2): for player_role in xrange(0, number_of_players / 2): player_pos = [0, 0] if player_role == 0: player_pos = [ width / 4.0, height / 6.0 * (1.0 if player_team == 0 else 5) ] elif player_role == 1: player_pos = [ width / 2.0, height / 6.0 * (1.0 if player_team == 0 else 5) ] elif player_role == 2: player_pos = [ width / 2.0, height / 3.0 * (1.0 if player_team == 0 else 2) ] elif player_role == 3: player_pos = [(width * 3.0) / 4.0, height / 6.0 * (1.0 if player_team == 0 else 5)] elif player_role == 4: player_pos = [ width / 2.0, height / 7 * (1.0 if player_team == 0 else 6) ] players.append( Player(general.surface, (20, 20), player_pos, player_team + 1, showing)) for i in xrange(0, number_of_skulls): skulls.append(CreatureBodyComputer(surface=general.surface)) ais = [] for idx in xrange(len(players) - 1): i = idx + 1 _ai = None if i == 4 or i == 9: _ai = ai.GoalkeeperAi(players[i], goal1, goal2) else: _ai = ai.Ai(players[i], goal1, goal2) ais.append(_ai) if showing: clock = pygame.time.Clock() counter = 0 while counter < time_length or time_length is None: """ Main loop of the simulation (e.g., game). """ moveCamera(balls[0]) stoppingx_event = False stoppingy_event = False new_key = False mouse_pos = pygame.mouse.get_pos() goal_size = goal1.image.get_size() if online: ball = balls[0] player1 = players[0] player2 = players[1] terminals0 = Terminals(counter, ball.pos, ball.vel, player1.pos, player1.vel, 1, [0, 0], [0, 0], 1) terminals1 = Terminals( counter, ball.pos, ball.vel, [width - player2.pos[0], height - player2.pos[1]], [-player2.vel[0], -player2.vel[1]], 1, [0, 0], [0, 0], 1 ) # width-players[1].pos[0],height-players[1].pos[1], players[1].vel[0], players[1].vel[1], 1) if not playing: players[0].acc[0] = running_tree(terminals0).run_tree( rootNode1_accx) players[0].acc[1] = running_tree(terminals0).run_tree( rootNode1_accy) players[1].acc[0] = running_tree(terminals1).run_tree( rootNode2_accx) players[1].acc[1] = -running_tree(terminals1).run_tree( rootNode2_accy) if showing: clock.tick(120) counter += 1 if showing: """ Background """ if showing: field.blitBackground(general.surface) """ Keyboard events """ input = pygame.event.get() for event in input: whatkey = Keyboard(event) if whatkey.isKEYDOWN(): if whatkey.isEscape(): sys.exit(0) elif whatkey.isEquals(): general.global_zoom *= 1.1 elif whatkey.isMinus(): general.global_zoom /= 1.1 elif whatkey.isLeft(): players[0].fireLeft() elif whatkey.isRight(): players[0].fireRight() elif whatkey.isUp(): players[0].fireUp() elif whatkey.isDown(): players[0].fireDown() elif whatkey.isPeriod(): balls[0].getShooted(players[0]) elif whatkey.isSlash(): balls[0].getShooted(players[0], 0.46) elif whatkey.isA(): players[1].fireLeft() elif whatkey.isD(): players[1].fireRight() elif whatkey.isW(): players[1].fireUp() elif whatkey.isS(): players[1].fireDown() elif whatkey.isBackquote(): balls[0].getShooted(players[1]) elif whatkey.isOne(): balls[0].getShooted(players[1], 0.46) elif whatkey.isKEYUP(): if whatkey.isLeft() or whatkey.isRight(): players[0].stopLeftAndRight() elif whatkey.isUp() or whatkey.isDown(): players[0].stopUpAndDown() elif whatkey.isA() or whatkey.isD(): players[1].stopLeftAndRight() elif whatkey.isW() or whatkey.isS(): players[1].stopUpAndDown() if event.type == pygame.MOUSEBUTTONDOWN: left, top = (x - 50 for x in event.pos) if whatkey.isKEYUP() or whatkey.isKEYDOWN(): new_key = True if online: net.updatePlayers(new_key, isClient, socket, players) nearest_player = players[0] nearest_distance = general.distance(nearest_player.get_centre_pos(), balls[0].get_centre_pos()) for player in players[1:]: _distance = general.distance(player.get_centre_pos(), balls[0].get_centre_pos()) if _distance < nearest_distance: nearest_player = player nearest_distance = _distance for _ai in ais: ai_state = ai.State(nearest_player, _ai.player, balls[0]) ai_state.update() _ai.do(ai_state) for player in players: player.collidingGoal(goal1) player.collidingGoal(goal2) player.move(general.surface, field, counter, cameraPos=cameraPos, goal_size=goal_size) for ball in balls: """ All balls """ ball_centre = ball.getCentre() # fitness1 += 1000/distance(ball_centre, players[0].get_pos()) # fitness2 += 1000/distance(ball_centre, players[1].get_pos()) ball.is_under_player = False # players colliding with the ball for player in players: ball.getKicked(player) # computer player colliding with the ball and the goal for cc in skulls: cc.collidingGoal(goal1) cc.collidingGoal(goal2) ball.getKicked(cc) if debug: print(mouse_pos) cc.acc = [(random.random() - 0.5) / 5.0, (random.random() - 0.5) / 5.0] cc.move(general.surface, field, counter, cameraPos=cameraPos, goal_size=goal_size) # to the pipe (tirake darvaze): is_colliding_goal_pipe_top_right = ( ball.vel[1] < 0 and (diff(ball_centre[1], goal_size[1]) < ball.radius) and (diff(ball_centre[0], (width / 2 + goal_size[0] / 2)) < 3)) is_colliding_goal_pipe_top_left = ( ball.vel[1] < 0 and (diff(ball_centre[1], goal_size[1]) < ball.radius) and (diff(ball_centre[0], (width / 2 - goal_size[0] / 2)) < 3)) is_colliding_goal_pipe_bottom_right = ( ball.vel[1] > 0 and (diff(ball_centre[1], (height - goal_size[1])) < ball.radius) and (diff(ball_centre[0], (width / 2 + goal_size[0] / 2)) < 3)) is_colliding_goal_pipe_bottom_left = ( ball.vel[1] > 0 and (diff(ball_centre[1], (height - goal_size[1])) < ball.radius) and (diff(ball_centre[0], (width / 2 - goal_size[0] / 2)) < 3)) if is_colliding_goal_pipe_top_right or is_colliding_goal_pipe_top_left or is_colliding_goal_pipe_bottom_right or is_colliding_goal_pipe_bottom_left: ball.vel[1] = -ball.vel[1] else: ball.collidingGoal(goal1) ball.collidingGoal(goal2) if goal1.rect.contains(ball.rect): fitness2 += 100 field.score2 += 1 ball.reset() players[0].reset() players[1].reset() players[0].fire_acc += 0.01 players[1].fire_acc += 0.01 if showing: field.setMessage2() elif goal2.rect.contains(ball.rect): fitness1 += 100 field.score1 += 1 ball.reset() players[0].reset() players[1].reset() players[0].fire_acc += 0.01 players[1].fire_acc += 0.01 if showing: field.setMessage1() ball.move(counter, cameraPos=cameraPos) if showing: field.blitField(width=width, height=height, surface=general.surface, cameraPos=cameraPos) vis = general.getVisibleSize() if debug: pygame.draw.rect(general.surface, pygame.Color(0, 0, 0), (0, 0, vis[0], vis[1]), 1) if showing: pygame.display.flip() return (1.0 * fitness1 / counter, 1.0 * fitness2 / counter)