def countDown(self, number, task): if number == 5: print 5 self.count_down = loadObject('5.png') self.count_down.setPos(0,0.1,0) self.count_down.setScale(configs.SCALE*0.1) self.count_down.setAlphaScale(1) taskMgr.doMethodLater(1, countDown, 'draw lines', extraArgs=[self, 4], appendTask=True) if number == 4: self.count_down.removeNode() print 4 self.count_down = loadObject('4.png') self.count_down.setPos(0,0.1,0) self.count_down.setScale(configs.SCALE*0.1) self.count_down.setAlphaScale(1) taskMgr.doMethodLater(1, countDown, 'draw lines', extraArgs=[self, 3], appendTask=True) if number == 3: self.count_down.removeNode() self.count_down = loadObject('3.png') self.count_down.setPos(0,0.1,0) self.count_down.setScale(configs.SCALE*0.1) self.count_down.setAlphaScale(1) print 3 taskMgr.doMethodLater(1, countDown, 'draw lines', extraArgs=[self, 2], appendTask=True) if number == 2: self.count_down.removeNode() self.count_down = loadObject('2.png') self.count_down.setPos(0,0.1,0) self.count_down.setScale(configs.SCALE*0.1) self.count_down.setAlphaScale(1) print 2 taskMgr.doMethodLater(1, countDown, 'draw lines', extraArgs=[self, 1], appendTask=True) if number == 1: self.count_down.removeNode() self.count_down = loadObject('1.png') self.count_down.setPos(0,0.1,0) self.count_down.setScale(configs.SCALE*0.1) self.count_down.setAlphaScale(1) print 1 for entity_id, entity in configs.ENTITIES.items(): if entity['CATEGORY'] == 'player': entity['PLAYER_ID'].detachNode() entity['CIRCLE_NODE'].detachNode() taskMgr.doMethodLater(1, countDown, 'draw lines', extraArgs=[self, 0], appendTask=True) if number == 0: print 0 self.count_down.removeNode() for entity_id, entity in configs.ENTITIES.items(): if entity['CATEGORY'] == 'player': configs.GAME_ONGOING = 1 new_line, line_vertex, line_node = start_new_line(self, entity['NODE'].getX(), entity['NODE'].getZ(), entity['COLOR']) line_id = configs.ENTITY_ID configs.ENTITIES[configs.ENTITY_ID] = {'CATEGORY':'line', 'GEOM':new_line, 'VERTEX':line_vertex, 'NODE': line_node} configs.ENTITY_ID += 1 entity["CURRENT_LINE"] = line_id draw_line(entity_id, start=True) configs.NEXT_BONUS_TIME = globalClock.getFrameTime() + random.randint(3, 10) self.spawn_bonus = taskMgr.add(spawn_bonus, 'bonusSpawner', extraArgs=[self], appendTask=True) return task.done
def _draw_lines_by_points_with_visibility(self, points, color, hidden_color): lines = make_lines_from_points(points) for line in lines: if line[0].visibility == VISIBLE\ or line[0].visibility == TO_VISIBLE: draw_line(self._pixels, line[0], line[1], color) else: draw_line(self._pixels, line[0], line[1], hidden_color)
def test_boundaries(self, entity_id, new_pos_x, new_pos_y): entity = configs.ENTITIES[entity_id] teleport = False if new_pos_x > 1.8: if configs.BORDER == True: entity['ALIVE'] = False else: new_pos_x = -1.8 teleport = True if new_pos_x < -1.8: if configs.BORDER == True: entity['ALIVE'] = False else: new_pos_x = 1.8 teleport = True if new_pos_y > 1: if configs.BORDER == True: entity['ALIVE'] = False else: new_pos_y = -1 teleport = True if new_pos_y < -1: if configs.BORDER == True: entity['ALIVE'] = False else: new_pos_y = 1 teleport = True if teleport == True: if entity["CURRENT_LINE"] != None: draw_line(entity_id, end=True) entity["CURRENT_LINE"] = None new_line, line_vertex, line_node = start_new_line( self, new_pos_x, new_pos_y, entity['COLOR']) line_id = configs.ENTITY_ID configs.ENTITIES[configs.ENTITY_ID] = { 'CATEGORY': 'line', 'GEOM': new_line, 'VERTEX': line_vertex, 'NODE': line_node } configs.ENTITY_ID += 1 entity["CURRENT_LINE"] = line_id return new_pos_x, new_pos_y
def test_boundaries(self, entity_id, new_pos_x, new_pos_y): entity = configs.ENTITIES[entity_id] teleport = False if new_pos_x > 1.8: if configs.BORDER == True: entity['ALIVE'] = False else: new_pos_x = -1.8 teleport = True if new_pos_x < -1.8: if configs.BORDER == True: entity['ALIVE'] = False else: new_pos_x = 1.8 teleport = True if new_pos_y > 1: if configs.BORDER == True: entity['ALIVE'] = False else: new_pos_y = -1 teleport = True if new_pos_y < -1: if configs.BORDER == True: entity['ALIVE'] = False else: new_pos_y = 1 teleport = True if teleport == True: if entity["CURRENT_LINE"] != None: draw_line(entity_id, end=True) entity["CURRENT_LINE"] = None new_line, line_vertex, line_node = start_new_line(self, new_pos_x, new_pos_y, entity['COLOR']) line_id = configs.ENTITY_ID configs.ENTITIES[configs.ENTITY_ID] = {'CATEGORY':'line', 'GEOM':new_line, 'VERTEX':line_vertex, 'NODE':line_node} configs.ENTITY_ID += 1 entity["CURRENT_LINE"] = line_id return new_pos_x, new_pos_y
def draw(self, screen, field, color): draw_line(screen, field, color, self.a, self.b)
def main(stdscr): curses.curs_set(0) win_height, win_width = stdscr.getmaxyx() pix_height = win_height * 4 - win_height % 4 pix_width = win_width * 2 - win_width % 2 arr = [] for i in range(pix_height): row = [] for j in range(pix_width): row.append(0) arr.append(row) last_frame = time.time() while True: # Clear the screen stdscr.refresh() stdscr.erase() for i in range(pix_height): for j in range(pix_width): arr[i][j] = 0 # Project vertices_2d = project(vertices) # Convert the coordinates from the range [-1, 1] to the actual screen width and height for vertex in vertices_2d: vertex[0] = remap(vertex[0], -1, 1, 0, pix_width) vertex[1] = remap(vertex[1], -1, 1, 0, pix_height) # Draw graphics.draw_line(arr, vertices_2d[0], vertices_2d[1]) graphics.draw_line(arr, vertices_2d[0], vertices_2d[5]) graphics.draw_line(arr, vertices_2d[0], vertices_2d[7]) graphics.draw_line(arr, vertices_2d[1], vertices_2d[2]) graphics.draw_line(arr, vertices_2d[1], vertices_2d[4]) graphics.draw_line(arr, vertices_2d[2], vertices_2d[3]) graphics.draw_line(arr, vertices_2d[2], vertices_2d[7]) graphics.draw_line(arr, vertices_2d[3], vertices_2d[4]) graphics.draw_line(arr, vertices_2d[3], vertices_2d[6]) graphics.draw_line(arr, vertices_2d[4], vertices_2d[5]) graphics.draw_line(arr, vertices_2d[5], vertices_2d[6]) graphics.draw_line(arr, vertices_2d[6], vertices_2d[7]) # Render chars = array_to_pixels(arr) for i in range(win_height - 1): for j in range(win_width - 1): stdscr.addstr(i, j, chars[i][j]) # Physics update # axis = [1/math.sqrt(14), 2/math.sqrt(14), 3/math.sqrt(14)] axis = [2, 3, 1] norm = sum(map(lambda x: x**2, axis)) axis = list([x / norm for x in axis]) rotate(vertices, 0.03, axis) # Show FPS now = time.time() stdscr.addstr(0, 0, f'FPS: {int(1/(now - last_frame))}') last_frame = now
def update_players(self, dt): if configs.GAME_ONGOING == 0: return players_alive = 0 average_x_pos = 0.0 average_y_pos = 0.0 min_x_pos = 0 max_x_pos = 0 min_y_pos = 0 max_y_pos = 0 for entity_id, entity in configs.ENTITIES.items(): if entity['CATEGORY'] == 'player': if configs.ARDUINO_MODE == True: value = configs.ARDUINO_BUTTONS_MAP[entity['PLAYER_NUMBER']][0] which_button = 'TURN_LEFT' if value == False: entity['LEFT_ARMED'] = True entity[which_button] = value value = configs.ARDUINO_BUTTONS_MAP[entity['PLAYER_NUMBER']][1] which_button = 'TURN_RIGHT' if value == False: entity['RIGHT_ARMED'] = True entity[which_button] = value if entity['ALIVE'] == False: entity['PARTICLE_PARENT'].disable() entity['PARTICLE_PARENT'].reset() entity['NODE'].detachNode() continue players_alive += 1 if entity['RIGHT_ANGLE_TURN'] == True: test_heading = square_heading(entity['HEADING']) entity['HEADING'] = test_heading # print test_heading if entity['RIGHT_ANGLE_TURN'] == True: if entity['TURN_LEFT'] and entity['LEFT_ARMED'] == True: entity["HEADING"] += 90 entity['LEFT_ARMED'] = False if entity['TURN_RIGHT'] and entity['RIGHT_ARMED'] == True: entity["HEADING"] -= 90 entity['RIGHT_ARMED'] = False else: if entity['TURN_LEFT']: entity["HEADING"] += configs.TURN_SPEED *dt*50 if entity['TURN_RIGHT']: entity["HEADING"] -= configs.TURN_SPEED *dt*50 pos = entity["NODE"].getPos() heading = entity["HEADING"] last_pos_x = pos.x last_pos_y = pos.z new_pos_x = last_pos_x + entity['SPEED'] *dt*50 * cos(heading* pi/180) new_pos_y = last_pos_y + entity['SPEED'] *dt*50 * sin(heading* pi/180) new_pos_x, new_pos_y = test_boundaries(self, entity_id, new_pos_x, new_pos_y) test_bonus(self, entity_id) dot_size = entity["TICKNESS"] entity["NODE"].setPos(new_pos_x,0,new_pos_y) entity["NODE"].setScale(dot_size*0.004) entity["PARTICLE"].emitter.setRadiateOrigin(Point3(0.05*cos(heading* pi/180), 0.0, 0.05*sin(heading* pi/180))) average_x_pos += new_pos_x average_y_pos += new_pos_y if min_y_pos > new_pos_y: min_y_pos = new_pos_y if max_y_pos < new_pos_y: max_y_pos = new_pos_y if min_x_pos > new_pos_x: min_x_pos = new_pos_x if max_x_pos < new_pos_x: max_x_pos = new_pos_x time = globalClock.getFrameTime() # print time if configs.LINE_GAP == True: if time % 5 < 4.5: if entity["CURRENT_LINE"] == None: new_line, line_vertex, line_node = start_new_line(self, new_pos_x, new_pos_y, entity['COLOR']) line_id = configs.ENTITY_ID configs.ENTITIES[configs.ENTITY_ID] = {'CATEGORY':'line', 'GEOM':new_line, 'VERTEX':line_vertex, 'NODE': line_node} configs.ENTITY_ID += 1 entity["CURRENT_LINE"] = line_id draw_line(entity_id, start=True) create_dots(entity_id, new_pos_x, new_pos_y, dot_size) draw_line(entity_id) else: if entity["CURRENT_LINE"] != None: draw_line(entity_id, end=True) entity["CURRENT_LINE"] = None else: if entity["CURRENT_LINE"] == None: new_line, line_vertex, line_node = start_new_line(self, new_pos_x, new_pos_y, entity['COLOR']) line_id = configs.ENTITY_ID configs.ENTITIES[configs.ENTITY_ID] = {'CATEGORY':'line', 'GEOM':new_line, 'VERTEX':line_vertex, 'NODE': line_node} configs.ENTITY_ID += 1 entity["CURRENT_LINE"] = line_id draw_line(entity_id, start=True) create_dots(entity_id, new_pos_x, new_pos_y, dot_size) draw_line(entity_id) if players_alive <= 1: player_win(self)
def stream(tracker, camera=0, server=0): """ @brief Captures video and runs tracking and moves robot accordingly @param tracker The BallTracker object to be used @param camera The camera number (0 is default) for getting frame data camera=1 is generally the first webcam plugged in """ ######## GENERAL PARAMETER SETUP ######## MOVE_DIST_THRESH = 20 # distance at which robot will stop moving SOL_DIST_THRESH = 150 # distance at which solenoid fires PACKET_DELAY = 1 # number of frames between sending data packets to pi OBJECT_RADIUS = 13 # opencv radius for circle detection AXIS_SAFETY_PERCENT = 0.05 # robot stops if within this % dist of axis edges packet_cnt = 0 tracker.radius = OBJECT_RADIUS ######## SERVER SETUP ######## motorcontroller_setup = False if server: # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Obtain server address by going to network settings and getting eth ip server_address = ('169.254.171.10',10000) # CHANGE THIS #server_address = ('localhost', 10000) # for local testing print 'starting up on %s port %s' % server_address sock.bind(server_address) sock.listen(1) connection, client_address = None, None while True: # Wait for a connection print 'waiting for a connection' connection, client_address = sock.accept() break ######## CV SETUP ######## # create video capture object for #cap = cv2.VideoCapture(camera) cap = WebcamVideoStream(camera).start() # WEBCAM #cap = cv2.VideoCapture('../media/goalie-test.mov') #cap = cv2.VideoCapture('../media/bounce.mp4') cv2.namedWindow(tracker.window_name) # create trajectory planner object # value of bounce determines # of bounces. 0 is default (no bounces) # bounce not currently working correctly planner = TrajectoryPlanner(frames=4, bounce=0) # create FPS object for frame rate tracking fps_timer = FPS(num_frames=20) while(True): # start fps timer fps_timer.start_iteration() ######## CAPTURE AND PROCESS FRAME ######## ret, frame = True, cap.read() # WEBCAM #ret, frame = cap.read() # for non-webcam testing if ret is False: print 'Frame not read' exit() # resize to 640x480, flip and blur frame,img_hsv = tracker.setup_frame(frame=frame, w=640,h=480, scale=1, blur_window=15) ######## TRACK OBJECTS ######## # use the HSV image to get Circle objects for robot and objects. # object_list is list of Circle objects found. # robot is single Circle for the robot position # robot_markers is 2-elem list of Circle objects for robot markers object_list = tracker.find_circles(img_hsv.copy(), tracker.track_colors, tracker.num_objects) robot, robot_markers = tracker.find_robot_system(img_hsv) walls = tracker.get_rails(img_hsv, robot_markers, colors.Yellow) planner.walls = walls # Get the line/distances between the robot markers # robot_axis is Line object between the robot axis markers # points is list of Point objects of closest intersection w/ robot axis # distanes is a list of distances of each point to the robot axis robot_axis = utils.line_between_circles(robot_markers) points, distances = utils.distance_from_line(object_list, robot_axis) planner.robot_axis = robot_axis ######## TRAJECTORY PLANNING ######## # get closest object and associated point, generate trajectory closest_obj_index = utils.min_index(distances) # index of min value closest_line = None closest_pt = None if closest_obj_index is not None: closest_obj = object_list[closest_obj_index] closest_pt = points[closest_obj_index] closest_line = utils.get_line(closest_obj, closest_pt) # only for viewing planner.add_point(closest_obj) # Get trajectory - list of elements for bounces, and final line traj # Last line intersects with robot axis traj_list = planner.get_trajectory_list(colors.Cyan) traj = planner.traj ######## SEND DATA TO CLIENT ######## if packet_cnt != PACKET_DELAY: packet_cnt = packet_cnt + 1 else: packet_cnt = 0 # reset packet counter # error checking to ensure will run properly if len(robot_markers) is not 2 or robot is None or closest_pt is None: pass elif server: try: if motorcontroller_setup is False: # send S packet for motorcontroller setup motorcontroller_setup = True ######## SETUP MOTORCONTROLLER ######## axis_pt1 = robot_markers[0].to_pt_string() axis_pt2 = robot_markers[1].to_pt_string() data = 'SM '+axis_pt1+' '+axis_pt2+' '+robot.to_pt_string() print data connection.sendall(data) # setup is done, send packet with movement data else: obj_robot_dist = utils.get_pt2pt_dist(robot, closest_obj) print 'dist: ' + str(obj_robot_dist) # USE FOR CALIBRATION ######## SOLENOID ACTIVATION CODE ######## # check if solenoid should fire if obj_robot_dist <= SOL_DIST_THRESH: # fire solenoid, dont move print 'activate solenoid!' # TODO SEND SOLENOID ACTIVATE ######## MOTOR CONTROL ######## # get safety parameters rob_ax1_dist = utils.get_pt2pt_dist(robot_markers[0],robot) rob_ax2_dist = utils.get_pt2pt_dist(robot_markers[1],robot) axis_length = utils.get_pt2pt_dist(robot_markers[0], robot_markers[1]) # ensure within safe bounds of motion relative to axis # if rob_ax1_dist/axis_length <= AXIS_SAFETY_PERCENT or \ # rob_ax2_dist/axis_length <= AXIS_SAFETY_PERCENT: # # in danger zone, kill motor movement # print 'INVALID ROBOT LOCATION: stopping motor' # data = 'KM' # connection.sendall(data) # if in danger zone near axis edge, move towards other edge if rob_ax1_dist/axis_length <= AXIS_SAFETY_PERCENT: print 'INVALID ROBOT LOCATION' data = 'MM '+robot.to_pt_string()+' '+robot_markers[1].to_pt_string() elif rob_ax2_dist/axis_length <= AXIS_SAFETY_PERCENT: print 'INVALID ROBOT LOCATION' data = 'MM '+robot.to_pt_string()+' '+robot_markers[0].to_pt_string() # check if robot should stop moving elif obj_robot_dist <= MOVE_DIST_THRESH: # obj close to robot # Send stop command, obj is close enough to motor to hit data = 'KM' print data connection.sendall(data) pass # Movement code else: # far enough so robot should move #### FOR TRAJECTORY ESTIMATION # if planner.traj is not None: # axis_intersect=shapes.Point(planner.traj.x2,planner.traj.y2) # # Clamp the point to send to the robot axis # traj_axis_pt = utils.clamp_point_to_line( # axis_intersect, robot_axis) # data = 'D '+robot.to_pt_string()+' '+traj_axis_pt.to_string() # connection.sendall(data) #### FOR CLOSEST POINT ON AXIS #### if closest_pt is not None and robot is not None: # if try to move more than length of axis, stop instead if utils.get_pt2pt_dist(robot,closest_pt) > axis_length: print 'TRYING TO MOVE OUT OF RANGE' data = 'KM' print data connection.sendall(data) else: data = 'MM ' + robot.to_pt_string() + ' ' + \ closest_pt.to_string() print data connection.sendall(data) except IOError: pass # don't send anything ######## ANNOTATE FRAME FOR VISUALIZATION ######## frame = gfx.draw_lines(img=frame, line_list=walls) frame = gfx.draw_robot_axis(img=frame, line=robot_axis) # draw axis line frame = gfx.draw_robot(frame, robot) # draw robot frame = gfx.draw_robot_markers(frame, robot_markers) # draw markers frame = gfx.draw_circles(frame, object_list) # draw objects # eventually won't need to print this one frame = gfx.draw_line(img=frame, line=closest_line) # closest obj>axis # draw full set of trajectories, including bounces #frame = gfx.draw_lines(img=frame, line_list=traj_list) #frame = gfx.draw_line(img=frame, line=traj) # for no bounces frame = gfx.draw_point(img=frame, pt=closest_pt) #frame=gfx.draw_line(frame,planner.debug_line) # for debug ######## FPS COUNTER ######## fps_timer.get_fps() fps_timer.display(frame) ######## DISPLAY FRAME ON SCREEN ######## cv2.imshow(tracker.window_name,frame) # quit by pressing q if cv2.waitKey(1) & 0xFF == ord('q'): break # release capture cap.stop() # WEBCAM #cap.release() # for testing w/o webcam cv2.destroyAllWindows()
def update_players(self, dt): if configs.GAME_ONGOING == 0: return players_alive = 0 average_x_pos = 0.0 average_y_pos = 0.0 min_x_pos = 0 max_x_pos = 0 min_y_pos = 0 max_y_pos = 0 for entity_id, entity in configs.ENTITIES.items(): if entity['CATEGORY'] == 'player': if configs.ARDUINO_MODE == True: value = configs.ARDUINO_BUTTONS_MAP[entity['PLAYER_NUMBER']][0] which_button = 'TURN_LEFT' if value == False: entity['LEFT_ARMED'] = True entity[which_button] = value value = configs.ARDUINO_BUTTONS_MAP[entity['PLAYER_NUMBER']][1] which_button = 'TURN_RIGHT' if value == False: entity['RIGHT_ARMED'] = True entity[which_button] = value if entity['ALIVE'] == False: entity['PARTICLE_PARENT'].disable() entity['PARTICLE_PARENT'].reset() entity['NODE'].detachNode() continue players_alive += 1 if entity['RIGHT_ANGLE_TURN'] == True: test_heading = square_heading(entity['HEADING']) entity['HEADING'] = test_heading # print test_heading if entity['RIGHT_ANGLE_TURN'] == True: if entity['TURN_LEFT'] and entity['LEFT_ARMED'] == True: entity["HEADING"] += 90 entity['LEFT_ARMED'] = False if entity['TURN_RIGHT'] and entity['RIGHT_ARMED'] == True: entity["HEADING"] -= 90 entity['RIGHT_ARMED'] = False else: if entity['TURN_LEFT']: entity["HEADING"] += configs.TURN_SPEED * dt * 50 if entity['TURN_RIGHT']: entity["HEADING"] -= configs.TURN_SPEED * dt * 50 pos = entity["NODE"].getPos() heading = entity["HEADING"] last_pos_x = pos.x last_pos_y = pos.z new_pos_x = last_pos_x + entity['SPEED'] * dt * 50 * cos( heading * pi / 180) new_pos_y = last_pos_y + entity['SPEED'] * dt * 50 * sin( heading * pi / 180) new_pos_x, new_pos_y = test_boundaries(self, entity_id, new_pos_x, new_pos_y) test_bonus(self, entity_id) dot_size = entity["TICKNESS"] entity["NODE"].setPos(new_pos_x, 0, new_pos_y) entity["NODE"].setScale(dot_size * 0.004) entity["PARTICLE"].emitter.setRadiateOrigin( Point3(0.05 * cos(heading * pi / 180), 0.0, 0.05 * sin(heading * pi / 180))) average_x_pos += new_pos_x average_y_pos += new_pos_y if min_y_pos > new_pos_y: min_y_pos = new_pos_y if max_y_pos < new_pos_y: max_y_pos = new_pos_y if min_x_pos > new_pos_x: min_x_pos = new_pos_x if max_x_pos < new_pos_x: max_x_pos = new_pos_x time = globalClock.getFrameTime() # print time if configs.LINE_GAP == True: if time % 5 < 4.5: if entity["CURRENT_LINE"] == None: new_line, line_vertex, line_node = start_new_line( self, new_pos_x, new_pos_y, entity['COLOR']) line_id = configs.ENTITY_ID configs.ENTITIES[configs.ENTITY_ID] = { 'CATEGORY': 'line', 'GEOM': new_line, 'VERTEX': line_vertex, 'NODE': line_node } configs.ENTITY_ID += 1 entity["CURRENT_LINE"] = line_id draw_line(entity_id, start=True) create_dots(entity_id, new_pos_x, new_pos_y, dot_size) draw_line(entity_id) else: if entity["CURRENT_LINE"] != None: draw_line(entity_id, end=True) entity["CURRENT_LINE"] = None else: if entity["CURRENT_LINE"] == None: new_line, line_vertex, line_node = start_new_line( self, new_pos_x, new_pos_y, entity['COLOR']) line_id = configs.ENTITY_ID configs.ENTITIES[configs.ENTITY_ID] = { 'CATEGORY': 'line', 'GEOM': new_line, 'VERTEX': line_vertex, 'NODE': line_node } configs.ENTITY_ID += 1 entity["CURRENT_LINE"] = line_id draw_line(entity_id, start=True) create_dots(entity_id, new_pos_x, new_pos_y, dot_size) draw_line(entity_id) if players_alive <= 1: player_win(self)
def main(): x = 500 y = 400 gameDisplay, clock = graphics.initialize_display(x, y) fps = 30 speed = 50 aging = 1. running = True nload = 0 world = World(x, y) population=[] max_fish = 3 for i in range(max_fish): name = str(i) age = 0 pos = [random.randint(0, x-1), random.randint(0, y-1)] angle = random.randint(0, 359) size = 5 #random.randint(5, 10) health = 1 hunger = 1 amplitude = 90 distance = 30 input = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 1, 0]).T output = np.array([0, 0]).T if not nload: layers, brain = neural_network.initialize((input.size, 3, output.size)) else: brain = Brain() brain.weights = load.synapses(nload) layers = [input.size, output.size] population.append( Fish(name, age, pos, angle, size, health, hunger, amplitude, distance, input, output, layers, brain)) foods=[] max_food=200 for i in range(max_food): pos = [random.randint(0, x-1), random.randint(0, y-1)] while not world.free_pos(pos): pos = [random.randint(0, x-1), random.randint(0, y-1)] world.insert(pos, 1) foods.append(pos) while running: # Analizes all users inputs/events for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Draws the background in white gameDisplay.fill(color.white) # Generate more food if necessary while len(foods) < max_food: pos = [random.randint(0, x-1), random.randint(0, y-1)] while not world.free_pos(pos): pos = [random.randint(0, x-1), random.randint(0, y-1)] world.insert(pos, 1) foods.append(pos) flag=False fittest=[[0 , 0], [0 , 0]] j=0 for i in range(len(population)): if population[j].health>0: f=neural_network.fitness(population[j]) if f>fittest[0][1]: if f<fittest[1][1]: fittest[0]=[population[j], f] elif fittest[0][1]>fittest[1][1]: fittest[1]=[population[j], f] else: fittest[0] = [population[j], f] elif f>fittest[1][1]: fittest[1] = [population[j], f] j=j+1 else: population.pop(j) flag=True if flag: flag2=0 if fittest[0]==[0, 0]: flag2=1 else: #print (fittest[0][0].name) #print (fittest[0][0].brain) #print ('\n') pass if fittest[1]==[0, 0]: if not flag: flag2=2 else: flag2=3 else: #print (fittest[1][0].name) #print (fittest[1][0].brain) #print ('\n') #print ('\n') pass while len(population) < max_fish: if len(population)==0: name = "1" else: name = str( int(population[-1].name) + 1 ) age = 0 pos = [random.randint(0, x - 1), random.randint(0, y - 1)] angle = random.randint(0, 359) size = 5 #random.randint(5, 10) health = 1 hunger = 1 amplitude = 90 distance = 30 input = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 1, 0]).T output = np.array([0, 0]).T layers = [input.size, output.size] if flag2==0: brain = neural_network.crossover(fittest[0][0].brain, fittest[1][0].brain) elif flag2==1: brain = neural_network.crossover(fittest[1][0].brain, neural_network.initialize((input.size, 3, output.size))[1]) elif flag2==2: brain = neural_network.crossover(fittest[0][0].brain, neural_network.initialize((input.size, 3, output.size))[1]) elif flag2==3: brain = neural_network.crossover(neural_network.initialize((input.size, 3, output.size))[1], neural_network.initialize((input.size, 3, output.size))[1]) #synapses = load.synapses(1) neural_network.mutation(brain, 0.80) population.append( Fish(name, age, pos, angle, size, health, hunger, amplitude, distance, input, output, layers, brain)) for food in foods: graphics.draw_food(gameDisplay, food, 1) for fish in population: graphics.draw_fish(gameDisplay, fish.pos, fish.size) fish.output = neural_network.calculate(fish.input, fish.brain) movement.next_pos(world, fish, 1.0/fps) interaction.vision2(world, fish) graphics.draw_line(gameDisplay, fish.pos, [fish.pos[0]+fish.distance*math.cos(math.radians(fish.angle-fish.amplitude/2.0)), fish.pos[1]+fish.distance*math.sin((math.radians(fish.angle-fish.amplitude/2.0)))]) graphics.draw_line(gameDisplay, fish.pos, [fish.pos[0]+fish.distance*math.cos(math.radians(fish.angle+fish.amplitude/2.0)), fish.pos[1]+fish.distance*math.sin((math.radians(fish.angle+fish.amplitude/2.0)))]) interaction.eat(world, fish, foods) fish.aging(aging/fps) # Updates display graphics.update(fps*speed, clock) #raw_input() # Terminates Pygame graphics.close_display() # Terminates Python quit()