def make_map(self, floors, blocks, pipes, goombas, invis, koopa): size = self.settings.rectSize for row in self.lines: for chars in row: # Floor if chars == "F": new_floor = Floor(self.screen, self.settings) new_floor.rect.x, new_floor.rect.y = self.xShift, self.yShift self.xShift += size floors.add(new_floor) # Breakable brick elif chars == "B": new_brick = Block(self.screen, self.settings, 4) new_brick.rect.x, new_brick.rect.y = self.xShift + size / 4, self.yShift + size / 4 self.xShift += size blocks.add(new_brick) # Unbreakable brick elif chars == "U": new_brick = Block(self.screen, self.settings, 0) new_brick.rect.x, new_brick.rect.y = self.xShift + size / 4, self.yShift + size / 4 self.xShift += size blocks.add(new_brick) # Pipe elif chars == "P": new_pipe = Pipe(self.screen, self.settings) new_pipe.rect.x, new_pipe.rect.y = self.xShift + size / 4, self.yShift + size / 4 self.xShift += size pipes.add(new_pipe) # Blank space elif chars == "X": self.xShift += size # ? block elif chars == "?": new_brick = Block(self.screen, self.settings, 6) new_brick.rect.x, new_brick.rect.y = self.xShift + size / 4, self.yShift + size / 4 self.xShift += size blocks.add(new_brick) # Mushroom blocks (look like ? blocks): elif chars == "M": new_brick = Block(self.screen, self.settings, 6, 0, 1) new_brick.rect.x, new_brick.rect.y = self.xShift + size / 4, self.yShift + size / 4 self.xShift += size blocks.add(new_brick) # Invisible walls elif chars == "I": new_invis = Block(self.screen, self.settings, 8, 0, 1) new_invis.rect.x, new_invis.rect.y = self.xShift + size / 4, self.yShift + size / 4 self.xShift += size invis.add(new_invis) # Goombas elif chars == "G": new_goomba = Goomba(self.screen, self.settings) new_goomba.rect.x, new_goomba.rect.y = self.xShift + size / 4, self.yShift - size / 10 self.xShift += size goombas.add(new_goomba) elif chars == "K": new_koopa = Koopa(self.screen, self.settings) new_koopa.rect.x, new_koopa.rect.y = self.xShift + size / 4, self.yShift - size / 10 self.xShift += size koopa.add(new_koopa) self.xShift = 0 self.yShift += size print("Done.")
def main_play(genomes, config): global Win, generation win = Win generation += 1 nets = [] birds = [] gen = [] for gen_id, genome in genomes: genome.fitness = 0 net = neat.nn.FeedForwardNetwork.create(genome, config) nets.append(net) birds.append(Bird(200, 320)) gen.append(genome) BGround = Back_ground() base = Base(FLOOR) pipes = [Pipe(650)] run = True clock = pygame.time.Clock() scores = 0 while run and len(birds) > 0: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() # bird.move() # if event.type == pygame.KEYDOWN and (event.key == pygame.K_SPACE or event.key == pygame.K_UP): # bird.jump() # bird.y -=90 pipe_index = 0 if len(birds) > 0: if len(pipes) > 1 and birds[ 0].x > pipes[0].x + pipes[0].pipe_top.get_width(): pipe_index = 1 for index, bird in enumerate(birds): gen[index].fitness += 0.1 bird.move() output = nets[birds.index(bird)].activate( (bird.y, abs(bird.y - pipes[pipe_index].height), abs(bird.y - pipes[pipe_index].bottom))) if output[0] > 0.5: bird.jump() BGround.move() base.move() disappear = [] addPipe = False for pipe in pipes: pipe.move() for bird in birds: if pipe.attack(bird): ip = birds.index(bird) gen[ip].fitness -= 1 nets.pop(ip) gen.pop(ip) birds.pop(ip) if pipe.x + pipe.pipe_top.get_width() < 0: disappear.append(pipe) if not pipe.passed and pipe.x < bird.x: pipe.passed = True addPipe = True if addPipe: scores += 1 for genome in gen: genome.fitness += 5 pipes.append(Pipe(500)) for pipe_remove in disappear: pipes.remove(pipe_remove) for bird in birds: if bird.y + bird.image.get_height() - 10 >= FLOOR or bird.y < 0: ip = birds.index(bird) nets.pop(ip) gen.pop(ip) birds.pop(ip) draw_win(Win, birds, pipes, base, BGround, scores, generation)
def test_українськогож(self): word = run_through_module(Text('українськогож')) self.assertEqual(word.get_text(), 'українськогож') self.assertEqual(word.get_phonotypes(), [ VOWEL, CONS, SONOR, VOWEL, VOWEL, SONOR, CONS, SPEC, CONS, VOWEL, CONS, VOWEL, CONS ]) def run_through_module(word): pin.acquire() pin.put(word) pin.notify() pin.release() pout.acquire() if pout.empty(): pout.wait() word = pout.get() pout.release() return word data = ConfigData(str(Path(__file__).parents[2]) + '\config\conf_uk_cyr.json') pin = Pipe(Queue(), Condition()) pout = Pipe(Queue(), Condition()) mod = PhonotypeModule([pin, pout], data) if __name__ == '__main__': unittest.main()
def play(daemon, firstStart=False, generation=1): counter = 0 if firstStart: population = gen.population else: population = gen.crossover() fitness = 0 deadcounter = 0 pipes = [Pipe(randint(120, 400))] if not daemon: screen = pg.display.set_mode(cs.SCREEN) clock = pg.time.Clock() pg.init() pg.font.init() font = pg.font.SysFont('Arial', 25) while True: if not daemon: clock.tick(60) screen.blit( pg.image.load('assets/background.png').convert(), (0, 0)) for event in pg.event.get(): if event.type == pg.KEYDOWN: gen.grade() pg.quit() sys.exit() fitness += 1 for i, p in enumerate(pipes): # what is this for??? if not daemon: p.draw(screen) p.update() if p.pipe_down.x < int((cs.WIDTH) / 3) and len(pipes) < 2: pipes.append(Pipe(randint(120, 400))) if p.pipe_down.x <= -cs.P_WIDTH - 10: del pipes[i] counter += 1 pipe = get_closest_pipe(pipes, population[0].rect.x) for player in population: if not player.dead: #if player not dead if detect_colision(pipe, player): player.dead = True player.fitness += 1000 * counter deadcounter += 1 if deadcounter >= len(population): print(generation) play(False, generation=generation + 1) player.update(pipe) player.fitness += 1 if not daemon: #draw bird player.draw(screen) if generation >= 500: gen.grade() break if not daemon: screen.blit( font.render( 'Birds left:{}'.format(str(len(population) - deadcounter)), -1, (255, 0, 0)), (200, 150)) screen.blit( font.render('Progress:{}'.format(str(counter)), -1, (255, 255, 0)), (200, 50)) screen.blit( font.render('Fitness:{}'.format(fitness), -1, (0, 0, 255)), (200, 250)) screen.blit( font.render('Generation:{}'.format(generation), -1, (0, 0, 0)), (200, 350)) pg.display.flip()
def start(self): self.player = Bird((width / 2, height / 2)) self.pipes = [] self.pipes.append(Pipe((width, 0)))
def __or__(self, mutator): from pipe import Pipe return Pipe(self, mutator)
def game(genomes, config): # Used to control the frame rate of the game FPSCLOCK = pygame.time.Clock() # Setup the game window with the given dimensions size = (SCREEN_WIDTH, SCREEN_HEIGHT) # Array used to store birds birds = [] # Variable keeps track of the dead birds # Once all the birds are dead the function game() # terminates and retruns the birds array num_dead_birds = 0 # A library specific way to loop through all genomes for genome_id, genome in genomes: # Create a network based on a given genome and the config file brain = neat.nn.FeedForwardNetwork.create(genome, config) # Create a bird which uses the previously created network bird = Bird(brain) # Add bird to the birds array birds.append(bird) # Array used to store the pipes in the game pipes = [] # Add initial pipe pipes.append(Pipe()) # The pyame drawable surface used to render objects screen = pygame.display.set_mode(size) # Execute the code below until all birds die while num_dead_birds != len(genomes): # Handle game events for event in pygame.event.get(): # Terminate game if escape key is pressed or window is closed if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() # Find pipe closest to bird closest = closest_pipe(birds, pipes) if closest != None: # Query for each bird for bird in birds: # Inputs to network: # bird.y - Y-location of a given bird # closest.x - X-location of the pipe closest to the bird # closest.upper_pipe_len - Y-location of the top of pipe gap # closest.bottom_pipe_y - Y-location of the bottom of pipe gap # Inputs are normalized accordingly brain_input = (bird.y / SCREEN_HEIGHT, closest.x / SCREEN_WIDTH, closest.upper_pipe_len / SCREEN_HEIGHT, closest.bottom_pipe_y / SCREEN_HEIGHT) # Query the netwrok of a given bird with the input output = bird.brain.activate(brain_input) # If output significant bird flaps up # otherwise it does nothing if output[0] >= 0.5: bird.flap() # Draw Background screen.fill(BLACK) # Draw pipe(s) for pipe in reversed(pipes): # Update pipe location and render pipe.update() pipe.show(screen) for bird in birds: # If bird collides with pipe it dies. # If the bird has reached the goal fitness it also dies # So that the game() function can terminate if bird.is_alive() and (pipe.has_collided(bird) or bird.fitness_score() > 10000): bird.die() num_dead_birds += 1 # If a pipe has exited the screen it get deleted from the array if pipe.x < -PIPE_WIDTH: pipes.remove(pipe) # Draw bird(s) for bird in birds: if bird.is_alive(): # Update bird location and render on screen bird.update() bird.show(screen) # Print additional information once a bird can play the game # for an extended period of time if Decimal(str(bird.fitness_score())) % Decimal('500.0') == Decimal('0.0'): print("A Genome has reached a fitness of %f" % bird.fitness_score()) # Once last pipe has reached a predefined position on the screen # a new pipe gets added to the array if pipes[-1].x == ADD_PIPE_POS: pipes.append(Pipe()) # Change frames pygame.display.flip() # Set frame rate for faster training FPSCLOCK.tick(FPS_TRAIN) # Returns the birds array to evolve networks based on # birds fitness return birds
def game(self, genomes, config): score = 0 nets = [] generation = [] birds = [] for _, gen in genomes: net = neat.nn.FeedForwardNetwork.create(gen, config) nets.append(net) birds.append(Bird(self.BIRD_IMGS, 100, 200)) gen.fitness = 0 generation.append(gen) # Game Objects bg = Bg(self.BG_IMG) floor = Floor(self.FLOOR_IMG, 530) pipes = [Pipe(pygame, self.PIPE_IMG, 500)] # Pygame Misc win = pygame.display.set_mode((self.WIN_WIDTH, self.WIN_HEIGHT)) clock = pygame.time.Clock() run = True while run: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() quit() pipe_ind = 0 if (len(birds)) > 0: if (len(pipes)) > 1 and birds[ 0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width(): pipe_ind = 1 else: self.running_generation += 1 break for x, bird in enumerate(birds): bird.move() generation[x].fitness += 0.1 outputs = nets[x].activate( (bird.y, abs(bird.y - pipes[pipe_ind].height), abs(bird.y - pipes[pipe_ind].bottom))) if outputs[0] > 0.5: bird.flap() # Animation add_pipe = False removed_pipe = [] for pipe in pipes: for x, bird in enumerate(birds): if pipe.collide(pygame, bird): generation[x].fitness -= 1 birds.pop(x) nets.pop(x) generation.pop(x) if not pipe.passed and pipe.x < bird.x: pipe.passed = True add_pipe = True if pipe.x + pipe.PIPE_TOP.get_width() < 0: removed_pipe.append(pipe) pipe.move() if add_pipe: score += 1 for g in generation: g.fitness += 5 pipes.append(Pipe(pygame, self.PIPE_IMG, 400)) for pipe in removed_pipe: pipes.remove(pipe) for x, bird in enumerate(birds): if bird.y + bird.img.get_height() >= 530 or bird.y < 0: birds.pop(x) nets.pop(x) generation.pop(x) floor.move() bg.move() self.draw_window(win, bg, birds, pipes, floor, score, self.running_generation) if score > 30: print('Target Acquired! (50++ Flappy Score)') with open('best_bird.pkl', 'wb') as file: pickle.dump(nets[0], file) break
import queue import threading import unittest from clean_module import CleanModule from config_data import ConfigData from end import End from pipe import Pipe from read_module import ReadModule from word import Text file_path = '../test_files/russian/test_russian.txt' encoding = 'utf-8-sig' data = ConfigData('../../configs/conf_ru_cyr.json') read_clean_pipe = Pipe(queue.Queue(), threading.Condition()) clean_out_pipe = Pipe(queue.Queue(), threading.Condition()) expected_result = [ Text('россия'), Text('официально'), Text('также'), Text('российская'), Text('федерация'), Text('государство'), Text('ввосточной'), Text('европе'), Text('центральной'), Text('и'), Text('северной'), Text('азии'),
def start(self): self.airpods = Airpods(self) self.pipe = Pipe(self) pass
space = random.randint(80, 100) ready = False yloc = random.randint(32, 500 - 32 - space) # we will determine this by a random call # size of the pipes LxW xsize = 100 ysize = random.randint(100, 325) # speed to draw a pipe, make pipe visual on screen pipespeed = 4.0 points = 0 lastKey = 0 bottomPipe = Pipe(1, xloc, yloc, space) topPipe = Pipe(0, xloc, bottomPipe.rect.y, space) allPipes.add( topPipe ) #IMPORTANT THIS GOES FIRST LOOOOL OR IT WONT CALCULATE IT CORRECTLY OMG allPipes.add(bottomPipe) pygame.draw.rect(screen, black, [0, 300, 400, 60]) # start game screen start = False while not start: pygame.display.flip() screen.blit(startscreen, [0, 0])
pygame.init() SCREEN = pygame.display.set_mode(CONSTANT.game_res) pygame.display.set_caption(CONSTANT.game_title) # sprites bird = Bird() x = bird.get_width() y = int(CONSTANT.canvas[0][1]/2) - bird.get_height()/2 # print('x = {}'.format(x)) bird.update(x, y) # define game area game_area = Game_Area() # pipe test pipe = Pipe(250) # set pipe x position pipe.set_x(game_area.get_width()-Pipe.get_width()*2) # set pipe on bottom of area pipe.set_y(game_area.get_height() - pipe.get_height()) # create State instance state = State(game_area=game_area,bird=bird,SCREEN=SCREEN,pipe=pipe) # create timer clock = pygame.time.Clock() # game loop: # - update game state # - events # - draw current game state SCREEN.fill(colours.BLACK)
def main(genomes, config): global GENERATION GENERATION += 1 nets = [] #nets control each bird ge = [] #genomes birds = [] #each bird for genome_id, genome in genomes: net = neat.nn.FeedForwardNetwork.create(genome, config) #generate a net nets.append(net) birds.append(Bird(230,350)) genome.fitness = 0 #starting fitness = 0 ge.append(genome) #bird = Bird(230,350) base = Base(img.WIN_HEIGHT - 70) pipes = [Pipe(700)] win = pygame.display.set_mode((img.WIN_WIDTH,img.WIN_HEIGHT)) clock = pygame.time.Clock() score = 0 running = True while running: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() quit() pipe_index = 0 # the pipe we should check for inputs for the birds, there can be more than 1 pipe on screen #if the birds pass the first pipe, they should consider the inputs of the second one instead if len(birds) > 0: if len(pipes) > 1 and birds[0].x > pipes[0].x + pipes[0].PIPE_TOP_IMG.get_width(): pipe_index = 1 else: running = False break for bird_index, bird in enumerate(birds): bird.move() ge[bird_index].fitness += 0.1 # 30 for each second (30 fps) output = nets[bird_index].activate((bird.y, abs(bird.y - pipes[pipe_index].height), abs(bird.y - pipes[pipe_index].height_bottom))) if output[0] > 0.5: # if the value of the output neuron is > 0.5 we jump bird.jump() pipes_to_remove = [] add_pipe = False # should we add a new pipe to the game? for pipe in pipes: for bird_index, bird in enumerate(birds): if pipe.collide(bird): ge[bird_index].fitness -= 1 # if a bird hits a pipe, reduce fitness by 1 birds.pop(bird_index) nets.pop(bird_index) ge.pop(bird_index) # ???? if not pipe.completed and pipe.x < bird.x: pipe.completed = True add_pipe = True if pipe.x + pipe.PIPE_TOP_IMG.get_width() < 0: pipes_to_remove.append(pipe) pipe.move() if add_pipe: score += 1 for genome in ge: genome.fitness += 5 pipes.append(Pipe(700)) for pipe in pipes_to_remove: pipes.remove(pipe) for bird_index, bird in enumerate(birds): #print(bird.y + bird.img.get_height(), img.WIN_HEIGHT - 75) if bird.y + bird.img.get_height() >= (img.WIN_HEIGHT - 75): #print("bird hit the bottom") birds.pop(bird_index) nets.pop(bird_index) ge.pop(bird_index) elif (bird.y <= 0 ): #print("bird hit the top") birds.pop(bird_index) nets.pop(bird_index) ge.pop(bird_index) base.move() draw_window(win,birds,pipes,base,score, GENERATION)
# define x and y x = 350 y = 250 x_speed = 0 y_speed = 0 ground = 495 xloc = 700 yloc = 0 xsize = 100 ysize = randint(200, 350) space = 200 pipespeed = 2.5 points = 0 lastKey = 0 allPipes.add(Pipe(0, xloc, yloc + ysize + space)) allPipes.add(Pipe(1, xloc, yloc)) pygame.display.flip() def gameOver(): # check if the ball goes too far down font = pygame.font.SysFont("comicsansms.tff", 20) text = font.render("Game over", True, black) screen.blit(text, [200, 350]) pygame.display.flip() pygame.time.wait(6000) def score(points): font = pygame.font.SysFont("comicsansms.tff", 20)
for i in range(int(NUM_BIRDS / 4)): birds.append(Bird()) # set up clock FPS = 300 # frames per second counter = 0 # loop until user clicks the close button done = False while not done: counter += 1 if not pipes: pipes.append(Pipe()) if len(pipes) == 1: if pipes[0].x < width * pipeSpacing: pipes.append(Pipe()) if not birds: restart() for bird in birds: bird.think(pipes) if bird.score > bestScore: bestScore = bird.score bestBird = bird bestBirds.append(bird) bestBirds.sort(key=Bird.get_score, reverse=True) bestBirds = bestBirds[:10] # only keep best 10 (PG) savedBirds.append(bird) bird.show()
from datetime import datetime from pipe import Pipe def calc(list_): return [x * 2 for x in list_] class callable_calc(object): def __call__(self, list_): return calc(list_) decorated_callable = Pipe(callable_calc()) class MyDescriptor(object): def __get__(self, instance, owner): return lambda list_: calc(list_) class C(object): @Pipe def calc(self, list_): return calc(list_) @Pipe @classmethod def class_calc(cls, list_):
def summarize(PDFfile): pipe = Pipe() # converts PDFfile from upload and returns the text(string) text = pipe.convert(PDFfile) return text
def test_simple(self): self.assertEqual([2, 4, 6], [1, 2, 3] | Pipe(calc))
def __init__(self, blk_pipe, api_pipe, protocol_version, disable_api, disable_blk): gr.basic_block.__init__(self, name="protocol_sink", in_sig=[], out_sig=[]) # Validate parameters if (protocol_version < 1 or protocol_version > 2): raise ValueError("Protocol version should be either 1 or 2") # Input parameters self.protocol_version = protocol_version self.disable_api = disable_api self.disable_blk = disable_blk # Open named pipes if (not disable_blk): self.blk_pipe = Pipe(blk_pipe) if ((self.protocol_version > 1) and (not disable_api)): self.api_pipe = Pipe(api_pipe) else: self.api_pipe = None # Buffer to accumulate incoming API data (from API Blocksat packets) # until the entire user-transmitted data is accumulated self.api_buffer = b'' # Stats self.blk_data_cnt = 0 self.api_data_cnt = 0 self.blk_byte_rate = RateAvg( 5) # Compute over 5 secs. sample ~ once/sec self.api_byte_rate = RateAvg( 5) # Compute over 5 secs, sample ~ once/sec self.stats_period = 1 self.next_stats = time.time() # Print control self.print_period = 10 self.next_print = time.time() + 2 * self.print_period self.last_api_warning = 0 self.last_blk_warning = 0 self.api_ovflw_print_pending = False self.blk_ovflw_print_pending = False # Initialize buffers to store output API and blocks packets self.api_data_buffer = list() self.blk_data_buffer = list() self.api_data_buffer_data_cnt = 0 self.blk_data_buffer_data_cnt = 0 # Count the amount of data that has been deleted from the data buffer # and not yet informed via a console log self.api_data_buffer_del_cnt = 0 self.blk_data_buffer_del_cnt = 0 # Define threads to consume API and blocks data separately self.api_consumer_en = True self.blk_consumer_en = True self.api_data_available = Event() self.blk_data_available = Event() self.api_data_buffer_lock = Lock() self.blk_data_buffer_lock = Lock() api_consumer = Thread(target=self.api_consumer) blk_consumer = Thread(target=self.blk_consumer) api_consumer.daemon = True blk_consumer.daemon = True # Start threads if (not disable_api): api_consumer.start() if (not disable_blk): blk_consumer.start() # Register the message port self.message_port_register_in(pmt.intern('async_pdu')) self.set_msg_handler(pmt.intern('async_pdu'), self.handle_msg)
def main(genomes, config): nets = [] ge = [] birds = [] for _, g in genomes: net = neat.nn.FeedForwardNetwork.create(g, config) nets.append(net) birds.append(Bird(230, 350)) g.fitness = 0 ge.append(g) run = True win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) pygame.display.set_caption("Flappia !") clock = pygame.time.Clock() bird = Bird(230, 350) base = Base(730) pipes = [Pipe(600)] score = 0 with open("best_score.json") as out_file: data = json.load(out_file) high_score = str(data["bestscore"]) while (run): clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False myData = {} myData["bestscore"] = int(high_score) with open("best_score.json", "w") as json_file: json.dump(myData, json_file) pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: bird.jump() pipe_ind = 0 if len(birds) > 0: if (len(pipes) > 1) and ( birds[0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width()): pipe_ind = 1 else: run = False break for x, bird in enumerate(birds): bird.move() ge[x].fitness = ge[x].fitness + 0.1 output = nets[x].activate( (bird.y, abs(bird.y - pipes[pipe_ind].height), abs(bird.y - pipes[pipe_ind].bottom))) if output[0] > 0.5: bird.jump() bird.move() add_pipe = False rem = [] for x, bird in enumerate(birds): if (bird.y + bird.img.get_height() >= 700) or bird.y < 0: birds.pop(x) nets.pop(x) ge.pop(x) if int(score) > int(high_score): high_score = score main(genomes, config) for pipe in pipes: for x, bird in enumerate(birds): if pipe.collide(bird): ge[x].fitness -= 1 birds.pop(x) nets.pop(x) ge.pop(x) if int(score) > int(high_score): high_score = score main(genomes, config) if (not (pipe.passed) and (pipe.x < bird.x)): pipe.passed = True add_pipe = True if (pipe.x + pipe.PIPE_TOP.get_width() < 0): rem.append(pipe) pipe.move() if (add_pipe): score = score + 1 for g in ge: g.fitness += 5 pipes.append(Pipe(600)) for r in rem: pipes.remove(r) base.move() draw_window(win, bird, base, pipes, score, high_score)
for i in filter(lambda i: i[0].alive, birds): bird, gfx = i x,y = bird.getPos() pipe = obstacles[0] px, py, gap = pipe.getPos() if x == px: bird.score += 1 if (x > px and x < px+gap) and (y > py+gap or y < py): bird.die() canvas.delete(gfx) pipes = [] obstacles = [] obstacles.append(Pipe(500, HEIGHT/2, GAP)) main = Tk() main.resizable(width = False, height = False) main.title("Flappy Bird") main.geometry( '{}x{}'.format(WIDTH, HEIGHT) ) canvas = Canvas(main, width=WIDTH, height=HEIGHT) canvas.pack() birds = [] for i in range(1): bird = Bird(100, randint(50, 650)) x, y = bird.getPos() img = PhotoImage(file="images/bird.gif") y = y+random()*HEIGHT
def main(genomes, config): # bird = Bird(230, 350) global GENERATION nets = [] ge = [] birds = [] GENERATION += 1 for _, genome in genomes: net = neat.nn.FeedForwardNetwork.create(genome, config) nets.append(net) birds.append(Bird(230, 350)) genome.fitness = 0 ge.append(genome) base = Base(730) pipes = [Pipe(600)] win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) clock = pygame.time.Clock() score = 0 run = True while run: clock.tick(30) # Increase to 60 if frame rate of game is low for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() quit() pipe_ind = 0 if len(birds) > 0: if len(pipes) > 1 and birds[0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width(): pipe_ind = 1 else: run = False break for x, bird in enumerate(birds): bird.move() ge[x].fitness += 0.1 output = nets[x].activate((bird.y, abs(bird.y - pipes[pipe_ind].height), \ abs(bird.y - pipes[pipe_ind].bottom))) # print(output), output will be between -1 and 1 for given tanh activation function if output[0] > 0.5: bird.jump() # bird.move() add_pipe = False rem = [] for pipe in pipes: for x, bird in enumerate(birds): if pipe.collide(bird): birds.pop(x) nets.pop(x) ge.pop(x) if not pipe.passed and (pipe.x + pipe.get_width()) < bird.x : pipe.passed = True add_pipe = True if pipe.x + pipe.PIPE_TOP.get_width() < 0: rem.append(pipe) pipe.move() # Score/ Add new pipe if add_pipe: score += 1 for g in ge: g.fitness += 5 pipes.append(Pipe(500)) # Remove offscreen pipes for r in rem: pipes.remove(r) # Collision with ground at 730 or ceiling at 0 for x, bird in enumerate(birds): if bird.y + bird.img.get_height() > 730 or bird.y < 0: birds.pop(x) nets.pop(x) ge.pop(x) base.move() draw_window(win, birds, pipes, base, score, GENERATION)
def main(genomes, config): global gen nets = [] ge = [] birds = [] for g in genomes: net = neat.nn.FeedForwardNetwork.create(g, config) nets.append(net) birds.append(Bird(230, 350)) g.fitness = 0 ge.append(g) base = Base(730) pipes = [Pipe(700)] win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) clock = pygame.time.Clock() score = 0 run = True while run: clock.tick(50) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() quit() if score > 100: run = False break pipe_ind = 0 if len(birds) > 0: if len(pipes) > 1 and birds[ 0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width(): pipe_ind = 1 else: run = False break for x, bird in enumerate(birds): bird.move() ge[x].fitness += 0.1 output = nets[x].activate( (bird.y, abs(bird.y - pipes[pipe_ind].height), abs(bird.y - pipes[pipe_ind].bottom))) if output[0] > 0.5: bird.jump() rem = [] add_pipe = False for pipe in pipes: for x, bird in enumerate(birds): if pipe.collide(bird): ge[x].fitness -= 1 birds.pop(x) nets.pop(x) ge.pop(x) if not pipe.passed and pipe.x < bird.x: pipe.passed = True add_pipe = True if pipe.x + pipe.PIPE_TOP.get_width() < 0: rem.append(pipe) pipe.move() if add_pipe: score += 1 for genome in ge: genome.fitness += 5 pipes.append(Pipe(600)) for r in rem: pipes.remove(r) for x, bird in enumerate(birds): if bird.y + bird.img.get_height() >= 730 or bird.y < 0: birds.pop(x) nets.pop(x) ge.pop(x) base.move() draw_window(win, birds, pipes, base, score, gen) gen += 1
import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from pipe import Pipe # main """enter flow, diameter, length, us invert, ds invert, Ks, kinematic viscocity""" print("Test Run 1") pipe1 = Pipe() pipe1.setValues(0.375, 0.9, 87.385, 15.456, 15.338, 0.006, 1.141e-06) pipe1.calculate() print(pipe1.crit_depth) print(pipe1.norm_depth) x = 0 for i in pipe1.chainage: print("Length %.1f" % i, "Energy %.3f" % pipe1.energy[x], "Water %.3f" % pipe1.water[x], "Head %.3f" % pipe1.head[x]) x += 1
def generate_floor(screen, settings, map_group, floor_group, pipe_group): for i in range(0, 69): # level 15 and 16 f = Floor(screen, settings) f.rect.top = 13 * settings.floor_height f.rect.left = i * settings.floor_width fl = Floor(screen, settings) fl.rect.top = 14 * settings.floor_height fl.rect.left = i * settings.floor_width # print('floor top: ' + str(f.rect.top)) # print('floor x,y: ' + str(f.rect.x) + ', ' + str(f.rect.y)) f.add(map_group, floor_group) fl.add(map_group, floor_group) for i in range(71, 86): f = Floor(screen, settings) f.rect.top = 13 * settings.floor_height f.rect.left = i * settings.floor_width fl = Floor(screen, settings) fl.rect.top = 14 * settings.floor_height fl.rect.left = i * settings.floor_width f.add(map_group, floor_group) fl.add(map_group, floor_group) for i in range(89, 153): f = Floor(screen, settings) f.rect.top = 13 * settings.floor_height f.rect.left = i * settings.floor_width fl = Floor(screen, settings) fl.rect.top = 14 * settings.floor_height fl.rect.left = i * settings.floor_width f.add(map_group, floor_group) fl.add(map_group, floor_group) for i in range(155, 224): f = Floor(screen, settings) f.rect.top = 13 * settings.floor_height f.rect.left = i * settings.floor_width fl = Floor(screen, settings) fl.rect.top = 14 * settings.floor_height fl.rect.left = i * settings.floor_width f.add(map_group, floor_group) fl.add(map_group, floor_group) # Stairs stairs_arr = [] # 135-138,12 block for i in range(134, 138): b = Block(screen, settings, is_stairs=True) b.set_position(12, i) stairs_arr.append(b) # 136-138,11 block for i in range(135, 138): b = Block(screen, settings, is_stairs=True) b.set_position(11, i) stairs_arr.append(b) # 137,10 block # 138,10 block for i in range(136, 138): b = Block(screen, settings, is_stairs=True) b.set_position(10, i) stairs_arr.append(b) # 138,9 block b = Block(screen, settings, is_stairs=True) b.set_position(9, 137) stairs_arr.append(b) # 141-144,12 block for i in range(140, 144): b = Block(screen, settings, is_stairs=True) b.set_position(12, i) stairs_arr.append(b) # 141-143,11 block for i in range(140, 143): b = Block(screen, settings, is_stairs=True) b.set_position(11, i) stairs_arr.append(b) # 141-142,10 block for i in range(140, 142): b = Block(screen, settings, is_stairs=True) b.set_position(10, i) stairs_arr.append(b) # 141,9 block b = Block(screen, settings, is_stairs=True) b.set_position(9, 140) stairs_arr.append(b) # 149,12 block b = Block(screen, settings, is_stairs=True) b.set_position(12, 148) stairs_arr.append(b) # 150,12 block # 150,11 block for i in range(11, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 149) stairs_arr.append(b) # 151,12 block # 151,11 block # 151,10 block for i in range(10, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 150) stairs_arr.append(b) # 152,12 block # 152,11 block # 152,10 block # 152,9 block for i in range(9, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 151) stairs_arr.append(b) # 153,12 block # 153,11 block # 153,10 block # 153,9 block for i in range(9, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 152) stairs_arr.append(b) # 156,12 block # 156,11 block # 156,10 block # 156,9 block for i in range(9, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 155) stairs_arr.append(b) # 157,12 block # 157,11 block # 157,10 block for i in range(10, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 156) stairs_arr.append(b) # 158,12 block # 158,11 block for i in range(11, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 157) stairs_arr.append(b) # 159,12 block b = Block(screen, settings, is_stairs=True) b.set_position(12, 158) stairs_arr.append(b) # 182,12 block b = Block(screen, settings, is_stairs=True) b.set_position(12, 181) stairs_arr.append(b) # 183,12 block # 183,11 block for i in range(11, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 182) stairs_arr.append(b) # 184,12 block # 184,11 block # 184,10 block for i in range(10, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 183) stairs_arr.append(b) # 185,12 block # 185,11 block # 185,10 block # 185,9 block for i in range(9, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 184) stairs_arr.append(b) # 186,12 block # 186,11 block # 186,10 block # 186,9 block # 186,8 block for i in range(8, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 185) stairs_arr.append(b) # 187,12 block # 187,11 block # 187,10 block # 187,9 block # 187,8 block # 187,7 block for i in range(7, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 186) stairs_arr.append(b) # 188,12 block # 188,11 block # 188,10 block # 188,9 block # 188,8 block # 188,7 block # 188,6 block for i in range(6, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 187) stairs_arr.append(b) # 189,12 block # 189,11 block # 189,10 block # 189,9 block # 189,8 block # 189,7 block # 189,6 block # 189,5 block for i in range(5, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 188) stairs_arr.append(b) # 190,12 block # 190,11 block # 190,10 block # 190,9 block # 190,8 block # 190,7 block # 190,6 block # 190,5 block for i in range(5, 13): b = Block(screen, settings, is_stairs=True) b.set_position(i, 189) stairs_arr.append(b) # # 199,12 block b = Block(screen, settings, is_stairs=True) b.set_position(12, 198) stairs_arr.append(b) for s in stairs_arr: s.add(map_group, floor_group) # Overworld Pipes p = Pipe(screen, settings) p.set_position(11, 28) p.add(map_group, pipe_group) print('pipe x,y' + str(p.rect.x) + ', ' + str(p.rect.y)) p = Pipe(screen, settings, height_factor=3) p.set_position(10, 38) p.add(map_group, pipe_group) p = Pipe(screen, settings, height_factor=4) p.set_position(9, 46) p.add(map_group, pipe_group) # 58,12 pipe p = Pipe(screen, settings, height_factor=4) p.set_position(9, 57) p.add(map_group, pipe_group) p = Pipe(screen, settings) p.set_position(11, 163) p.add(map_group, pipe_group) p = Pipe(screen, settings) p.set_position(11, 179) p.add(map_group, pipe_group)
def train_model(genomes, config): global generation nets = [] ge = [] birds = [] generation += 1 for _, g in genomes: net = neat.nn.FeedForwardNetwork.create(g, config) nets.append(net) birds.append(Bird(200, 200)) g.fitness = 0 ge.append(g) window = pygame.display.set_mode((WIDTH, HEIGHT)) base = Ground(HEIGHT - ground.GROUND_IMG.get_height() / 2) pipes = [Pipe(700)] running = True simulation_speed = 30 clock = pygame.time.Clock() add_pipe = False score = 0 while running: clock.tick(simulation_speed) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: player.jump() pipe_index = 0 if len(birds) > 0: if len(pipes) > 1 and birds[ 0].x > pipes[0].x + pipes[0].img.get_width(): pipe_index = 1 else: running = False break #end generation base.update() for index, bird in enumerate(birds): bird.update() ge[index].fitness += 0.3 output = nets[index].activate( (bird.y, abs(bird.y - pipes[pipe_index].height), abs(bird.y - pipes[pipe_index].bottom))) if output[0] > 0.5: bird.jump() for pipe in pipes: for index, bird in enumerate(birds): if pipe.collide(bird): ge[index].fitness = -0.5 birds.pop(index) nets.pop(index) ge.pop(index) if not pipe.passed and pipe.x < bird.x: pipe.passed = True add_pipe = True if pipe.x + pipe.img.get_width() < 0: pipes.remove(pipe) if add_pipe: score += 1 for g in ge: g.fitness += 5 pipes.append(Pipe(700)) add_pipe = False pipe.update() for index, bird in enumerate(birds): if bird.y + bird.img.get_height() >= HEIGHT - 100 or bird.y < 0: bird.y = HEIGHT - bird.img.get_height() - 100 birds.pop(index) nets.pop(index) ge.pop(index) draw(window, birds, base, pipes, score, generation)
def main(self, genomes, config): """mock main game""" global GEN GEN += 1 nets = [] genome = [] birds = [] for _, gen in genomes: net = neat.nn.FeedForwardNetwork.create(gen, config) nets.append(net) birds.append(Bird(230, 350)) gen.fitness = 0 genome.append(gen) base = Base(730) pipes = [Pipe(600)] win = pygame.display.set_mode( (self.settings.win_width, self.settings.win_height)) clock = pygame.time.Clock() score = 0 run = True while run: clock.tick(100000) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() sys.exit() pipe_idx = 0 if len(birds) > 0: if len(pipes) > 1 \ and birds[0].x_coord > pipes[0].x_coord + pipes[0].pipe_top.get_width(): pipe_idx = 1 else: run = False break # TODO: get rid of that uglyness for idx, bird in enumerate(birds): bird.move() genome[idx].fitness += 0.1 output = nets[idx].activate( (bird.y_coord, abs(bird.y_coord - pipes[pipe_idx].top), abs(bird.y_coord - pipes[pipe_idx].bottom))) if output[0] > 0.5: bird.jump() remove_pipe = [] # TODO : get that in a function add_pipe = False for pipe in pipes: for idx, bird in enumerate(birds): if pipe.collide(bird): genome[idx].fitness -= 1 birds.pop(idx) nets.pop(idx) genome.pop(idx) if not pipe.passed and pipe.x_coord < bird.x_coord: pipe.passed = True add_pipe = True if pipe.x_coord + pipe.pipe_top.get_width() < 0: remove_pipe.append(pipe) pipe.move() if add_pipe: score += 1 for gen in genome: gen.fitness += 5 pipes.append(Pipe(600)) for trash in remove_pipe: pipes.remove(trash) for idx, bird in enumerate(birds): if bird.y_coord + bird.img.get_height() >= 730 \ or bird.y_coord < 0: # FIXME: Variable the 730 birds.pop(idx) nets.pop(idx) genome.pop(idx) base.move() self.draw_window(win, birds, pipes, base, score, GEN)
while not pout.empty(): word = pout.get() self.assertEqual(word.get_syllables(), syllables[index]) self.assertEqual(word.get_lengths(), lengths[index]) index += 1 self.assertEqual(mod_count.lengths_of_syllables, lengths_map) self.assertEqual(mod_count.frequencies_of_syllables, frequency_map) def run_through_module(word, mod): pin = mod.get_pipes()[0] pin.acquire() pin.put(word) pin.notify() pin.release() pin = Pipe(Queue(), Condition()) pipe_syllabify_count = Pipe(Queue(), Condition()) pout = Pipe(Queue(), Condition()) cd = ConfigData("conf_cs_lat.json") mod_syll = SyllabifyModule([pin, pipe_syllabify_count]) mod_count = CountModule([pipe_syllabify_count, pout], cd, "blabla") if __name__ == '__main__': unittest.main()
def test_Should_ReturnMappedVlaues_When_MapApplied(self): input = [7, 8, 9] func = lambda x: -x pipe = Pipe(input).map(func) result = [x for x in pipe] self.assertEqual([-7, -8, -9], result)
def add_column(self, num): # Create a new column of bricks if num in self.gapcols: # If this is a gap column (canyon) pass # Do nothing else: new_column = Group() if len(self.brick_columns) == 0: x = 0 else: x = 32 * num for i in range(2): brick_temp = Brick(self.screen) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset + (32 * i) new_column.add(brick_temp) if num in self.b3cols: brick_temp = BreakBrick(self.screen) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 128 new_column.add(brick_temp) if num in self.q4cols: brick_temp = QBrick(self.screen) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 128 new_column.add(brick_temp) if num in self.q7cols: brick_temp = QBrick(self.screen) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 32 * 7 new_column.add(brick_temp) if num in self.b7cols: brick_temp = BreakBrick(self.screen) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 32 * 7 new_column.add(brick_temp) if num in self.pipe3cols: brick_temp = Pipe(self.screen, 3) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 128 new_column.add(brick_temp) if num in self.pipe1cols: brick_temp = Pipe(self.screen, 1) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 64 new_column.add(brick_temp) if num in self.pipe2cols: brick_temp = Pipe(self.screen, 2) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 96 new_column.add(brick_temp) if num in self.pipe3cols: brick_temp = Pipe(self.screen, 3) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 128 new_column.add(brick_temp) if num in self.stair1: brick_temp = StairBrick(self.screen, 1) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 32 new_column.add(brick_temp) if num in self.stair2: brick_temp = StairBrick(self.screen, 2) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 64 new_column.add(brick_temp) if num in self.stair3: brick_temp = StairBrick(self.screen, 3) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 96 new_column.add(brick_temp) if num in self.stair4: brick_temp = StairBrick(self.screen, 4) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 128 new_column.add(brick_temp) if num in self.stair5: brick_temp = StairBrick(self.screen, 5) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 160 new_column.add(brick_temp) if num in self.stair6: brick_temp = StairBrick(self.screen, 6) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 192 new_column.add(brick_temp) if num in self.stair7: brick_temp = StairBrick(self.screen, 7) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 224 new_column.add(brick_temp) if num in self.stair8: brick_temp = StairBrick(self.screen, 8) brick_temp.rect.x = x brick_temp.rect.y = self.settings.brick_y_offset - 256 new_column.add(brick_temp) self.brick_columns.append(new_column)