def game(screen): move = False score = 0 running = True snake = Snake(screen) apple = Apple() bg = Background("images/bg.jpg", [0, 0]) while running: clickedArrow = False ateApple = False screen.fill(bgcolor) #screen.blit(bg.image, bg.rect) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pause(screen) continue if event.key == pygame.K_UP and snake.direction != 2 and not clickedArrow: move = True clickedArrow = True snake.setDirection(0) if event.key == pygame.K_RIGHT and snake.direction != 3 and not clickedArrow: move = True clickedArrow = True snake.setDirection(1) if event.key == pygame.K_DOWN and snake.direction != 0 and not clickedArrow: move = True clickedArrow = True snake.setDirection(2) if event.key == pygame.K_LEFT and snake.direction != 1 and not clickedArrow: move = True clickedArrow = True snake.setDirection(3) if event.key == pygame.K_1: snake.makeBigger() score += 1 ateApple = True if event.key == pygame.K_2: snake.makeSmaller() if move: snake.move() if snake.pieces[0].x == apple.x and snake.pieces[0].y == apple.y: score += 1 apple.changeCoords() snake.makeBigger() ateApple = True if snake.isDead() and not ateApple: gameOver(screen, score) running = False apple.draw(screen) if not ateApple: snake.draw() drawscore(screen, score) pygame.display.update() time.sleep(.25)
def main(): cfg = _parse_args() common.setup_logging(cfg.verbose) game_quit = False pygame.init() pygame.display.set_caption("Snake - by lewohart") clock = pygame.time.Clock() display = pygame.Rect(0, 0, 1000, 800) box = display.inflate(-200, -100) columns = box.width // 20 rows = box.height // 20 screen = pygame.display.set_mode(display.size) board = Board(screen, display, box, columns, rows, cfg) snake = Snake(board) apple = Apple(board) apple.yield_away_from_the(snake) while not (game_quit): for event in pygame.event.get(): if event.type == pygame.QUIT: game_quit = True elif event.type == pygame.KEYDOWN: snake.turn(event.key) snake.step() if snake.reachs_the_border or snake.bit_herself: break if snake.reachs_the(apple): snake.eat_the(apple) apple.yield_away_from_the(snake) board.draw() apple.draw() snake.draw() pygame.display.flip() clock.tick(20) font_style = pygame.font.SysFont(pygame.font.get_default_font(), 50) text = font_style.render("Game over", True, Color.RED) text_rect = text.get_rect(center=display.center) screen.blit(text, text_rect) pygame.display.flip() time.sleep(4) pygame.quit() quit(0)
def run(self, screen): running = True score = 0 scoreFont = pygame.font.SysFont("arial", 18) lossFont = pygame.font.SysFont("arial", 72) lossText = lossFont.render('You died', True, (0, 255, 0)) clock = pygame.time.Clock() snake = Snake() apple = Apple() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and snake.direction != 'DOWN': snake.direction = 'UP' if event.key == pygame.K_DOWN and snake.direction != 'UP': snake.direction = 'DOWN' if event.key == pygame.K_RIGHT and snake.direction != 'LEFT': snake.direction = 'RIGHT' if event.key == pygame.K_LEFT and snake.direction != 'RIGHT': snake.direction = 'LEFT' if event.key == pygame.K_r and not snake.alive: Game() pygame.event.clear() if snake.alive: if apple.rect.colliderect(snake.rect): snake.eatApple() apple.eaten() score += 1 screen.fill((0, 0, 0)) scoreText = scoreFont.render('Score: %s' % score, True, (0, 255, 0)) screen.blit(scoreText, (25, 10)) apple.draw(screen) snake.draw(screen) clock.tick(5) pygame.display.flip() if not snake.alive: screen.blit(lossText, (300, 250)) pygame.display.update()
class App: windowDimY = 14 windowDimX = 18 windowWidth = 0 windowHeight = 0 toolbarWidth = 200 player = 0 apple = 0 toolbar = 0 dataCollect = 0 displayq = False def __init__(self,dq,state,freq): self._running = True self._display_surf = None self._image_surf = None self._apple_surf = None self.game = Game() self.player = Player(3,self.windowDimX, self.windowDimY) self.windowWidth = self.windowDimX*self.player.step self.windowHeight = self.windowDimY*self.player.step self.toolbar = Toolbar(self.toolbarWidth, self.windowWidth, self.windowHeight) self.apple = Apple(randint(0,self.windowDimX-1), randint(0,self.windowDimY-1)) self.dataCollect = DataCollector() self.displayq=dq self.state_size = state self.frequency = freq def on_init(self): pygame.init() if(self.displayq): self._display_surf = pygame.display.set_mode((self.windowWidth+self.toolbarWidth,self.windowHeight), pygame.HWSURFACE) pygame.display.set_caption('Pygame Snake game!') self._image_surf = pygame.image.load("images/game_objects/smake.png").convert() self._apple_surf = pygame.image.load("images/game_objects/smapple.png").convert() self.toolbar.load_images() self._running = True # self.savepath = "frames/"+time.strftime("%Y%m%d-%H%M%S") # os.mkdir(self.savepath) def on_event(self, event): if event.type == QUIT: self._running = False def on_loop(self): self.player.update() # does snake collide with itself? for i in range(2,self.player.length): if self.game.isCollision(self.player.x[0],self.player.y[0],self.player.x[i], self.player.y[i],self.player.step-1): print("You lose! Collision with yourself: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") print("x[" + str(i) + "] (" + str(self.player.x[i]) + "," + str(self.player.y[i]) + ")") self.player.crashed = True # does snake eat apple? for i in range(0,self.player.length): if self.game.isCollision(self.apple.x,self.apple.y,self.player.x[i], self.player.y[i],self.player.step-1): self.apple.x = randint(0,self.windowDimX-1) * self.player.step self.apple.y = randint(0,self.windowDimY-1) * self.player.step print("apple x=",self.apple.x,"apple y=",self.apple.y) self.player.eatenApple = True #does snake collide with wall? if(self.player.x[0]<0 or self.player.x[0]>=self.windowWidth or self.player.y[0]<0 or self.player.y[0]>=self.windowHeight): print("You lose! Collision with wall: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") self.player.crashed = True pass def on_render(self, state): self._display_surf.fill((0,0,0)) self.player.draw(self._display_surf, self._image_surf) self.apple.draw(self._display_surf, self._apple_surf) self.toolbar.draw(self._display_surf, self.player.direction, state) pygame.display.flip() def on_cleanup(self): pygame.quit() # initializing agent before the 1st move def init_agent(self, agent): state_init1 = agent.get_state(game, self.player, self.food) #first state after random placement #first action def reset_player(self): self.player = Player(3,self.windowDimX, self.windowDimY) #print(self.player.x) #print(self.player.y) def on_execute(self,speed): print('starting execution!') params = parameters() agent = dqnagent(params,self.state_size) #initialize the agent! if(agent.load_weights): #load weights maybe agent.model.load_weights(agent.weights) print("loaded the weights") counter = 0 #how many games have been played/trials done record = 0 #highest score #--------------------------------------------------------------------------- #------------------------- LOOP THRU EPISODES ------------------------------ #--------------------------------------------------------------------------- while counter<params['episodes']: #still have more trials to do counter += 1 print(counter) print("\nEPISODE ", counter, "\n") if not params['train']: # if you're not training it, no need for exploration agent.epsilon = 0 else: agent.epsilon = 1.0 - ((counter -1) * params['epsilon_decay_linear'])#exploration/randomness factor that decreases over time #print("EPSILON = ", agent.epsilon, "\n") if self.on_init() == False: self._running = False #print("PLAYER\tx : ", self.player.x,"\ty : ", self.player.y, "\n") duration = 0 #--------------------------------------------------------------------------- #--------------------------- INDIVIDUAL EPISODE ---------------------------- #--------------------------------------------------------------------------- # indexx = 0 while(self._running): if(counter%self.frequency==0): self.dataCollect.record(self.player.x, self.player.y, self.apple.x, self.apple.y) duration+=1 #print("\nMOVE : ", duration, "\n") if(self.displayq): pygame.event.pump() keys = pygame.key.get_pressed() if (keys[K_ESCAPE]): exit(0) oldstate = agent.get_state(self, self.player, self.apple) #print("\noldstate = ", oldstate) #--------------------------- GET AGENT ACTION ---------------------------- if random() < agent.epsilon: #every so often random exploration action = randint(0,3) #random action #print("random action : ",action) else: #Actionprecited by agent state = oldstate.reshape(1,self.state_size**2+8) predictedq= agent.model.predict(state) # predicts the q values for the action in that state action = np.argmax(predictedq[0]) #maximum (highest q) action #print("predicted action : ", action, "\tq-values : ", predictedq) #---------------------------- EXECUTE ACTION ----------------------------- print(action) self.player.do_move(action) #do the action self.on_loop() newstate = agent.get_state(self, self.player, self.apple) #new state from the action we've taken reward = agent.set_reward(self.player) #print("newstate = ", newstate) #print("reward = ", reward) #print("crashed = ", self.player.crashed, "\n") #---------------------------- SHORT TRAINING ----------------------------- if(params['train']): agent.train_short_memory(oldstate,action, reward, newstate, self.player.crashed) agent.remember(oldstate,action, reward, newstate, self.player.crashed) #------------------------------ RENDER GAME ------------------------------ self._running = not(self.player.crashed) if(self.displayq): self.on_render(newstate) # if(counter%self.frequency==0): # self.on_render(newstate) # pygame.image.save(self._display_surf,savepath+str(indexx)) time.sleep (speed/1000.0) # indexx +=1 #--------------------------------------------------------------------------- #----------------------- TRAINING & DATA COLLECTION ------------------------ #--------------------------------------------------------------------------- if(params['train']): agent.replay_new(agent.memory, params['batch_size']) # self.dataCollect.add(self.player.length,duration,agent.epsilon,agent.history.losses) self.dataCollect.add(self.player.length,duration,agent.epsilon, 0.0) self.dataCollect.save() #print(agent.history.losses.length()) #agent.history.losses = [] self.player.reset(3,self.windowDimX, self.windowDimY ) self.on_cleanup() #--------------------------------------------------------------------------- #------------------------------ DATA OUTPUT -------------------------------- #--------------------------------------------------------------------------- if(params['train']): os.mkdir(params['weights_path_save']) agent.model.save_weights(params['weights_path_save']+'/weights.hdf5') self.dataCollect.save()
class Pynake(arcade.Window): def __init__(self, width, height, tile_size): super().__init__(width, height, 'Pynake') self.tile_size = tile_size def setup(self): self.set_update_rate(1 / 8) # fps self.game_started = False self.game_over = False self.score = 0 self.snake = Snake( (self.width, self.height), self.tile_size ) self.apple = Apple( (self.width, self.height), self.tile_size, self.snake.placement ) # goes clockwise (top, right, bottom, left) self.borders = ( int(self.height - self.tile_size / 2), int(self.width - self.tile_size / 2), int(0 + self.tile_size / 2), int(0 + self.tile_size / 2), ) self.death_sound = arcade.Sound('assets/audio/death.mp3') return self def run(self): arcade.run() def on_draw(self): # This command should happen before we start drawing. It will clear # the screen to the background color, and erase what we drew last frame. arcade.start_render() self.draw_background() self.draw_score() self.apple.draw() self.snake.draw() if self.game_over: self.draw_game_over() if not self.game_started: self.draw_start_guide() def on_update(self): if not self.game_started or self.game_over: return if self.hits_border() or self.snake.collides_self(): self.finalize_game() return did_eat = self.snake.update(self.apple.position) if did_eat: self.score += 10 self.apple.respawn(self.snake.placement) def on_key_press(self, key): if self.game_over: if key == constants.SPACE: self.restart() return # when first starting, game is paused if not self.game_started and key in [constants.UP, constants.DOWN, constants.LEFT, constants.RIGHT]: self.game_started = True if ( key == constants.UP or key == constants.DOWN or key == constants.LEFT or key == constants.RIGHT ): self.snake.direction = key def hits_border(self): x, y = self.snake.next_move() top, right, bottom, left = self.borders if x < left or x > right or y < bottom or y > top: return True return False def finalize_game(self): self.game_over = True self.death_sound.play() def restart(self): self.game_over = False self.game_started = False self.score = 0 self.snake.reset() self.apple.respawn(self.snake.placement) def draw_background(self): color = arcade.color.ANDROID_GREEN for y in range(int(self.tile_size / 2), int(self.height - self.tile_size / 2) + 1, self.tile_size): for x in range(int(self.tile_size / 2), int(self.width - self.tile_size / 2) + 1, self.tile_size): arcade.draw_point(x, y, color, self.tile_size) color = (arcade.color.ANDROID_GREEN if color != arcade.color.ANDROID_GREEN else arcade.color.APPLE_GREEN) color = (arcade.color.ANDROID_GREEN if color != arcade.color.ANDROID_GREEN else arcade.color.APPLE_GREEN) def draw_game_over(self): arcade.draw_text( "GAME OVER", self.width / 2, self.height * 2 / 3, arcade.color.RED, 40, align="center", anchor_x="center", anchor_y="center" ) arcade.draw_text( "Press SPACE to start over", self.width / 2, self.height * 2 / 3 - self.tile_size * 2, arcade.color.BLACK_OLIVE, 20, align="center", anchor_x="center", anchor_y="center" ) def draw_start_guide(self): arcade.draw_text( "Press Arrow keys to start", self.width / 2, self.height * 2 / 3, arcade.color.BLACK_OLIVE, 40, align="center", anchor_x="center", anchor_y="center" ) def draw_score(self): arcade.draw_text( f'{self.score}', self.tile_size / 8, self.height - self.tile_size / 2, arcade.color.BLACK_OLIVE, 16, anchor_y="center" )
class App: windowDimY = 14 windowDimX = 18 windowWidth = 0 windowHeight = 0 toolbarWidth = 200 player = 0 apple = 0 toolbar = 0 def __init__(self): self._running = True self._display_surf = None self._image_surf = None self._apple_surf = None self.game = Game() self.player = Player(3, self.windowDimX, self.windowDimY) self.windowWidth = self.windowDimX * self.player.step self.windowHeight = self.windowDimY * self.player.step self.toolbar = Toolbar(self.toolbarWidth, self.windowWidth, self.windowHeight) self.apple = Apple(randint(0, self.windowDimX - 1), randint(0, self.windowDimY - 1)) def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode( (self.windowWidth + self.toolbarWidth, self.windowHeight), pygame.HWSURFACE) pygame.display.set_caption('Pygame Snake game!') self._running = True self._image_surf = pygame.image.load( "images/game_objects/smake.png").convert() self._apple_surf = pygame.image.load( "images/game_objects/smapple.png").convert() self.toolbar.load_images() def on_event(self, event): if event.type == QUIT: self._running = False def on_loop(self): self.player.update() # does snake collide with itself? for i in range(2, self.player.length): if self.game.isCollision(self.player.x[0], self.player.y[0], self.player.x[i], self.player.y[i], self.player.step - 1): print("You lose! Collision with yourself: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") print("x[" + str(i) + "] (" + str(self.player.x[i]) + "," + str(self.player.y[i]) + ")") exit(0) # does snake eat apple? for i in range(0, self.player.length): if self.game.isCollision(self.apple.x, self.apple.y, self.player.x[i], self.player.y[i], self.player.step - 1): self.apple.x = randint(0, self.windowDimX - 1) * self.player.step self.apple.y = randint(0, self.windowDimY - 1) * self.player.step print("apple x=", self.apple.x, "apple y=", self.apple.y) self.player.eatenApple = True #does snake collide with wall? if (self.player.x[0] < 0 or self.player.x[0] >= self.windowWidth or self.player.y[0] < 0 or self.player.y[0] >= self.windowHeight): print("You lose! Collision with wall: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") exit(0) pass def state(self): middle = int(dim / 2) grid = np.zeros((dim, dim), dtype=bool) print("x=", self.player.x, "y=", self.player.y) relativex = [ int((a - self.player.x[0]) / self.player.step + middle) for a in self.player.x ] relativey = [ int((a - self.player.y[0]) / self.player.step + middle) for a in self.player.y ] for x, y in zip(relativex, relativey): if (x >= 0 and y >= 0 and x < dim and y < dim): grid[y, x] = True print("x", relativex, "y", relativey) right = int(self.windowDimX - (self.player.x[0] / self.player.step) + middle) down = int(self.windowDimY - (self.player.y[0] / self.player.step) + middle) up = int(middle - (self.player.y[0] / self.player.step)) left = int(middle - (self.player.x[0] / self.player.step)) if (right < dim and right >= 0): grid[:, right:] = True if (left < dim and left >= 0): grid[:, :left] = True if (down < dim and down >= 0): grid[down:, :] = True if (up < dim and up >= 0): grid[:up, :] = True print(right, left, up, down) print("GRID after") print(grid) grid = list(grid.flatten()) state = [ self.player.direction == 0, #right self.player.direction == 1, #left self.player.direction == 2, #up self.player.direction == 3, #down self.apple.y < self.player.y[0], #food is up from the player self.apple.y > self.player.y[0], #food is down from the player self.apple.x < self.player.x[0], #food is to the left of the player self.apple.x > self.player.x[0] #food is to the right of the player ] state += grid for i in range(len(state)): #convert list to 0s and 1s if (state[i]): state[i] = 1 else: state[i] = 0 return np.asarray(state) def on_render(self): self._display_surf.fill((0, 0, 0)) self.player.draw(self._display_surf, self._image_surf) self.apple.draw(self._display_surf, self._apple_surf) print(self.state()) self.toolbar.draw(self._display_surf, self.player.direction, self.state()) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False while (self._running): pygame.event.pump() keys = pygame.key.get_pressed() if (keys[K_RIGHT]): self.player.moveRight() if (keys[K_LEFT]): self.player.moveLeft() if (keys[K_UP]): self.player.moveUp() if (keys[K_DOWN]): self.player.moveDown() if (keys[K_ESCAPE]): self._running = False self.on_loop() self.on_render() time.sleep(70.0 / 1000.0) self.on_cleanup()
for event in pygame.event.get(): # IF QUIT... if event.type == pygame.QUIT: run = False # DRAW OBJECTS # Log Objects for i in range(len(logs)): logs[i].move() logs[i].draw() # Other Objects top.draw() apple.draw() bot.draw() frog.draw() # Move Frog if keys[pygame.K_UP]: # 'Up' has different calculations than down or side-to-side. # if frog # Q: How to check for the NEXT log? # TOP GROUND if frog.y == row[1]: frog.y -= 50
class App: windowWidth = 800 windowHeight = 600 player = 0 apple = 0 def __init__(self): self._running = True self._display_surf = None self._image_surf = None self._apple_surf = None self.game = Game() self.player = Player(3) self.apple = Apple(5,5) def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode((self.windowWidth,self.windowHeight), pygame.HWSURFACE) pygame.display.set_caption('Pygame pythonspot.com example') self._running = True self._image_surf = pygame.image.load("snake_block.png").convert() self._apple_surf = pygame.image.load("apple.png").convert() def on_event(self, event): if event.type == QUIT: self._running = False def on_loop(self): self.player.update() # does snake eat apple? for i in range(0,self.player.length): if self.game.isCollision(self.apple.x,self.apple.y,self.player.x[i], self.player.y[i],44): self.apple.x = randint(2,9) * 44 self.apple.y = randint(2,9) * 44 self.player.length = self.player.length + 1 # does snake collide with itself? for i in range(2,self.player.length): if self.game.isCollision(self.player.x[0],self.player.y[0],self.player.x[i], self.player.y[i],40): print("You lose! Collision: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") print("x[" + str(i) + "] (" + str(self.player.x[i]) + "," + str(self.player.y[i]) + ")") exit(0) pass def on_render(self): self._display_surf.fill((0,0,0)) self.player.draw(self._display_surf, self._image_surf) self.apple.draw(self._display_surf, self._apple_surf) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False while( self._running ): pygame.event.pump() keys = pygame.key.get_pressed() #Example of an if statement for the right key if (keys[K_RIGHT]): self.player.moveRight() """Complete the code for the other keys""" #If statement for left key self.player.moveLeft() #If statement for the up key self.player.moveUp() #If statement for the down key self.player.moveDown() #If statement for the esc key self._running = False self.on_loop() self.on_render() time.sleep (50.0 / 1000.0); self.on_cleanup()
class App: windowWidth = 800 windowHeight = 600 player = 0 event = None rect = None gameOver = False def __init__(self): self._running = True self._display_surf = None self._image_surf = None self._apple_surf = None self.player = Player(3) self.apple = Apple(5,5) self.game = Game() def on_init(self): print('inside on_init') pygame.init() self._display_surf = pygame.display.set_mode((self.windowWidth,self.windowHeight), pygame.HWSURFACE) pygame.display.set_caption('Snake Game') self._running = True self.rect = pygame.Rect(25, 47, 750, 600-47-25) self._snakebody = pygame.image.load('snakebody.png').convert() self._apple_surf = pygame.image.load('apple.png').convert() def on_event(self, event): if event.type == QUIT: self._running = False def on_loop(self): if not self.gameOver: self.player.update() #does snake eat apple for i in range(0, self.player.length): if self.game.isCollision(self.apple.x, self.apple.y, self.player.x[i], self.player.y[i], 20): self.player.length = self.player.length + 1 self.apple.x = randint(2,9) * 25 self.apple.y = randint(2,9) * 25 self.player.score = self.player.score + 1 #does snake collide with itself for i in range(2, self.player.length): self.gameOver = self.game.isCollision(self.player.x[0], self.player.y[0], self.player.x[i], self.player.y[i], 20) if self.game.isCollision(self.player.x[0], self.player.y[0], self.player.x[i], self.player.y[i], 20): print("You lose! Collision") print('YOUR SCORE IS : ', self.player.score) return #does snake collide with boundary self.gameOver = self.game.boundaryCollision(self.rect.x, self.rect.y, self.player.x[0], self.player.y[0], 20) pass def on_render(self): #filling color in background self._display_surf.fill((255,255,255)) pygame.draw.rect(self._display_surf, (0, 0, 0), self.rect) #line dividing score board block and game block pygame.draw.line(self._display_surf, (255, 255, 255), (0, 47), (800, 47)) #checking what side of head should be drawn on the snake if self.event[K_RIGHT]: if self.player.block != 0: self._image_surf = pygame.image.load('snakehead_right.png').convert() if self.event[K_LEFT]: if self.player.block != 1: self._image_surf = pygame.image.load('snakehead_left.png').convert() if self.event[K_UP]: if self.player.block != 2: self._image_surf = pygame.image.load('snakehead_up.png').convert() if self.event[K_DOWN]: if self.player.block != 3: self._image_surf = pygame.image.load('snakehead_down.png').convert() #draw player(snake) self.player.draw(self._display_surf, self._image_surf, self._snakebody) #draw apple self.apple.draw(self._display_surf, self._apple_surf) #draw score board self.game.drawScore(self._display_surf, str('your Score is : ')+str(self.player.score), 30, 50, 10 ) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False self._image_surf = pygame.image.load('snakehead_right.png').convert() while(self._running): pygame.event.pump() keys = pygame.key.get_pressed() #self.on_loop() self.event = keys if keys[K_RIGHT]: self.player.moveRight() if keys[K_LEFT]: self.player.moveLeft() if keys[K_UP]: self.player.moveUp() if keys[K_DOWN]: self.player.moveDown() if keys[K_ESCAPE]: self._running = False #if game is over the screen stops if self.gameOver: self.game.gameOver(self._display_surf, self.player) for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self._image_surf = pygame.image.load('snakehead_right.png').convert() self._display_surf.fill([255,255,255]) self.player = Player(3) self.appple = Apple(5,5) self.on_init() self.gameOver = False break else: self.on_loop() self.on_render() time.sleep(100.0/1000.0) #self.on_event() self.on_cleanup()
class App: windowWidth = 800 windowHeight = 600 snake = 0 apple = 0 def __init__(self): self._running = True self._display_surf = None self._image_surf = None self._apple_surf = None self.game = Game() self.snake = Player(3) self.apple = Apple(5, 5) def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode( (self.windowWidth, self.windowHeight), pygame.HWSURFACE) pygame.display.set_caption('Rabbit_2k18: Snake') self._running = True self._image_surf = pygame.Surface((STEP, STEP)) self._apple_surf = pygame.Surface((STEP, STEP)) def on_event(self, event): if event.type == QUIT: self._running = False def on_loop(self): self.snake.update() # does snake eat apple? for i in range(0, self.snake.length): if self.game.isCollision(self.apple.x, self.apple.y, self.snake.x[i], self.snake.y[i], STEP): self.apple.x = randint(2, 9) * STEP self.apple.y = randint(2, 9) * STEP self.snake.length = self.snake.length + 1 self.snake.points = self.snake.points + 1 # does snake collide with itself? for i in range(2, self.snake.length): if self.game.isCollision(self.snake.x[0], self.snake.y[0], self.snake.x[i], self.snake.y[i], 40): print("You lose! Collision: ") print("x[0] (" + str(self.snake.x[0]) + "," + str(self.snake.y[0]) + ")") print("x[" + str(i) + "] (" + str(self.snake.x[i]) + "," + str(self.snake.y[i]) + ")") print("Points: " + str(self.snake.points)) exit(0) pass def on_render(self): self._display_surf.fill((0, 0, 0)) self.snake.draw(self._display_surf, self._image_surf) self.apple.draw(self._display_surf, self._apple_surf) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False while (self._running): pygame.event.pump() keys = pygame.key.get_pressed() if (keys[K_RIGHT]): self.snake.moveRight() if (keys[K_LEFT]): self.snake.moveLeft() if (keys[K_UP]): self.snake.moveUp() if (keys[K_DOWN]): self.snake.moveDown() if (keys[K_ESCAPE]): self._running = False self.on_loop() self.on_render() time.sleep(50.0 / 1000.0) self.on_cleanup()
class Grid: """ A rectangular grid on which the game is played. ... Attributes ---------- dimensions : tuple of int the dimensions of the playing grid in pixels background : pygame.Surface a rectangular graphic representing the grid rect : pygame.Rect coordinates of the grid snake : Snake the single snake in the game red_apple : Apple the single apple in the game other_apples : list of Apple a collection of golden and poison currently on the grid other_apple_spawn_rate : float the rate at which golden and poison apples randomly spawn onto grid other_apple_despawn_rate : float the rate at which golden and poison apples are randomly removed from the grid Methods ------- randomly_place_sprite(sprite_to_place) randomly place sprite on grid where it will not overlap with the snake, any apples, or the wall check_apple_eaten() handle events for when the snake runs into an apple check_snake_collision() handle events for when the snake runs into a wall or itself level_up() change the snake and apple stats when the player levels up update() update the grid's snake and randomly spawn apples change_colors() change the colors of the grid's background and wall draw() draw the grid and it's snake and apples to the screen """ def __init__(self, dimensions, color_palette, snake): self.dimensions = dimensions self.background = pygame.Surface(dimensions).convert() self.background.fill(color_palette[0]) self.rect = self.background.get_rect() self.rect.topleft = 0, BANNER_DIMENSIONS[1] self.brick_wall = BrickWall(self.dimensions, color_palette[1]) self.snake = snake self.red_apple = Apple(RED) self.other_apples = [] self.other_apple_spawn_rate = 0.0050 self.other_apple_despawn_rate = 0.0025 self.randomly_place_sprite(self.snake.head) self.randomly_place_sprite(self.red_apple) def randomly_place_sprite(self, sprite_to_place): while True: rows_in_grid = int(self.dimensions[1] / TILE_WIDTH_PIXELS) columns_in_grid = int(self.dimensions[0] / TILE_WIDTH_PIXELS) x_pos = random.randint(0, columns_in_grid - 1) * TILE_WIDTH_PIXELS y_pos = random.randint( 0, rows_in_grid - 1) * TILE_WIDTH_PIXELS + BANNER_DIMENSIONS[1] sprite_to_place.move_to(x_pos, y_pos) all_sprites = (self.snake.all_pieces + self.other_apples + self.brick_wall.bricks) all_other_sprites = [ sprite for sprite in all_sprites if sprite is not sprite_to_place ] if sprite_to_place.rect.collidelist( all_other_sprites) == -1 and self.rect.contains( sprite_to_place.rect): return def check_apple_eaten(self): all_apples = self.other_apples + [self.red_apple] collision_index = self.snake.head.rect.collidelist(all_apples) if collision_index != -1: # if collision apple_obtained = all_apples[collision_index] apple_obtained.eaten_sound.play() if apple_obtained.color == RED: self.randomly_place_sprite(self.red_apple) self.snake.elongation_cycles_remaining += self.snake.elongation_factor elif apple_obtained.color == GOLDEN: self.snake.remove_half() del self.other_apples[collision_index] elif apple_obtained.color == POISON: self.snake.elongation_cycles_remaining += self.snake.elongation_factor * 5 del self.other_apples[collision_index] return True return False def check_snake_collision(self): # ignore first 5 pieces of snake body, they overlap with snake's head when turning if self.snake.head.rect.collidelist( self.snake.body_pieces_only[5:]) != -1: return True if self.snake.head.rect.collidelist(self.brick_wall.bricks) != -1: return True return False def level_up(self): self.snake.level_up() self.other_apples = [] self.other_apple_spawn_rate *= 1.05 self.other_apple_despawn_rate *= 1.05 def update(self): self.snake.update() self._handle_snake_OOB() self._apple_spawn_events() def change_color(self, background_color, wall_color): self.background.fill(background_color) self.brick_wall.change_color(wall_color) def draw(self, surface): surface.blit(self.background, self.rect) self.red_apple.draw(surface) for apple in self.other_apples: apple.draw(surface) for piece in self.snake.all_pieces: piece.draw(surface) self.brick_wall.draw(surface) def _handle_snake_OOB(self): for piece in self.snake.all_pieces: if piece.rect.right > self.rect.right: piece.rect.move_ip(-self.dimensions[0], 0) return elif piece.rect.left < self.rect.left: piece.rect.move_ip(+self.dimensions[0], 0) return elif piece.rect.top < self.rect.top: piece.rect.move_ip(0, +self.dimensions[1]) return elif piece.rect.bottom > self.rect.bottom: piece.rect.move_ip(0, -self.dimensions[1]) return def _apple_spawn_events(self): if random.random() < self.other_apple_spawn_rate: if random.random() < 0.1: self.other_apples.append(Apple(GOLDEN)) else: self.other_apples.append(Apple(POISON)) self.randomly_place_sprite(self.other_apples[-1]) if random.random( ) < self.other_apple_despawn_rate and self.other_apples: apple_to_delete = random.choice(self.other_apples) self.other_apples.remove(apple_to_delete)
class Field: def __init__(self, ga, width, height): self.ga = ga self.width = width self.height = height self.sc = pygame.display.set_mode([width + 1, height + 1]) self.clock = pygame.time.Clock() self.snake = Snake(self.sc, self) self.apple = Apple(self.sc, self) self.death_stats = [0] * 3 pygame.init() def get_fitness(self, individual): self.ga.ind_counter += 1 self.snake.reset() self.snake.load_weights(individual) self.apple.reset() while True: self.snake.move() self.draw() if self.snake.check_apple_collision(): self.apple.reset() if self.snake.check_wall_collision(): self.death_stats[0] += 1 break if self.snake.check_self_collision(): self.death_stats[1] += 1 break if self.snake.check_energy(): self.death_stats[2] += 1 break check_events() return self.snake.get_fitness() # Проверяем не вышла ли голова змейки на границы поля def is_valid_pos(self, pos): if pos.x < 0 or pos.x > self.width - self.snake.size or pos.y < 0 or pos.y > self.height - self.snake.size: return False return True # Получаем случайную позицию на поле [доработать] def get_random_pos(self): while True: pos = Vector2(randrange(0, self.width, self.snake.size), randrange(0, self.height, self.snake.size)) if pos not in self.snake.get_segments(): return pos def get_apple_pos(self): return self.apple.get_pos() def set_death_stats(self, death_stats): self.death_stats = death_stats def get_death_stats(self): return self.death_stats def draw(self): if settings['animation']: self.sc.fill(pygame.Color('#282A36')) if settings['grid']: self.draw_grid() if settings['info']: self.draw_info() if settings['snake_footprint']: self.snake.draw_footprint() if settings['snake_vectors']: self.snake.draw_vectors() self.snake.draw() self.apple.draw() pygame.display.flip() if settings['slow_mode']: self.clock.tick(settings['fps']) def draw_grid(self): for x in range(0, self.width + self.snake.size, self.snake.size): pygame.draw.aaline(self.sc, '#44475a', [x, 0], [x, self.height]) for y in range(0, self.height + self.snake.size, self.snake.size): pygame.draw.aaline(self.sc, '#44475a', [0, y], [self.width, y]) def draw_info(self): self.draw_text(20, 20, f'HIGH SCORE: {self.snake.high_score}') self.draw_text(20, 40, f'GENERATION: {self.ga.gen_counter}') self.draw_text(20, 60, f'GENOME: {self.ga.ind_counter}/{self.ga.pop_length}') self.draw_text(20, 80, f'SCORE: {self.snake.score}') self.draw_text(20, 100, f'STEPS: {self.snake.steps}') self.draw_text(20, 120, f'ENERGY: {self.snake.get_energy()}') if sum(self.death_stats) != 0: percent = '{:.2f}'.format(self.death_stats[0] * 100 / sum(self.death_stats)) self.draw_text( 20, 140, f'BUMPED INTO A WALL: {self.death_stats[0]} | {percent}%') percent = '{:.2f}'.format(self.death_stats[1] * 100 / sum(self.death_stats)) self.draw_text( 20, 160, f'HIT ITS OWN TAIL: {self.death_stats[1]} | {percent}%') percent = '{:.2f}'.format(self.death_stats[2] * 100 / sum(self.death_stats)) self.draw_text( 20, 180, f'DIED OF HUNGER: {self.death_stats[2]} | {percent}%') self.draw_text(20, 220, f'HOTKEYS:') self.draw_text(20, 240, f'A - evolution without animation') self.draw_text(20, 260, f'S - slow/fast') self.draw_text(20, 280, f'M - smart speed') self.draw_text(20, 300, f'F - footprint') self.draw_text(20, 320, f'V - vectors') self.draw_text(20, 340, f'G - grid') self.draw_text(20, 360, f'I - info') self.draw_text( 20, 400, f'Snake: [ {self.snake.get_head().x}, {self.snake.get_head().y} ]') self.draw_text( 20, 420, f'Apple: [ {self.apple.get_pos().x}, {self.apple.get_pos().x} ]') def draw_text(self, x, y, text): font = pygame.font.Font('./fonts/TerminusTTF.ttf', 14) self.sc.blit(font.render(text, True, pygame.Color('#50FA7B')), (x, y))
class App: window_width = 600 window_height = 600 player = 0 apple = 0 running = True def __init__(self): self.running = True self._display_surf = None self._image_surf = None self.game = Game(self.window_width, self.window_height) self.player = Player(STARTING_LENGTH, self.window_height * self.window_width) self.apple = Apple(randint(0, self.window_width // STEP - 1), randint(0, self.window_height // STEP - 1)) def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode( (self.window_width, self.window_height), pygame.HWSURFACE) pygame.display.set_caption('Pygame Snake AI Game') self.running = True self._image_surf = pygame.Surface((10, 10)) self._image_surf.fill((255, 255, 255)) self._apple_surf = pygame.Surface((10, 10)) self._apple_surf.fill((0, 255, 0)) return self.get_observations() def get_observations(self): observs = np.zeros( (self.window_width // STEP, self.window_height // STEP)) observs[self.apple.x // STEP - 1, self.apple.y // STEP - 1] = 1 x = self.player.x[0] // STEP - 1 y = self.player.y[0] // STEP - 1 if not (x > self.window_width // STEP or x < 0 or y > self.window_height // STEP or y < 0): observs[x, y] = -2 for i in range(1, self.player.length): observs[self.player.x[i] // STEP - 1, self.player.y[i] // STEP - 1] = -1 return observs.reshape((1, -1)) # reshape to vector def on_event(self, event): if event.type == QUIT: self.running = False def on_loop(self): self.player.update() # does snake eat apple? for i in range(0, self.player.length): if self.game.is_collision(self.apple.x, self.apple.y, self.player.x[i], self.player.y[i]): self.apple.x = randint(0, self.window_width // STEP - 1) * STEP self.apple.y = randint(0, self.window_height // STEP - 1) * STEP # print("Apple Location, (", self.apple.x, ", ", self.apple.y, ")" ) self.player.length = self.player.length + 1 # does snake collide with itself? lost = False for i in range(1, self.player.length): lost = self.game.is_collision(self.player.x[0], self.player.y[0], self.player.x[i], self.player.y[i]) if lost: break if self.game.is_wall_collision(self.player.x[0], self.player.y[0]) or lost: print("You lose! Collision: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") print("x[" + str(i) + "] (" + str(self.player.x[i]) + "," + str(self.player.y[i]) + ")") self.running = False def on_render(self): self._display_surf.fill((20, 20, 15)) self.player.draw(self._display_surf, self._image_surf) self.apple.draw(self._display_surf, self._apple_surf) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_key(self, key, loop=False): if key == K_RIGHT: self.player.move_right() if key == K_LEFT: self.player.move_left() if key == K_UP: self.player.move_up() if key == K_DOWN: self.player.move_down() if loop: self.on_loop() self.on_render() def on_execute(self): self.on_init() while self.running: pygame.event.pump() keys = pygame.key.get_pressed() if keys[K_RIGHT]: self.on_key(K_RIGHT) if keys[K_LEFT]: self.on_key(K_LEFT) if keys[K_UP]: self.on_key(K_UP) if keys[K_DOWN]: self.on_key(K_DOWN) if keys[K_ESCAPE]: self.running = False self.on_loop() self.on_render() time.sleep(20.0 / 1000.0) self.on_cleanup() def get_reward(self): r = self.game.get_distance(self.player.x[0], self.player.y[0], self.apple.x, self.apple.y) r += 240 * (self.player.length - STARTING_LENGTH) r -= (not self.running) * 200 # r = self.player.length - STARTING_LENGTH return r
class App: windowWidth = 800 windowHeight = 600 player = 0 apple = 0 def __init__(self): self._running = True self._display_surf = None self._image_surf = None self._apple_surf = None self.game = Game() self.player = Player(3) self.apple = Apple(5, 5) file = 'music.mp3' pygame.mixer.init() # Initialize background music pygame.mixer.music.load(file) pygame.mixer.music.play() def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode( (self.windowWidth, self.windowHeight), pygame.HWSURFACE) pygame.display.set_caption('Slithery') self._running = True self._image_surf = pygame.image.load("images/apple.jpg").convert() self._apple_surf = pygame.image.load("images/snake.jpg").convert() def on_event(self, event): if event.type == QUIT: self._running = False def on_loop(self): self.player.update() # does snake eat apple? for i in range(0, self.player.length): if self.game.isCollision(self.apple.x, self.apple.y, self.player.x[i], self.player.y[i], 44): self.apple.x = randint(2, 9) * 44 self.apple.y = randint(2, 9) * 44 self.player.length += 1 # does snake collide with itself? for i in range(2, self.player.length): if self.game.isCollision(self.player.x[0], self.player.y[0], self.player.x[i], self.player.y[i], 40): print("You lose! Collision: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") print("x[" + str(i) + "] (" + str(self.player.x[i]) + "," + str(self.player.y[i]) + ")") exit(0) pass def on_render(self): self._display_surf.fill((0, 0, 0)) self.player.draw(self._display_surf, self._image_surf) self.apple.draw(self._display_surf, self._apple_surf) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False while self._running: pygame.event.pump() keys = pygame.key.get_pressed() if keys[K_RIGHT]: self.player.move_right() if keys[K_LEFT]: self.player.move_left() if keys[K_UP]: self.player.move_up() if keys[K_DOWN]: self.player.move_down() if keys[K_ESCAPE]: self._running = False self.on_loop() self.on_render() time.sleep(50.0 / 1000.0) self.on_cleanup()
class Environment: def __init__(self, draw=True, fps=10, debug=False): if draw: pygame.init() pygame.display.set_caption('NN Snake') self.font_game_over = pygame.font.SysFont("ani", 72) self.fps = fps self.debug = debug self.draw = draw self.clock = pygame.time.Clock() self.time_elapsed_since_last_action = 0 self.global_time = 0 self.screen = pygame.display.set_mode(SCREEN_SIZE) self.snake = Snake(self.screen, WIDTH, HEIGHT, SNAKE_COLOR, SCALE) self.apple = Apple(self.screen, WIDTH, HEIGHT, APPPLE_COLOR, SCALE) # self.bird = Bird(self.screen, WIDTH, HEIGHT, BIRD_COLOR) # self.pipes = [Pipe(self.screen, WIDTH, HEIGHT, PIPE_COLOR, self.pipe_image, self.pipe_long_image)] self.reward = 0 self.is_done = False self.printed_score = False # ML INTERFACE ################################################################################## def reset(self): self.clock = pygame.time.Clock() self.time_elapsed_since_last_action = 0 self.global_time = 0 # self.bird = Bird(self.screen, WIDTH, HEIGHT, BIRD_COLOR) # self.pipes = [Pipe(self.screen, WIDTH, HEIGHT, PIPE_COLOR, self.pipe_image, self.pipe_long_image)] self.reward = 0 self.is_done = False self.printed_score = False # lol no premium action, why did i write that ? obs, reward, is_done, _ = self.step_buffer(0) return obs def step(self, action): while not self.time_elapsed_since_last_action > self.fps: dt = self.clock.tick() self.time_elapsed_since_last_action += dt self.global_time += 1 return self.run_ai_game_step(action) def step_buffer(self, action): obs = [] rew = 0 for i in range(BUFFER_SIZE): while not self.time_elapsed_since_last_action > self.fps: dt = self.clock.tick() self.time_elapsed_since_last_action += dt self.global_time += 1 o, r, d, _ = self.run_ai_game_step(action) rew += r for j in range(len(o)): obs.append(o[j]) if rew > 1: rew = 1 elif rew < -1: rew = -1 else: rew = 0.1 return obs, rew, d, _ # The actual game step ########################################################################## def run_ai_game_step(self, action): current_reward = 0.1 # snake logic self.snake.handle_events_human() self.snake.update() if self.draw: self.screen.fill(BACKGROUND) self.snake.draw() text = pygame.font.SysFont(FONT, 28).render( "SCORE {}".format(self.reward), True, (0, 0, 0)) self.screen.blit(text, (565 - text.get_width() // 2, 30 - text.get_height() // 2)) pygame.display.flip() obs = self.get_observation_space() if self.draw: pygame.display.update() self.time_elapsed_since_last_action = 0 return obs, current_reward, self.is_done, None ################################################################################################# def get_observation_space(self): obs = None return obs def get_action_random(self): action = np.random.choice((0, 1, 2, 3), 1, p=(0.25, 0.25, 0.25, 0.25)) return action.item(0) def get_observation_size(self): return OBSERVATION_SIZE def get_observation_size_buffer(self): return OBSERVATION_SIZE * BUFFER_SIZE def get_actions(self): return ACTIONS def get_action_size(self): return ACTION_SIZE def game_over(self): if not self.printed_score: print('Score: {}'.format(self.reward)) self.printed_score = True if self.draw: text = pygame.font.SysFont(FONT, 28).render( "Game Over!".format(self.reward), True, (0, 0, 0)) self.screen.blit(text, (320 - text.get_width() // 2, 240 - text.get_height() // 2)) pygame.display.flip() time.sleep(0.4) self.is_done = True # HUMAN STUFF ################################################ def run_human_game(self): while not self.is_done: while not self.time_elapsed_since_last_action > self.fps: dt = self.clock.tick() self.time_elapsed_since_last_action += dt self.global_time += 1 self.screen.fill(BACKGROUND) self.handle_events_human() # snake logic self.snake.handle_events_human() self.snake.update() if self.apple.eat(self.snake.x, self.snake.y): print('jjum') if self.draw: self.screen.fill(BACKGROUND) self.snake.draw() self.apple.draw() if self.draw: pygame.display.update() self.time_elapsed_since_last_action = 0 def handle_events_human(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.is_done = False pygame.quit()
def loop(self): #TIME clock = pygame.time.Clock() #INSTANCE board = Board(self.display) apple = Apple(self.display) snake = Snake(self.display) #ACTUAL GAMELOOP while True: path = astar(board.returnBoard(), snake.snake_pos(), apple.apple_Position()) print(path) for i in range(1, len(path)): #if next move is not orthogonal if snake.changeDirectionTo(snake.CoordinateToDirection( path[i])): path = astar(board.returnBoard(), snake.snake_pos(), apple.apple_Position()) for event in pygame.event.get(): if event.type == pygame.QUIT: print("exit pressed!") return 0 # DRAW BACKGROUND if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: snake.changeDirectionTo('UP') elif event.key == pygame.K_DOWN: snake.changeDirectionTo('DOWN') elif event.key == pygame.K_LEFT: snake.changeDirectionTo('LEFT') elif event.key == pygame.K_RIGHT: snake.changeDirectionTo('RIGHT') # MOVE SNAKE and record position of SNAKE snake.move() # Collision Detection if snake.collision(): return 0 #eating if snake.ate(apple.apple_Position()): self.score += 1 pygame.display.set_caption(GAME['CAPTION'] + str(self.score)) apple.randomize() #DRAW board.drawBoard(self.display, snake.snake_body(), apple.apple_Position()) apple.draw() snake.draw_body() #DRAW UPDATE pygame.display.update() clock.tick(GAME['FPS'])
class Game: ''' Esta clase contiene la lógica general del juego. ''' windowWidth = 800 windowHeight = 600 snake = 0 apple = 0 def __init__(self): self.running = True self.display_surf = None self.image_surf = None self.apple_surf = None self.snake = Snake(3) self.apple = Apple(5, 5) def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode( (self.windowWidth, self.windowHeight), pygame.HWSURFACE) pygame.display.set_caption( 'Snake Game') # Establecer el título de la pantalla self._running = True self._image_surf = pygame.image.load( "snake.png").convert() # Carga de la superficie de imagen snake self._apple_surf = pygame.image.load( "apple.png").convert() # Carga de la superficie de imagen apple def isCollision(self, x1, y1, x2, y2, size): if x1 >= x2 and x1 <= x2 + size: # Prueba si ocurre colisión en posiciones horizontales. if y1 >= y2 and y1 <= y2 + size: # Prueba si ocurre colisión en posiciones verticales. return True return False def on_event(self, event): if pygame.event.type == QUIT: self._running = False # Termina el juego def on_loop(self): self.snake.update() # Snake choca con los bordes if self.snake.x[0] < 0 or self.snake.x[ 0] > self.windowWidth or self.snake.y[0] < 0 or self.snake.y[ 0] > self.windowHeight: print("GAME OVER!") exit(0) # Snake come Apple? for i in range(0, self.snake.length): if self.isCollision(self.apple.x, self.apple.y, self.snake.x[i], self.snake.y[i], 20): self.apple.x = randint(2, 9) * 44 self.apple.y = randint(2, 9) * 44 self.snake.length = self.snake.length + 1 # Snake se come a ella? for i in range(2, self.snake.length): if self.isCollision(self.snake.x[0], self.snake.y[0], self.snake.x[i], self.snake.y[i], 20): print("GAME OVER!") exit(0) def on_render(self): self._display_surf.fill((0, 0, 0)) self.snake.draw(self._display_surf, self._image_surf) self.apple.draw(self._display_surf, self._apple_surf) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False while (self._running): pygame.event.pump() keys = pygame.key.get_pressed() # Presionando las teclas if (keys[pygame.K_RIGHT]) and not self.snake.direction == 1: self.snake.moveRight() elif (keys[pygame.K_LEFT]) and not self.snake.direction == 0: self.snake.moveLeft() elif (keys[pygame.K_UP]) and not self.snake.direction == 3: self.snake.moveUp() elif (keys[pygame.K_DOWN]) and not self.snake.direction == 2: self.snake.moveDown() elif (keys[pygame.K_ESCAPE]): self._running = False self.on_loop() self.on_render() time.sleep(50.0 / 1000.0) self.on_cleanup()
class Game: screen = None clock = None def __init__(self): self.title = "Snake" self.board_size = 600 # its always a square self.cell_size = 40 self.board_color = Color.BLACK.value self.has_grid = True self.grid_color = Color.GRAY.value self.speed = 10 self.pause = 2 self.running = True # Score self.score = 0 self.score_font = "bahnschrift" self.score_size = 30 self.score_color = Color.GREEN.value self.score_position = (self.board_size - 4 * self.cell_size, self.cell_size) self.score_text = 'Score: ' # Game over self.game_over_font = "bahnschrift" self.game_over_size = 120 self.game_over_color = Color.GREEN.value self.game_over_position = (self.board_size // 6, self.board_size // 4) self.game_over_text = 'Game Over' self.snake = Snake(self.board_size, self.cell_size) self.apple = Apple(self.board_size, self.cell_size) self.apple.random_position() def boundaries_collision(self): snake_head = self.snake.head() return snake_head[0] == self.board_size or snake_head[1] == self.board_size or \ snake_head[0] < 0 or snake_head[1] < 0 def eat(self): return self.snake.head()[0] == self.apple.position()[0] and \ self.snake.head()[1] == self.apple.position()[1] def draw_grid(self): for i in range(0, self.board_size, self.cell_size): # Draw vertical lines pygame.draw.line(self.screen, self.grid_color, (i, 0), (i, self.board_size)) for i in range(0, self.board_size, self.cell_size): # Draw horizontal lines pygame.draw.line(self.screen, self.grid_color, (0, i), (self.board_size, i)) def draw_score(self): score_font = pygame.font.SysFont(self.score_font, self.score_size) text = score_font.render(self.score_text + str(self.score), True, self.score_color) self.screen.blit(text, self.score_position) def game_over(self): print("GO") font = pygame.font.SysFont(self.game_over_font, self.game_over_size) text = font.render(self.game_over_text, True, self.game_over_color) self.screen.blit(text, self.game_over_position) pygame.display.update() time.sleep(self.pause) exit() def run(self): pygame.init() self.screen = pygame.display.set_mode( (self.board_size, self.board_size)) pygame.display.set_caption(self.title) self.clock = pygame.time.Clock() while self.running: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() exit() if event.type == KEYDOWN: if event.key == K_UP and self.snake.direction != Direction.DOWN: self.snake.move_up() if event.key == K_RIGHT and self.snake.direction != Direction.LEFT: self.snake.move_right() if event.key == K_DOWN and self.snake.direction != Direction.UP: self.snake.move_down() if event.key == K_LEFT and self.snake.direction != Direction.RIGHT: self.snake.move_left() if self.eat(): self.apple.random_position() self.snake.grow() self.score += 1 if self.boundaries_collision(): self.game_over() if self.snake.self_collision(): self.game_over() self.snake.crawl() self.screen.fill(self.board_color) if self.has_grid: self.draw_grid() self.apple.draw(self.screen) self.snake.draw(self.screen) self.draw_score() pygame.display.update() self.clock.tick(self.speed)
class Game: ''' This class contain the general game logic. ''' windowWidth = 800 windowHeight = 600 snake = 0 apple = 0 def __init__(self): self._running = True self._display_surf = None self._image_surf = None self._apple_surf = None self.snake = Snake(3) self.apple = Apple(5,5) def on_init(self): pygame.init(); self._display_surf = pygame.display.set_mode((self.windowWidth, self.windowHeight), pygame.HWSURFACE) # Criating the display surface pygame.display.set_caption('Snake Game - Pygame') # Setting the display title self._running = True self._image_surf = pygame.image.load("images/snake.png").convert() # Loading the snake image surface self._apple_surf = pygame.image.load("images/apple.png").convert() # Loading the apple image surface def isCollision(self, x1, y1, x2, y2, size): if x1 >= x2 and x1 <= x2 + size: # Testing if ocurrs collision on horizontal positions if y1 >= y2 and y1 <= y2 + size: # Testing if ocurrs collision on vertical positions return True return False def on_event(self, event): if pygame.event.type == QUIT: self._running = False # Shutdown the game def on_loop(self): self.snake.update() # Snake hits the bords if self.snake.x[0] < 0 or self.snake.x[0] > self.windowWidth or self.snake.y[0] < 0 or self.snake.y[0] > self.windowHeight: print("You lose!") exit(0) # Snake eats the apple? for i in range(0,self.snake.length): if self.isCollision(self.apple.x,self.apple.y,self.snake.x[i], self.snake.y[i],20): self.apple.x = randint(2,9) * 44 self.apple.y = randint(2,9) * 44 self.snake.length = self.snake.length + 1 # Snake eats itself? for i in range(2,self.snake.length): if self.isCollision(self.snake.x[0], self.snake.y[0], self.snake.x[i], self.snake.y[i],20): print("You lose!") exit(0) def on_render(self): self._display_surf.fill((0,0,0)) self.snake.draw(self._display_surf, self._image_surf) self.apple.draw(self._display_surf, self._apple_surf) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False while( self._running ): pygame.event.pump() keys = pygame.key.get_pressed() # Getting the keys pressed if (keys[pygame.K_RIGHT]) and not self.snake.direction == 1: self.snake.moveRight() elif (keys[pygame.K_LEFT]) and not self.snake.direction == 0: self.snake.moveLeft() elif (keys[pygame.K_UP]) and not self.snake.direction == 3: self.snake.moveUp() elif (keys[pygame.K_DOWN]) and not self.snake.direction == 2: self.snake.moveDown() elif (keys[pygame.K_ESCAPE]): self._running = False self.on_loop() self.on_render() time.sleep (50.0 / 1000.0); self.on_cleanup()
class Game: def __init__(self): # Config # tps = ticks per second self.tps_max = 50.0 self.screen_width = 800 self.screen_height = 600 # Initialization pygame.init() self.screen = pygame.display.set_mode((self.screen_width, self.screen_height)) pygame.display.set_caption('Snake by Max') self.tps_clock = pygame.time.Clock() self.tps_delta = 0.0 self.player = Player(3) self.apple = Apple(5,5) self.collision = Collision() while True: # Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit(0) # Ticking self.tps_delta += self.tps_clock.tick() / 1000.0 while self.tps_delta > 1 / self.tps_max: self.tick() self.tps_delta -= 1 / self.tps_max # Drawing self.screen.fill((0, 0, 0)) self.player.draw(self.screen) self.apple.draw(self.screen) pygame.display.flip() def tick(self): # Checking inputs keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.player.moveLeft() elif keys[pygame.K_RIGHT]: self.player.moveRight() elif keys[pygame.K_UP]: self.player.moveUp() elif keys[pygame.K_DOWN]: self.player.moveDown() self.player.update() # does snake eat apple? for i in range(0, self.player.length): if self.collision.isCollision(self.apple.x, self.apple.y, self.player.x[i], self.player.y[i], 50): self.apple.x = randint(1, 14) * 50 self.apple.y = randint(1, 10) * 50 self.player.length = self.player.length + 1 # does snake collide with itself? for i in range(2, self.player.length): if self.collision.isCollision(self.player.x[0], self.player.y[0], self.player.x[i], self.player.y[i], 40): print("You lose! Collision: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") print("x[" + str(i) + "] (" + str(self.player.x[i]) + "," + str(self.player.y[i]) + ")") exit(0)
class App: windowWidth = 800 windowHeight = 600 player = 0 apple = 0 def __init__(self): self._running = True self._display_surf = None self._image_surf = None self._apple_surf = None # self._wall_surf = None self.game = Game() self.player = Player self.apple = Apple(5, 5) # self.wall = Wall def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode( (self.windowWidth, self.windowHeight), pygame.HWSURFACE) pygame.display.set_caption('Pygame pythonspot.com example') self._running = True self._image_surf = pygame.image.load("block.jpg").convert() self._apple_surf = pygame.image.load("apple.jpg").convert() # self._wall_surf = pygame.image.load("apple.jpg").convert() def on_event(self, event): if event.type == QUIT: self._running = False def on_loop(self): self.player.update # does snake eat apple? print("Length = " + str(self.player.length)) for i in range(1, self.player.length - 1): print(self.player.x) if self.game.isCollision(self.apple.x, self.apple.y, self.player.x[i], self.player.y[i], 40): self.apple.x = randint(2, 9) * 50 self.apple.y = randint(2, 9) * 50 self.player.length = self.player.length + 1 # does snake collide with itself? for i in range(1, self.player.length - 1): if self.game.isCollision(self.player.x[0], self.player.y[0], self.player.x[i], self.player.y[i], 40): print("You lose! Collision: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") print("x[" + str(i) + "] (" + str(self.player.x[i]) + "," + str(self.player.y[i]) + ")") exit(0) pass def on_render(self): self._display_surf.fill((0, 0, 0)) self.player.draw(self._display_surf, self._image_surf) self.apple.draw(self._display_surf, self._apple_surf) # self.wall.draw(self._display_surf, self._wall_surf) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False while (self._running): pygame.event.pump() keys = pygame.key.get_pressed() if (keys[K_RIGHT]): self.player.moveRight() if (keys[K_LEFT]): self.player.moveLeft() if (keys[K_UP]): self.player.moveUp() if (keys[K_DOWN]): self.player.moveDown() if (keys[K_ESCAPE]): self._running = False self.on_loop() self.on_render() time.sleep(50.0 / 1000.0) self.on_cleanup()
class Game: """"Game class contains the Snake and Apple and defines the game rules. It also calculates the inputs for the neural network and updates the fitness of the snake along the game.""" def __init__(self, parent_screen, parameters=None): self.surface = parent_screen self.seed = random.randint(999999) self.snake = Snake(self.surface, parameters, initial_pos=(BOARD_SIZE[0] // 2, BOARD_SIZE[1] // 2)) self.apple = Apple(self.surface, self.seed) self.last_distance = 0 self.game_over = False def reset(self): self.snake.reset((BOARD_SIZE[0] // 2, BOARD_SIZE[1] // 2)) self.apple = Apple(self.surface, self.seed) self.last_distance = 0 self.game_over = False def get_apple_vision(self): delta_x = self.apple.x - self.snake.x[0] delta_y = self.apple.y - self.snake.y[0] return delta_x, delta_y def get_wall_vision(self): left_vision = self.snake.x[0] up_vision = self.snake.y[0] right_vision = (BOARD_SIZE[0] - 1) - self.snake.x[0] down_vision = (BOARD_SIZE[1] - 1) - self.snake.y[0] return left_vision, up_vision, right_vision, down_vision def get_body_vision(self): pass def get_inputs(self): return self.get_apple_vision() + (0, 0, 0, 0 ) # + self.get_wall_vision() def update_fitness(self): distance = get_distance(self.apple.x, self.apple.y, self.snake.x[0], self.snake.y[0]) if distance < self.last_distance: self.snake.fitness += 1 else: self.snake.fitness -= 1 self.last_distance = distance def move_apple(self): # TODO: get all available spaces and then choose one of them at random apple_in_snake = True while apple_in_snake: self.apple.move() apple_in_snake = False for i in range(self.snake.length): if is_collision(self.apple.x, self.apple.y, self.snake.x[i], self.snake.y[i]): apple_in_snake = True break def play(self): # move snake: inputs = self.get_inputs() self.snake.process_inputs(inputs) self.snake.move() # check if snake ran out of energy: if self.snake.energy < 0: self.game_over = True # check if snake collides with itself: for i in range(3, self.snake.length): if is_collision(self.snake.x[0], self.snake.y[0], self.snake.x[i], self.snake.y[i]): self.game_over = True # check if snake is out of board: if self.snake.x[0] < 0 or \ self.snake.x[0] >= BOARD_SIZE[0] or \ self.snake.y[0] < 0 or \ self.snake.y[0] >= BOARD_SIZE[1]: self.game_over = True # check if snake collides with apple: if is_collision(self.apple.x, self.apple.y, self.snake.x[0], self.snake.y[0]): # increase fitness: self.snake.fitness += 100 + self.snake.energy * 2 # snake hits maximum length if self.snake.length >= BOARD_SIZE[0] * BOARD_SIZE[1]: self.game_over = True # self.snake.increase() self.snake.reset_energy() self.move_apple() self.update_fitness() def draw(self): self.snake.draw() self.apple.draw()