def _create_worms(self): '''Create a worm''' worm = Worm(self) worm_width, worm_height = worm.rect.size for worm_num in range(3): worm = Worm(self) random_number_x = randint(worm_width, self.settings.screen_width - worm_width) worm.rect.x = random_number_x self.worms.add(worm)
class Simulation(object): def __init__(self, environmentSizeX, environmentSizeY): self.environment = Environment(environmentSizeX, environmentSizeY) self.worm = Worm(self.environment) self.clock = 0 def executeTimeStep(self): print 'Time Step: %s' % self.clock self.render_display() self.worm.live() if not self.worm.alive: # worm is dead. Return value to signal simulation is done return False self.clock = self.clock + 1 def render_display(self): self.environment.print_environment() self.worm.print_worm_state()
def add_worms(): if len(apples_collected) > 5: xpos = random.randint(0 + WORM_WIDTH, GWINDOW_WIDTH - WORM_WIDTH) w = Worm(xpos) worm = w.worm gw.add(worm) worms.append(worm)
def __init__(self, game, battle, worms_positions, color, ground): self.game = game self.worms = [] self.selected_worm = 0 self.selected_weapon = 0 self.battle = battle for e in worms_positions: self.worms.append(Worm(game, battle, e, color, ground)) self.weapons = [Weapon(self, self.battle, game)] * 4
def __init__(self, cell_size=9): self.cell_size = cell_size self.map = np.full((cell_size, cell_size), SERVO_MAX, np.uint16) self.worm = Worm(self.cell_size) self.gold = Gold(self.cell_size) #check object is overlapped if self.check_overlapped_object(): self.gold.set_position(self.get_empty_position())
def __init__(self, window, gamers): self.terrain = Terrain(1200) self.worms = [] self.gamers = gamers for i in range(len(gamers)): self.worms += [ Worm(300 + i * 200, self.terrain.get_level(300 + i * 200) + 5, gamers[i], i) ] self.rockets = [] self.window = window self.control = []
def main(): stage_url = 'http://192.168.226.211:8012/stages/' gc_html = Worm.get_html(stage_url+'stage/?id='+str(1)+'&attempt=0', True) gc_soup = BeautifulSoup(gc_html, 'html.parser') tables = gc_soup.find_all('table', 'table table-bordered table-striped table-condensed sortable') trs = tables[1].find_all('tr') gc_total = 0.0 for i in range(0, len(trs)): tds = trs[i].find_all('td') gc_str = tds[8].string.strip() if gc_str != '': gc_total += Util.format_second(gc_str) print gc_total
def __init__(self): self.const = constant() self.root = Tk() self.fr = Frame(self.root) self.root.geometry( str(self.const['field_width']) + 'x' + str(self.const['field_height'])) self.canvas = Canvas(self.root, bg='skyblue') self.canvas.pack(fill=BOTH, expand=1) self.field = Field(self.canvas) self.field_list = self.field.field_model() self.is_field = 0 self.worms = [] self.guns = [] self.clouds = [] self.bullets = [] self.boom = [] self.field.field_visual() self.wind = rnd(-3, 3) self.turn = 0 self.turn_end = 0 self.worms_number = self.const['worms_number'] self.is_shot = 0 self.event = 0 self.canvas.bind('<p>', self.is_turn_end) self.canvas.bind('<ButtonRelease-1>', self.shot_start) if len(self.const) < len(self.field.start_position): print('too many worms for this map') else: for num in range(self.const['worms_number']): self.worms.append( Worm( self.field.start_position[num][0], self.field.start_position[num][1], num, self.canvas, self, )) for num in range(self.worms_number): self.worms[num].player_number = num + 1 for num in range(self.const['clouds_number']): self.clouds.append(Cloud(num, self.canvas)) self.shooting_processing() self.walking_processing() self.choose_weapon()
def init_worm1(): # Set a random start point on the left side. start_x = random.randint(5, (GRID_WIDTH / 2) - 6) start_y = random.randint(5, GRID_HEIGHT - 6) worm_coordinates = [{ X: start_x, Y: start_y }, { X: start_x - 1, Y: start_y }, { X: start_x - 2, Y: start_y }] direction = RIGHT return Worm(Colors.DARK_BLUE, Colors.BLUE, direction, worm_coordinates)
def init_worm2(): # Set a random start point on the right side. start_x = random.randint((GRID_WIDTH / 2) + 5, GRID_WIDTH - 6) start_y = random.randint(5, GRID_HEIGHT - 6) worm_coordinates = [{ X: start_x, Y: start_y }, { X: start_x - 1, Y: start_y }, { X: start_x - 2, Y: start_y }] direction = RIGHT return Worm(Colors.DARK_GREEN, Colors.GREEN, direction, worm_coordinates)
def add_worm(pos: Vector2, team: int): w = Worm(pos) physic_objects_list.append(w) TeamManager.instance.add_worm(w, team)
def runGame(): global FINAL_SCORE_1, FINAL_SCORE_2 board = Board(CELLWIDTH, CELLHEIGHT) # Set a random start point. classicalWorm = Worm('Classical', CELLWIDTH, CELLHEIGHT, RIGHT) # Our Quantum Adversary! quantumWorm = Quantumworm('Quantum', CELLWIDTH, CELLHEIGHT, LEFT, QUBITS) for coordinates in classicalWorm.coordinates: board.activateCollision(coordinates['x'], coordinates['y']) for coordinates in quantumWorm.coordinates: board.activateCollision(coordinates['x'], coordinates['y'], coordinates['probability']) # Start the apple in a random place. apple = getRandomLocation() while True: # main game loop DISPLAYSURF.fill(BGCOLOR) drawGrid() # Key control for event in pygame.event.get(): # event handling loop if event.type == QUIT: terminate() """ Let's ignore keystrokes for the moment elif event.type == KEYDOWN: if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT: direction = LEFT elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT: direction = RIGHT elif (event.key == K_UP or event.key == K_w) and direction != DOWN: direction = UP elif (event.key == K_DOWN or event.key == K_s) and direction != UP: direction = DOWN elif event.key == K_ESCAPE: terminate() """ ## STEP 1: Check if there is any worm alive. If not, save scores and kill game loop if classicalWorm.alive == 0 and quantumWorm.alive == 0: return # game over else: FINAL_SCORE_1 = classicalWorm.getScore() FINAL_SCORE_2 = quantumWorm.getScore() ## STEP 2: Calculate directions for each snake (and each head for the quantum snake) if classicalWorm.alive == 1: wormDirection = classicalWorm.calculateRandomDirection( apple, board) if quantumWorm.alive == 1: qWormDirections = quantumWorm.calculateQuantumRandomDirection( apple, board) ## STEP 3: Grow the worm in the calculated direction if classicalWorm.alive == 1: newHead = classicalWorm.calculateNewMovement() classicalWorm.growWorm(newHead) if quantumWorm.alive == 1: print("------------------------") print("GROWING QUANTUM WORM ") total_heads = [] for head in quantumWorm.heads: qNewHeads = quantumWorm.calculateNewQuantumMovement( head, board) total_heads += qNewHeads quantumWorm.heads = total_heads quantumWorm.growQuantumWorm(board) ## And paint the worms drawWorm(classicalWorm.coordinates, 1) drawWorm(quantumWorm.coordinates, 2) ## STEP 4: Check if either of the worms has hit something. If so, kill it (or the quantum head if he has splitted) # check if the worm has hit something or the edge if (classicalWorm.alive == 1 and board.getStatus(classicalWorm.coordinates[0]['x'], classicalWorm.coordinates[0]['y']) > 0): print("--- Final scores: Classical him himself ---") classicalWorm.storeResults() FINAL_SCORE_1 = classicalWorm.getScore() classicalWorm.die(board) board.printGrid() for coordinate in classicalWorm.coordinates: board.deactivateCollision(coordinate['x'], coordinate['y']) classicalWorm.coordinates.clear() if classicalWorm.alive == 0 and quantumWorm.alive == 0: return # game over elif (len(classicalWorm.coordinates) > 0): board.activateCollision(classicalWorm.coordinates[0]['x'], classicalWorm.coordinates[0]['y']) for qWormHead in quantumWorm.heads: if (quantumWorm.alive == 1 and board.getStatus(qWormHead['x'], qWormHead['y']) >= 1): print("--- Final scores: Quantum hit himself with Head: ---") print(qWormHead) board.printGrid() quantumWorm.storeResults() FINAL_SCORE_2 = quantumWorm.getScore() if (len(quantumWorm.heads) <= 1): quantumWorm.die(board) for coordinate in quantumWorm.coordinates: board.deactivateCollision(coordinate['x'], coordinate['y']) quantumWorm.coordinates.clear() if classicalWorm.alive == 0 and quantumWorm.alive == 0: return # game over else: board.activateCollision(qWormHead['x'], qWormHead['y'], qWormHead['probability']) ## STEP 5: Check if any of the worms has eaten an apple. If so, increase score. Otherwise remove one square at the end (it does not grow) # check if worm has eaten an apple if (classicalWorm.alive == 1 and len(classicalWorm.coordinates) > 0): if classicalWorm.coordinates[0]['x'] == apple[ 'x'] and classicalWorm.coordinates[0]['y'] == apple['y']: # don't remove worm's tail segment apple = getRandomLocation() # set a new apple somewhere classicalWorm.setScore(classicalWorm.getScore() + 1) else: board.deactivateCollision(classicalWorm.coordinates[-1]['x'], classicalWorm.coordinates[-1]['y']) del classicalWorm.coordinates[-1] # remove worm's tail segment # check if Quantum worm has eaten an apple if (quantumWorm.alive == 1 and len(quantumWorm.coordinates) > 0): if quantumWorm.coordinates[0]['x'] == apple[ 'x'] and quantumWorm.coordinates[0]['y'] == apple['y']: # don't remove worm's tail segment apple = getRandomLocation() # set a new apple somewhere quantumWorm.setScore(quantumWorm.getScore() + 1) else: board.deactivateCollision(quantumWorm.coordinates[-1]['x'], quantumWorm.coordinates[-1]['y']) del quantumWorm.coordinates[-1] # remove worm's tail segment ## STEP 6: Draw the apple again, and update scores in the board. Add one frame. The show goes on! drawApple(apple) drawScore(classicalWorm.getScore(), 1) drawScore(quantumWorm.getScore(), 2) pygame.display.update() FPSCLOCK.tick(FPS)
import variables as var from pygame.math import Vector2 from map import * from enum import Enum import time from worm import Worm from team_manager import TeamManager map = Map("Map.bmp", "background.bmp") map.remove_circle(Vector2(1200, 500), 150) pygame.font.init() TeamManager() font = pygame.font.SysFont("comicsansms", 48) physic_objects_list = [Worm((100, 100)), Worm((1500, 1500), is_selected=True)] teams = [] def cameraScrolling(frame_time: float): if var.scroling_X_Inc and var.camera_vector.x + var.SCREEN_WIDTH < map.surface.get_width( ): var.camera_vector.x += var.SCROLLING_SPEED * frame_time if var.camera_vector.x + var.SCREEN_WIDTH > map.surface.get_width(): var.camera_vector.x = map.surface.get_width() - var.SCREEN_WIDTH if var.scroling_X_Dec and var.camera_vector.x > 0: var.camera_vector.x -= var.SCROLLING_SPEED * frame_time if var.camera_vector.x < 0: var.camera_vector.x = 0 if var.scroling_Y_Inc and var.camera_vector.y + var.SCREEN_HEIGHT < map.surface.get_height( ): var.camera_vector.y += var.SCROLLING_SPEED * frame_time
import cv2 import numpy as np from worm import Worm size = 512 pos = np.ones((2, )) * size // 2 angle_t = 0 angle = 0 worn = Worm() history = [pos.copy() for _ in range(50)] while True: action = worn.step(np.random.randint(12, 27)) if action == 1: pos += np.array([np.cos(angle), np.sin(angle)]) * worn.speed / 25 elif action == 2: pos -= np.array([np.cos(angle), np.sin(angle)]) * worn.speed / 25 elif action == 3: angle_t -= 0.5 elif action == 4: angle_t += 0.5 angle = angle_t history.append(pos.copy()) history.pop(0) frame = np.zeros((size, size, 3)) for pos in history[5:-5]: try: # frame[int(pos[0]), int(pos[1])] = 255
import time from Gridcontainer import GridContainer from Grid import Grid from turtle import Turtle from rock import Rock from worm import Worm from random import randint from AstarAlgoritmo import aStar tela = pygame.display.set_mode([600,480]); tela.fill([203, 237, 216]) container = GridContainer() grid = Grid() tartaruga = Turtle(25,25,(92 + 262),(27+262),(255,255,255)) rock = Rock(25,25,(92 + 262),(27+262),(255,255,255)) worm = Worm(25,25,(92 + 262),(27+262),(255,255,255)) grid.CriandoMatriz(); sprite_group = pygame.sprite.Group() sprite_group.add(tartaruga) container.Desenhacontainer(tela) grid.DesenhaGrid(tela) tartaruga.setPosicaoInicial(8,8,grid.rectMap) worm.setWormPosicao(grid.matriz,grid.rectMap,tela) rock.setRockPosicao(grid.matriz,grid.rectMap,tela)
def __init__(self, *args, **kwargs): super(MyApp, self).__init__(*args, **kwargs) self.worm = Worm()
def main(argv): FILE_DATA = "poker-hand-training-true.data" # FILE_DATA = "test.data" # FILE_DATA = "mini_test.data" # FILE_DATA = "tiny_mini_test.data" comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() iteration = 0 starting_luciferin = 0.0 luci_dec = 0.0 luci_inc = 0.0 worm_step = 0.0 radius = 0.0 t_start = MPI.Wtime() if rank == 0: if os.path.exists('salida.txt'): os.remove('salida.txt') luci_dec, luci_inc, worm_step, radius, starting_luciferin = get_command_line_values( argv) # menu for debugging, TODO: remove for kabré. # print("1) poker-hand-training-true.data") # print("2) test.data") # print("3) mini_test.data") # print("4) tiny_mini_test.data") # op = input("Data? ") # # if op == "1": # FILE_DATA = "poker-hand-training-true.data" # elif op == "2": # FILE_DATA = "test.data" # elif op == "3": # FILE_DATA = "mini_test.data" # elif op == "4": # FILE_DATA = "tiny_mini_test.data" list_data = load_data(FILE_DATA) else: list_data = None list_data = comm.bcast(list_data, root=0) starting_luciferin, luci_dec, luci_inc = comm.bcast( (starting_luciferin, luci_dec, luci_inc), root=0) worm_step, radius = comm.bcast((worm_step, radius), root=0) min_n = int(rank * (len(list_data) * 0.04) / size) max_n = int((rank + 1) * (len(list_data) * 0.04) / size) local_swarm = [] for index in range(min_n, max_n): worm = Worm(starting_luciferin, create_point()) local_swarm.append(worm) global_swarm = comm.gather(local_swarm, root=0) if rank == 0: global_swarm = [ worm for local_swarm in global_swarm for worm in local_swarm ] tree_data = KDTree(list_data) else: tree_data = None tree_data, global_swarm = comm.bcast((tree_data, global_swarm), root=0) # SET UP PHASE if rank == 0: swarm_chunk = get_swarm_chunks(global_swarm, size) else: swarm_chunk = None local_swarm = comm.scatter(swarm_chunk, root=0) local_swarm = set_covered_data(local_swarm, tree_data, list_data, radius) local_swarm = comm.gather(local_swarm, root=0) if rank == 0: global_swarm = [ worm for swarm_chunk in local_swarm for worm in swarm_chunk ] global_swarm = sort_swarm(clean_swarm(global_swarm), LEN) list_centroids = get_centroid_list(global_swarm, radius) sse = calculate_sum_squared_errors(global_swarm, list_centroids) terminal_condition = len(list_centroids) record_output('cantidad inicial de centroides: ' + str(terminal_condition)) else: list_centroids = None sse = 0.0 global_swarm = None terminal_condition = 0 terminal_condition = comm.bcast(terminal_condition, root=0) # while iteration < 1: while terminal_condition > 10: if rank == 0: max_internal_dist = calculate_max_internal_distance( global_swarm, list_centroids) inter_dist = calculate_inter_centroid_distance( global_swarm, list_centroids) else: max_internal_dist = 0.0 inter_dist = 0.0 list_centroids = comm.bcast(list_centroids, root=0) max_internal_dist = comm.bcast(max_internal_dist, root=0) inter_dist = comm.bcast(inter_dist, root=0) sse = comm.bcast(sse, root=0) if rank == 0: swarm_chunk = get_swarm_chunks(global_swarm, size) else: swarm_chunk = None local_swarm = comm.scatter(swarm_chunk, root=0) local_swarm = update_fitness(local_swarm, sse, max_internal_dist, len(list_data), inter_dist) local_swarm = update_luciferin(local_swarm, luci_dec, luci_inc) local_swarm = comm.gather(local_swarm, root=0) if rank == 0: global_swarm = [ worm for swarm_chunk in local_swarm for worm in swarm_chunk ] worm_positions = [worm.position for worm in global_swarm] tree_swarm = KDTree(worm_positions) else: tree_swarm = None global_swarm = None global_swarm = comm.bcast(global_swarm, root=0) tree_swarm = comm.bcast(tree_swarm, root=0) if rank == 0: swarm_chunk = get_swarm_chunks(global_swarm, size) else: swarm_chunk = None local_swarm = comm.scatter(swarm_chunk, root=0) local_swarm = set_worm_neighborhood(global_swarm, local_swarm, tree_swarm, list_centroids, radius) local_swarm = update_positions_and_data(global_swarm, local_swarm, list_data, worm_step, tree_data, radius) local_swarm = comm.gather(local_swarm, root=0) if rank == 0: global_swarm = [ worm for swarm_chunk in local_swarm for worm in swarm_chunk ] global_swarm = sort_swarm(clean_swarm(global_swarm), FIT) list_centroids = get_centroid_list(global_swarm, radius) sse = calculate_sum_squared_errors(global_swarm, list_centroids) iteration += 1 terminal_condition = len(list_centroids) # pdb.set_trace() record_output('i: ' + str(iteration) + ' cantidad de centroides: ' + str(len(list_centroids))) else: global_swarm = None list_centroids = None sse = None # iteration = comm.bcast(iteration, root=0) terminal_condition = comm.bcast(terminal_condition, root=0) t_final = MPI.Wtime() total_time = comm.reduce(t_final - t_start, op=MPI.MAX) if rank == 0: record_time(total_time) for centroid in list_centroids: print(centroid, ' : ', global_swarm[centroid].position) return
class MyApp(Cmd, object): '''My Console Application.''' def __init__(self, *args, **kwargs): super(MyApp, self).__init__(*args, **kwargs) self.worm = Worm() def _parse_sid(self, args): if len(args) == 0: i = None else: try: i = [int(arg) for arg in args.split(',')] return i except: return -1 print('Wrong type of input! Should be e.g. >> update 1') def do_lp(self, args): '''list posts''' try: args = lp_argp.parse_args(args.replace(',', ' ').split()) except: return n, isource, kw, ni = args.n, args.s, args.w, args.a posts = [] for i, p in enumerate( self.worm.get_posts(maxN=n, isource=isource, kw=kw, important=not ni)): print( str(i) + p.__str__() + '\n来源: %s' % self.worm.get_handler_bysid(p.source_id).source.name) def do_ls(self, args): '''Show Status.''' self.worm.print_stat() def do_listen(self, args): ''' Listen updates. args: a source id, or empty. ''' i = self._parse_sid(args) if i is not -1: info = self.worm.do('listen', isource=i) def do_nolisten(self, args): ''' Stop Listen update. args: a source id, or empty. ''' i = self._parse_sid(args) if i is not -1: info = self.worm.do('stop_listen', isource=i) def do_update(self, args): ''' Update all posts. args: a source id, or empty. ''' i = self._parse_sid(args) if i is not -1: info = self.worm.do('update', isource=i) def do_refresh(self, args): ''' Refresh all posts. args: a source id, or empty. ''' i = self._parse_sid(args) if i is not -1: info = self.worm.do('refresh', isource=i) def do_h(self, args): '''Help''' print(helptext) def do_quit(self, args): '''Quit''' raise SystemExit def do_EOF(self, args): '''Ctrl+D''' self.do_quit('') def do_debug(self, args): '''Quick Debug''' pdb.set_trace()
def create_worm(self): new_index = len(self.worms) self.worms += [ Worm(self.worm_colors[new_index], self.calc_new_free_position(), self.size_fields) ]
def restart_worm(self, i_worm): self.worms[i_worm] = Worm(self.worm_colors[i_worm], self.calc_new_free_position(), self.size_fields)
from worm import Worm import random max_generations = 120 max_worms = 100 generation = 0 average_fitness = 0 doolhof = [] fit_pool = [] total_fitness = 0 with open('doolhof1.txt', 'r') as file: for line in file: doolhof.append(line.rstrip()) doolhof_size = (len(doolhof[0]), len(doolhof)) worms = [Worm() for i in range(max_worms)] exit_found = False while not exit_found: os.system('clear') print( f"==== {generation} avg_fit:{average_fitness} total:{len(worms)} ====") for w in worms: w.tick() deaths = [] for row in range(0, doolhof_size[1]): line = doolhof[row] for col in range(0, len(doolhof[row])): for w in worms: if w.pos[0] == col and w.pos[1] == row: if doolhof[row][col] == '.':
def createWorms(k, luciferin, ratio, indexList2, totalWorms, minRange): wormList = [] counter = 0 wormIndex = minRange indexListAux = indexList2 intraDistances = [] while (counter < totalWorms): indexListAux = initSetUp() actualWorm = Worm(luciferin, wormIndex) actualWorm.getCards(ratio) # obtiene las cartas actualWorm.buildPermutations() # le hace todas las permutaciones permutations = actualWorm.getPermutations() wormIndexList, handPermutations = searchIndex(permutations, indexListAux) if (wormIndexList != []): actualWorm.setTotalHands(handPermutations, len(handPermutations)) intraDistance = equations.EQ8(actualWorm) actualWorm.setIntraDistance(intraDistance) wormList.append(actualWorm) wormIndex += 1 intraDistances.append(intraDistance) counter += 1 wormListAux = wormList.copy() return wormList, intraDistances, wormListAux
def __init__(self, environmentSizeX, environmentSizeY): self.environment = Environment(environmentSizeX, environmentSizeY) self.worm = Worm(self.environment) self.clock = 0
def init_swarm(self): worms = [] for i in range(0, 1000): worms.append(Worm(self)) return worms