def __init__(self, nw_tile, nh_tile): self.nw_tile = nw_tile # Set number of tile in x self.nh_tile = nh_tile # Set number of tile in y self.number_body = 3 # Set number of snake's body self.score = 0 # Set score of sanke self.db_save_size = 6 # Column size of data base self.id = 0 # index of database's column self.type = 1 self.x = 2 self.y = 3 self.s = 4 self.t = 5 self.enemy_dict = {} # Enemy snake dictionary self.client_state_dict = { 'OK': 0, 'notNStart': 1, 'notNExit': 2 } # KList state of client self.client_state = self.client_state_dict[ 'notNStart'] # State of cleint self.play_state = False # Playing state self.game_time = 0 # time of game self.tile_mng = TileManager(width, height, self.nw_tile, self.nh_tile) # Set TileManager self.snake = Snake(1, 1, self.tile_mng, green, SNAKE, raw_input("Enter : "), self.number_body) # Set my sanke self.apple = Apple(0, 0, self.tile_mng, red, 0) # Set apple self.hud = HUD() # Set HUD
def resetGame(mySnake): # Recreate Level 1 nibble.level = 1 global currentLevel currentLevel = Level(1, nibble.total_columns, nibble.total_lines) # Draw level nibble.drawLevel(currentLevel) # Zero out total score nibble.score = 0 # Reset snake's attributes mySnake.resetSnake(nibble.center_x, nibble.center_y) mySnake.lives = 3 # Zero the apples eaten global apples_eaten apples_eaten = 0 # Show the first Apple global apple apple = Apple(nibble.total_columns, nibble.total_lines, currentLevel, mySnake) pygame.draw.rect( nibble.screen, (0, 255, 0), pygame.Rect(apple.getX(), apple.getY(), mySnake.size, mySnake.size), 0)
def eat(self): self.apple = Apple() self.gen_not_in_tail() self.time_left += 100 self.grow()
def __init__(self): # Snake attributes self.x_start = PLAYABLE_AREA_WIDTH / 2 self.y_start = PLAYABLE_AREA_HEIGHT / 2 self.len = 1 self.is_alive = True self.time_left = 200 self.life_time = 0 self.score = 0 # Create vector of position and velocity self.head = Vector(self.x_start, self.y_start) # actual position self.vel = Vector(RIGHT_VECTOR.x, RIGHT_VECTOR.y) # Init snake with 4 body segments self.tail = [] self.tail.append(Vector(self.x_start - 30, self.y_start)) # Add last segment of body self.tail.append(Vector(self.x_start - 20, self.y_start)) # Add second segment of body self.tail.append(Vector(self.x_start - 10, self.y_start)) # Add first segment of body self.len += 3 # Increase a body length # Vision for input self.visions = [Vision() for _ in range(8)] self.visions_array = [] # Get DNA as snake's brain self.DNA = NeuralNetwork(INPUT_NODES, HIDDEN_NODES, OUTPUT_NODES) self.apple = Apple()
def __init__(self): self.score = 0 self.snake = Snake(SCREEN_SIZE[0] // 2, SCREEN_SIZE[1] // 2) self.apple = Apple() self.apple.placeApple(self.snake.getBody(), SCREEN_SIZE[0], SCREEN_SIZE[1]) self.scorePosX = SCREEN_SIZE[0] // 2 - 10 self.eatingSound = pygame.mixer.Sound('Eating.ogg')
def __init__(self): self._display_surf = None self._image_surf = None self._apple_surf = None self._running = True self.board = Board(self.windowWidth, self.windowHeight) self.player = Player(3) self.apple = Apple(5,5)
def load(self): self.boundary = Boundary(self.screen, 0, 0) snake_position_x, snake_position_y = self.random_position() self.snake = Snake(self.screen, snake_position_x, snake_position_y) apple_position_x, apple_position_y = self.random_position() self.apple = Apple(self.screen, apple_position_x, apple_position_y) self.collision = Collision(self.boundary.get_boundaries())
def main(): # create fruit fr1 = Fruit("Pear", 3.0, 3.0) fr1.toString() print() # create a parametrized apple ap1 = Apple(5.0, 2.0, 'Gala', False) ap1.toString()
def restart(self, autostart=False): self.score = 0 self.snake = Snake() self.apple = Apple() self.stopped = not autostart # game not running (no steps made) self.finished = False # game is done and can't be resumed self.didRestart = True self.speed = SConfig.speed self.uiInstrText = 'press <SPACE> to start'
def eat_apple(self): is_collider, object_collider = self.collision.check_collision( self.snake) if self.collision.object_colision(self.snake, self.apple): del self.apple new_x, new_y = self.random_position() self.apple = Apple(self.screen, new_x, new_y) self.snake.grow_body(self.snake.get_position()[0], self.snake.get_position()[1])
def __init__(self, cnx=None): self._running = True self._displaySurface = None self._snakeHeadImageSurface = None self._snakeBodyImageSurface = None self._appleImageSurface = None #self._borderImageSurface = None self.thePlayer = SnakeHead() self.apple = Apple() self.cnx = cnx
class ExperimentalScene(Scene): def __init__(self, screen, id=0): super().__init__(screen, id) def load(self): self.boundary = Boundary(self.screen, 0, 0) snake_position_x, snake_position_y = self.random_position() self.snake = Snake(self.screen, snake_position_x, snake_position_y) apple_position_x, apple_position_y = self.random_position() self.apple = Apple(self.screen, apple_position_x, apple_position_y) self.collision = Collision(self.boundary.get_boundaries()) def random_position(self): x = random.randint(21, 379) y = random.randint(21, 379) return x, y def draw(self): self.boundary.draw() self.apple.draw() self.snake.draw_snake() def limit_movements(self): is_collider, object_collider = self.collision.check_collision( self.snake) if object_collider == self.boundary.horizontal_bar_left.get_rectangule( ): self.snake.update(25, 0, 25, -25) elif object_collider == self.boundary.horizontal_bar_right.get_rectangule( ): self.snake.update(0, -25, 25, -25) elif object_collider == self.boundary.vertical_bar_botton.get_rectangule( ): self.snake.update(25, -25, 0, -25) elif object_collider == self.boundary.vertical_bar_top.get_rectangule( ): self.snake.update(25, -25, 25, 0) else: self.snake.update(25, -25, 25, -25) def eat_apple(self): is_collider, object_collider = self.collision.check_collision( self.snake) if self.collision.object_colision(self.snake, self.apple): del self.apple new_x, new_y = self.random_position() self.apple = Apple(self.screen, new_x, new_y) self.snake.grow_body(self.snake.get_position()[0], self.snake.get_position()[1]) def update(self): self.limit_movements() self.eat_apple()
def __init__(self): pygame.init() pygame.display.set_caption("ugly snake ") pygame.mixer.init() self.play_backround_music() self.surface = pygame.display.set_mode((DX, DY)) self.surface.fill((255, 255, 255)) self.snake = Snake(self.surface, 1) self.snake.draw() self.apple = Apple(self.surface) self.apple.draw()
class GameEngine: def __init__(self): print("Game engine") pygame.init() self.screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("Snake challenge") # Fill background with black self.background = pygame.Surface(self.screen.get_size()) self.background = self.background.convert() self.background.fill((0, 0, 0)) self.running = True self.apple = Apple() self.snake = Snake() # Starting point of the game def start(self): clock = pygame.time.Clock() # Simplefied Game loop while self.running: clock.tick(50) self.handle_events() self.update() self.render() # Call rendering for all game objects def render(self): # Clear the screen self.screen.blit(self.background, (0, 0)) # Render objects self.apple.render() self.snake.render() # Update screen pygame.display.flip() # Call updates on all game objects def update(self): self.apple.update() self.snake.update(self.apple) # Handle events such as key presses or exits def handle_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False else: self.snake.handle_event(event)
def __init__(self): # tiles and pixels self._nb_tile_x = ConstantVariables.NB_COLUMN self._nb_tile_y = ConstantVariables.NB_ROW # elements self._snakes = [] self._apple = Apple(self._nb_tile_x - 1, self._nb_tile_y - 1) # other self._running = True
class test_Apple(unittest.TestCase): def setUp(self): self.myobject = Apple() def test_get_apple(self): self.assertEquals(self.myobject.get_apple(), 'apple') def test_get_apple_failing(self): self.assertEquals(self.myobject.get_apple(), 'APPLE') def test_get_apple_correct_failingcast(self): self.assertEquals(self.myobject.get_apple(), 'APPLE'.lower())
def game_loop(self): """The game loop for 1 player mode""" snake_length = 6 snake = Snake(snake_length, color=GREEN, game=self) apple = Apple(APPLE_SIZE, game=self) def game_reset(): nonlocal snake, apple snake = Snake(snake_length, color=GREEN, game=self) apple = Apple(APPLE_SIZE, game=self) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: self.game_exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and snake.direction != 'RIGHT' and not snake.turned: snake.started = True snake.turned = True snake.turn('LEFT') elif event.key == pygame.K_RIGHT and snake.direction != 'LEFT' and not snake.turned: snake.started = True snake.turned = True snake.turn('RIGHT') elif event.key == pygame.K_UP and snake.direction != 'DOWN' and not snake.turned: snake.started = True snake.turned = True snake.turn('UP') elif event.key == pygame.K_DOWN and snake.direction != 'UP' and not snake.turned: snake.started = True snake.turned = True snake.turn('DOWN') if snake.hit_wall() or snake.hit_tail(): self.show_score(snake, game_reset) self.display.fill(WHITE) pygame.draw.rect(self.display, BLACK, [0, self.height, self.width, PANEL_HEIGHT]) self.message("Score: " + str(snake.score), RED, h_align='left', v_align='bottom', off_set_y=20) apple.draw() snake.draw() if snake.started: snake.go() snake.turned = False pygame.display.update() if snake.eat(apple): apple = Apple(APPLE_SIZE, game=self) CLOCK.tick(FPS)
def __init__(self): self.width = 600 self.height = 600 self.player = Player() self.block = 10 self.background = (0, 0, 0) pygame.init() self.screen = pygame.display.set_mode((self.width, self.height)) self.running = True self.clock = pygame.time.Clock() self.apple = Apple() self.active = False Tk().wm_withdraw()
def __init__(self): self.snake = Snake() self.apple = Apple() self.addedWidth = 0 self.snakeMovSpeed = 2*SNAKE_WITH_HALH+1 # min = 2 self.eatenAppleCount = 0 self.GenNewApple()
def __init__(self, size): self.size = size self.snake = Snake(self) self.apple = Apple(self) self.board = Board(self) self.board.updateBoard() self.keyListener = Listener(on_press=self.on_press) self.isGameRunning = True
class GameServer: def __init__(self): # tiles and pixels self._nb_tile_x = ConstantVariables.NB_COLUMN self._nb_tile_y = ConstantVariables.NB_ROW # elements self._snakes = [] self._apple = Apple(self._nb_tile_x - 1, self._nb_tile_y - 1) # other self._running = True @property def snakes(self): return self._snakes @property def apple(self): return self._apple def create_snake(self, id_client): coordinate_not_free = [] for snake in self._snakes: coordinate_not_free.append(snake.get_head_coordinate()) for part_snake in snake.body_coordinates: coordinate_not_free.append(part_snake) coordinate_not_free.append(self.apple.get_coordinate()) self._snakes.append(Snake(id_client, self._nb_tile_x, self._nb_tile_y, coordinate_not_free)) def start(self): self.create_new_apple() def is_apple_caught(self, snake): return self._apple.x == snake.head_x and self._apple.y == snake.head_y def create_new_apple(self): apple_coord = self._apple.get_coordinate() all_coord_snake = [] for snake in self._snakes: all_coord_snake.append(snake.get_head_coordinate()) all_coord_snake.append(snake.body_coordinates) while apple_coord in all_coord_snake: self._apple.set_new_coordinates(self._nb_tile_x - 1, self._nb_tile_y - 1) apple_coord = self._apple.get_coordinate()
def resetLevel(mySnake): # Recreate Level 1 global currentLevel currentLevel = Level(nibble.level,nibble.total_columns,nibble.total_lines) # Draw level nibble.drawLevel(currentLevel) # Reset snake's attributes mySnake.resetSnake(nibble.center_x,nibble.center_y) # Zero the apples eaten global apples_eaten apples_eaten = 0 # Show the first Apple global apple apple = Apple(nibble.total_columns,nibble.total_lines,currentLevel,mySnake) pygame.draw.rect(nibble.screen, (0,255, 0), pygame.Rect(apple.getX(), apple.getY(), mySnake.size, mySnake.size),0)
def __init__(self, window_width, window_height): # tiles and pixels self._nb_tile_x = 60 self._tile_width = floor(window_width / self._nb_tile_x) self._width_px = self._tile_width * self._nb_tile_x self._nb_tile_y = floor(window_height / self._tile_width) self._height_px = self._tile_width * self._nb_tile_y # elements # screen self._screen = pygame.display.set_mode((self._width_px, self._height_px)) self._background = pygame.image.load('../assets/grass.jpg') self._background = pygame.transform.scale(self._background, (self._width_px, self._height_px)) # objects self._snake = Snake(self._nb_tile_x, self._nb_tile_y, self._tile_width) self._apple = Apple(self._nb_tile_x - 1, self._nb_tile_y - 1, self._tile_width) # other self._running = True
def on_init(self): self._running = True cols = 50 rows = 50 mapSizeX = 700 mapSizeY = 700 imageSize = (int(mapSizeX / cols), int(mapSizeY / rows)) self.map = Map(50, 50, mapSizeX, mapSizeY, cols, rows, self.headless) self.snake = Snake(cols / 2, rows / 2, imageSize, self.headless) self.apple = Apple(cols, rows, imageSize, self.headless) if self.bot: self.bot.AddGoal(self.apple) self.bot.AddBody(self.snake) self.bot.AddMap(self.map) if not self.headless: pygame.display.set_caption("Snake") self._display_surf = pygame.display.set_mode( self.size, pygame.DOUBLEBUF) self.font = pygame.font.SysFont('mono', 14, bold=True) self.fontEndscore = pygame.font.SysFont('mono', 32, bold=True)
def __init__(self): print("Game engine") pygame.init() self.screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("Snake challenge") # Fill background with black self.background = pygame.Surface(self.screen.get_size()) self.background = self.background.convert() self.background.fill((0, 0, 0)) self.running = True self.apple = Apple() self.snake = Snake()
def getNewApple(self): retry = True while retry: retry = False x = randrange(self.width) y = randrange(self.height) for b in self.player.body: if b.x == x and b.y == y: retry = True break if retry: continue self.apple = Apple(x, y) if self.isAI: self.moves = self.setMove()
def __init__(self, width, height, occurrences, ai, shortest, display_moves): self.occurrences = occurrences self.player = Snake() # Instanciate a dummy apple self.apple = Apple(0, 1) self.width = width self.height = height self.isAI = ai print(self.isAI) self.moves = None self.score = 0 self.scores = [] self.display_moves = display_moves self.shortest = shortest if ai: self.moves = self.setMove() self.getNewApple()
def run(self): play_btn = Button(self.load_screen.win, RETRO_BLUE, 0.106125 * WIDTH, 0.702 * HEIGHT, size=100, on_click=self.check_play_screen, btn_text="Play") self.load_screen.add_game_object("play_btn", (10, play_btn)) exit_btn = Button(self.load_screen.win, RETRO_BLUE, 0.76375 * WIDTH, 0.702 * HEIGHT, size=100, on_click=self.exit_trigger, btn_text="Exit") self.load_screen.add_game_object("exit_btn", (11, exit_btn)) settings_btn = Button(self.load_screen.win, RETRO_BLUE, 0.39625 * WIDTH, 0.702 * HEIGHT, size=100, on_click=None, btn_text="Settings") self.load_screen.add_game_object("settings_btn", (12, settings_btn)) snake = Snake(self.play_screen.win) self.play_screen.add_game_object("snake", (10, snake)) score_box = TextBox(self.play_screen.win, NEON_YELLOW, 650, 100, "fonts/true-crimes.ttf", "Score: ", 50) self.play_screen.add_game_object("score_box", (8, score_box)) apple = Apple(self.play_screen.win, RETRO_PINK, 28) self.play_screen.add_game_object("apple", (9, apple)) while True: self.active_screen.screen_update()
def __init__(self, name, weight, last_day, price, can_discount): Apple.__init__(self, name, weight, last_day, 100) self.can_discount = can_discount
def loop(self, screen): screen.blit(self.text, self.textRect) screen.blit(self.text2, self.textRect2) clock = pygame.time.Clock() self.snake = Snake(self.display, -(Config['snake']['width'])) self.snake2 = Snake(self.display, (Config['snake']['width'])) apple = Apple(self.display) ai = Ai() x_change = Config['snake']['speed'] y_change = 0 x_change2 = -Config['snake']['speed'] y_change2 = 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and x_change == 0: x_change = -Config['snake']['speed'] y_change = 0 elif event.key == pygame.K_RIGHT and x_change == 0: x_change = Config['snake']['speed'] y_change = 0 elif event.key == pygame.K_UP and y_change == 0: x_change = 0 y_change = -Config['snake']['speed'] elif event.key == pygame.K_DOWN and y_change == 0: x_change = 0 y_change = Config['snake']['speed'] if event.key == pygame.K_a and x_change2 == 0: x_change2 = -Config['snake']['speed'] y_change2 = 0 elif event.key == pygame.K_d and x_change2 == 0: x_change2 = Config['snake']['speed'] y_change2 = 0 elif event.key == pygame.K_w and y_change2 == 0: x_change2 = 0 y_change2 = -Config['snake']['speed'] elif event.key == pygame.K_s and y_change2 == 0: x_change2 = 0 y_change2 = Config['snake']['speed'] snake_rect = self.snake.draw(Config['colors']['blue']) snake_rect2 = self.snake2.draw(Config['colors']['green']) apple_rect = apple.draw() ai.update(pos=(snake_rect[0], snake_rect[1]), apple=(apple_rect[0], apple_rect[1]), size=self.snake.max_size) move = ai.action() bumper_x = Config['game']['width'] - Config['game']['bumper_size'] bumper_y = Config['game']['height'] - Config['game']['bumper_size'] if apple_rect.colliderect(snake_rect): apple.remove() apple.randomize() self.snake.eat() elif apple_rect.colliderect(snake_rect2): apple.remove() apple.randomize() self.snake2.eat() snakehit = self.snake.hit(self.snake2.body, bumper_x, bumper_y) snakehit2 = self.snake2.hit(self.snake.body, bumper_x, bumper_y) if (snakehit or snakehit2): if (snakehit and snakehit2): print("Tie") elif snakehit: self.snake2.score += 1 self.player2score += 1 else: self.snake.score += 1 self.player1score += 1 apple.remove() # snake.remove() self.map(screen) self.loop(screen) self.snake.move(x_change, y_change) self.snake2.move(x_change2, y_change2) pygame.display.update() clock.tick(Config['game']['fps'])
def game_loop_2p(self): """Game loop for 2 player mode""" snake_length = 6 snake1 = Snake(snake_length, color=GREEN, game=self, name="Player 1") snake2 = Snake(snake_length, color=BLUE, game=self, img=SNAKE_HEAD_2, name="Player 2", offset_y=20) apple = Apple(APPLE_SIZE, game=self) def game_reset(): nonlocal snake1, snake2, apple snake1 = Snake(snake_length, color=GREEN, game=self, name="Player 1") snake2 = Snake(snake_length, color=BLUE, game=self, img=SNAKE_HEAD_2, name="Player 2", offset_y=20) apple = Apple(APPLE_SIZE, game=self) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: self.game_exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and snake1.direction != 'RIGHT' and not snake1.turned: snake1.turn('LEFT') elif event.key == pygame.K_RIGHT and snake1.direction != 'LEFT' and not snake1.turned: snake1.turn('RIGHT') elif event.key == pygame.K_UP and snake1.direction != 'DOWN' and not snake1.turned: snake1.turn('UP') elif event.key == pygame.K_DOWN and snake1.direction != 'UP' and not snake1.turned: snake1.turn('DOWN') elif event.key == pygame.K_a and snake2.direction != 'RIGHT' and not snake2.turned: snake2.turn('LEFT') elif event.key == pygame.K_d and snake2.direction != 'LEFT' and not snake2.turned: snake2.turn('RIGHT') elif event.key == pygame.K_w and snake2.direction != 'DOWN' and not snake2.turned: snake2.turn('UP') elif event.key == pygame.K_s and snake2.direction != 'UP' and not snake2.turned: snake2.turn('DOWN') self.display.fill(WHITE) pygame.draw.rect(self.display, BLACK, [0, self.height, self.width, PANEL_HEIGHT]) self.message("Score: " + str(snake1.score), GREEN, h_align='left', v_align='bottom', off_set_y=20) self.message("Score: " + str(snake2.score), BLUE, h_align='right', v_align='bottom', off_set_y=20) apple.draw() snake1.draw() snake2.draw() snake1.go() snake2.go() if snake1.hit_wall() or snake1.hit_tail(): snake1.die = True if snake2.hit_wall() or snake2.hit_tail(): snake2.die = True if snake1.die and snake2.die: self.show_score(snake1, snake2, game_reset) pygame.display.update() if snake1.eat(apple) or snake2.eat(apple): apple = Apple(APPLE_SIZE, game=self) CLOCK.tick(FPS)
def gen_not_in_tail(self): while self.apple.pos in self.tail: self.apple = Apple()
class State: def __init__(self): self.snake = Snake() self.apple = Apple() self.addedWidth = 0 self.snakeMovSpeed = 2*SNAKE_WITH_HALH+1 # min = 2 self.eatenAppleCount = 0 self.GenNewApple() def _IsAppleHitSnake(self): appleRect = self.apple.getRect() snakeRects = self.snake.GetBodyRects() for rect in snakeRects: if RectIntersect(rect, appleRect): return True return False def IncreaseMovSpeed(self): if self.eatenAppleCount % 10 == 0: #self.snakeMovSpeed += 2*SNAKE_WITH_HALH+1 pass def IsAppleEaten(self): appleRect = self.apple.getRect() snakeRects = self.snake.GetBodyRects() if RectIntersect(snakeRects[-1], appleRect): self.eatenAppleCount += 1 return True return False def GenNewApple(self): self.apple.SetApple() while self._IsAppleHitSnake(): self.apple.SetApple() def AddSnakeLen(self): self.addedWidth += APPLE_WIDTH def ResetSnake(self): self.snake.Reset() self.snakeMovSpeed = 2*SNAKE_WITH_HALH+1 def IsSnakeDead(self, state): return state.snake.IsDead() def __deepcopy__(self, memo): newState = copy.copy(self) newState.snake = copy.deepcopy(self.snake) newState.apple = copy.deepcopy(self.apple) return newState def GetNextState(self, d): nextState = copy.deepcopy(self) if nextState.addedWidth > 0: nextState.snake.GoDirection(d, nextState.snakeMovSpeed-nextState.addedWidth, nextState.snakeMovSpeed) nextState.addedWidth = 0 else: nextState.snake.GoDirection(d, self.snakeMovSpeed, self.snakeMovSpeed) return nextState
class Snake: def __init__(self): # Snake attributes self.x_start = PLAYABLE_AREA_WIDTH / 2 self.y_start = PLAYABLE_AREA_HEIGHT / 2 self.len = 1 self.is_alive = True self.time_left = 200 self.life_time = 0 self.score = 0 # Create vector of position and velocity self.head = Vector(self.x_start, self.y_start) # actual position self.vel = Vector(RIGHT_VECTOR.x, RIGHT_VECTOR.y) # Init snake with 4 body segments self.tail = [] self.tail.append(Vector(self.x_start - 30, self.y_start)) # Add last segment of body self.tail.append(Vector(self.x_start - 20, self.y_start)) # Add second segment of body self.tail.append(Vector(self.x_start - 10, self.y_start)) # Add first segment of body self.len += 3 # Increase a body length # Vision for input self.visions = [Vision() for _ in range(8)] self.visions_array = [] # Get DNA as snake's brain self.DNA = NeuralNetwork(INPUT_NODES, HIDDEN_NODES, OUTPUT_NODES) self.apple = Apple() # Based on len and life_time def calc_score(self): if self.len > 10: self.score = pow(self.life_time, 2) * pow(2, 10) * (self.len - 9) else: self.score = pow(self.life_time, 2) * pow(2, self.len) def is_on_tail(self, x: int, y: int) -> bool: for segment in self.tail: if segment.x == x and segment.y == y: return True return False def check_dir_and_get_vision(self, direction: Vector) -> Vision: vision = Vision() distance = 0 head_buff = Vector(self.head.x, self.head.y) # Move once head_buff.x += direction.x head_buff.y += direction.y distance += 1 # Looks in 8 direction and checks where's food, wall and body's segment while 0 <= head_buff.x <= PLAYABLE_AREA_WIDTH and 0 <= head_buff.y <= PLAYABLE_AREA_HEIGHT: if head_buff.x == self.apple.pos.x and head_buff.y == self.apple.pos.y: vision.is_apple = 1 if self.is_on_tail(head_buff.x, head_buff.y): vision.tail_dist = 1 / distance head_buff.x += direction.x head_buff.y += direction.y distance += 1 vision.wall_dist = 1 / distance return vision # Get input to determine v def set_input(self): self.visions[0] = self.check_dir_and_get_vision(LEFT_VECTOR) self.visions[1] = self.check_dir_and_get_vision(UP_VECTOR) self.visions[2] = self.check_dir_and_get_vision(RIGHT_VECTOR) self.visions[3] = self.check_dir_and_get_vision(DOWN_VECTOR) self.visions[4] = self.check_dir_and_get_vision(LEFT_UP_VECTOR) self.visions[5] = self.check_dir_and_get_vision(RIGHT_UP_VECTOR) self.visions[6] = self.check_dir_and_get_vision(RIGHT_DOWN_VECTOR) self.visions[7] = self.check_dir_and_get_vision(LEFT_DOWN_VECTOR) self.visions_array = self.visions_to_array() def visions_to_array(self): array = [] for vision in self.visions: array.append(vision.is_apple) array.append(vision.tail_dist) array.append(vision.wall_dist) return array # Set v from output def set_velocity(self): output_array = self.DNA.get_output(self.visions_array) max_idx = self.find_max_val_index(output_array) # Set direction if max_idx == 0 and self.vel.x != RIGHT_VECTOR.x and self.vel.y != RIGHT_VECTOR.y: self.vel.x = LEFT_VECTOR.x self.vel.y = LEFT_VECTOR.y elif max_idx == 1 and self.vel.x != DOWN_VECTOR.x and self.vel.y != DOWN_VECTOR.y: self.vel.x = UP_VECTOR.x self.vel.y = UP_VECTOR.y elif max_idx == 2 and self.vel.x != LEFT_VECTOR.x and self.vel.y != LEFT_VECTOR.y: self.vel.x = RIGHT_VECTOR.x self.vel.y = RIGHT_VECTOR.y elif max_idx == 3 and self.vel.x != UP_VECTOR.x and self.vel.y != UP_VECTOR.y: self.vel.x = DOWN_VECTOR.x self.vel.y = DOWN_VECTOR.y @staticmethod def find_max_val_index(array: list) -> int: return array.index(max(array)) def check_if_dies(self) -> bool: if self.head.x + self.vel.x >= PLAYABLE_AREA_WIDTH or self.head.x + self.vel.x < 0 or\ self.head.y + self.vel.y < 0 or self.head.y + self.vel.y >= PLAYABLE_AREA_HEIGHT: return True return False def check_if_eats(self): if self.head.x + self.vel.x == self.apple.pos.x and self.head.y + self.vel.y == self.apple.pos.y: return True return False def grow(self): new_segment = Vector(self.head.x, self.head.y) self.tail.append(new_segment) self.len += 1 def gen_not_in_tail(self): while self.apple.pos in self.tail: self.apple = Apple() def eat(self): self.apple = Apple() self.gen_not_in_tail() self.time_left += 100 self.grow() def move(self): # Change attributes to determine fitness self.life_time += 1 self.time_left -= 1 if self.check_if_dies() or self.is_on_tail( self.head.x + self.vel.x, self.head.y + self.vel.y) or self.time_left < 0: self.is_alive = False return self.clear_snake() pygame.draw.rect(DISPLAY, pygame.Color("White"), (self.head.x, self.head.y, 10, 10)) if self.check_if_eats(): self.eat() else: self.tail.pop(0) self.tail.append(Vector(self.head.x, self.head.y)) self.head.x += self.vel.x self.head.y += self.vel.y def clear_snake(self): for segment in self.tail: pygame.draw.rect(DISPLAY, pygame.Color("White"), (segment.x, segment.y, 10, 10)) pygame.draw.rect(DISPLAY, pygame.Color("White"), (self.head.x, self.head.y, 10, 10)) def clear_apples(self): pygame.draw.rect(DISPLAY, pygame.Color("White"), (self.apple.pos.x, self.apple.pos.y, 10, 10)) def do_crossover(self, other_snake: Snake) -> Snake: child_snake = Snake() child_snake.DNA = self.DNA.do_crossover(other_snake.DNA) return child_snake def mutate(self, mutation_rate): self.DNA.mutate(mutation_rate) def clone(self): clone = Snake() clone.DNA = copy(self.DNA) clone.is_alive = True return clone def show(self): #DISPLAY.fill(pygame.Color("White")) # Show whole snake's body for segment in self.tail: pygame.draw.rect(DISPLAY, pygame.Color("Black"), (segment.x, segment.y, 10, 10)) # Draw head pygame.draw.rect(DISPLAY, pygame.Color("Black"), (self.head.x, self.head.y, 10, 10)) pygame.display.update(0, 0, PLAYABLE_AREA_WIDTH, PLAYABLE_AREA_HEIGHT) # Draw apple self.apple.show()
print "python's dir: " + os.getcwd() print "script's dir: " + os.path.dirname(os.path.abspath(__file__)) # Create level currentLevel = Level(1, nibble.total_columns, nibble.total_lines) # Draw level nibble.drawLevel(currentLevel) nibble.displayMessage("Level" + str(nibble.level) + ", Push Space") nibble.drawLevel(currentLevel) # Create a Snake mySnake = Snake(nibble.center_x, nibble.center_y) # Show the first Apple apple = Apple(nibble.total_columns, nibble.total_lines, currentLevel, mySnake) pygame.draw.rect( nibble.screen, (0, 255, 0), pygame.Rect(apple.getX(), apple.getY(), mySnake.size, mySnake.size), 0) pygame.mixer.init(48000, -16, 1, 1024) sound_eat = pygame.mixer.Sound( os.path.dirname(os.path.abspath(__file__)) + '/hit.wav') sound_crash = pygame.mixer.Sound( os.path.dirname(os.path.abspath(__file__)) + '/sounds/crash.ogg') sound_game_over = pygame.mixer.Sound( os.path.dirname(os.path.abspath(__file__)) + '/sounds/reverse.ogg') def resetLevel(mySnake): # Recreate Level 1
class App: def __init__(self, headless, bot): self.bot = bot self.headless = headless self._running = True self._close = False self._display_surf = None self.size = self.weight, self.height = 800, 800 if not self.headless: self.fps = 15 self.playtime = 0.0 self.clock = pygame.time.Clock() pygame.mixer.init() pygame.init() def on_init(self): self._running = True cols = 50 rows = 50 mapSizeX = 700 mapSizeY = 700 imageSize = (int(mapSizeX / cols), int(mapSizeY / rows)) self.map = Map(50, 50, mapSizeX, mapSizeY, cols, rows, self.headless) self.snake = Snake(cols / 2, rows / 2, imageSize, self.headless) self.apple = Apple(cols, rows, imageSize, self.headless) if self.bot: self.bot.AddGoal(self.apple) self.bot.AddBody(self.snake) self.bot.AddMap(self.map) if not self.headless: pygame.display.set_caption("Snake") self._display_surf = pygame.display.set_mode( self.size, pygame.DOUBLEBUF) self.font = pygame.font.SysFont('mono', 14, bold=True) self.fontEndscore = pygame.font.SysFont('mono', 32, bold=True) def on_event(self, event): if event.type == pygame.QUIT: self._close = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: if not self.bot: self.snake.SetDirection(Direction.RIGHT) elif event.key == pygame.K_LEFT: if not self.bot: self.snake.SetDirection(Direction.LEFT) elif event.key == pygame.K_DOWN: if not self.bot: self.snake.SetDirection(Direction.DOWN) elif event.key == pygame.K_UP: if not self.bot: self.snake.SetDirection(Direction.UP) elif event.key == pygame.K_ESCAPE: self._close = True elif event.key == pygame.K_r: self.on_init() def on_render(self): if not self.headless: self._display_surf.fill((90, 90, 90)) #Map self.map.Draw(self._display_surf) #Scoreboard self.draw_text("SCORE: {}".format(len(self.snake.Position())), (0, 0)) self.draw_text("Press R to restart", (0, 13)) self.draw_text("Press ESC to exit", (0, 26)) #Snake self.snake.Draw(self._display_surf, self.map) #Apple self.apple.Draw(self._display_surf, self.map) pygame.display.update() def on_cleanup(self): if not self.headless: pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False while (not self._close): if not self.headless: for event in pygame.event.get(): self.on_event(event) if self.bot: self.snake.SetDirection(self.bot.Move()) if self._running: self.snake.Move() self.snake.Eat(self.apple) if self.map.IsCollision((self.snake.x, self.snake.y), self.snake): self._running = False else: self.on_render() elif not self.headless: self.fontEndscore.size("Game over! Score: {}".format( len(self.snake.Position()))) text = self.fontEndscore.render( "Game over! Score: {}".format(len(self.snake.Position())), True, (0, 0, 0)) text_rect = text.get_rect(center=(self.weight / 2, self.height / 2)) self._display_surf.blit(text, text_rect) else: print("Game over! Score: {}".format(len( self.snake.Position()))) self._close = True if not self.headless: self.playtime += self.clock.tick(self.fps) / 1000.0 pygame.display.flip() self.on_cleanup() def draw_text(self, text, position): self.font.size(text) surface = self.font.render(text, True, (255, 255, 255)) self._display_surf.blit(surface, position)
print "python's dir: " + os.getcwd() print "script's dir: " + os.path.dirname(os.path.abspath(__file__)) # Create level currentLevel = Level(1,nibble.total_columns,nibble.total_lines) # Draw level nibble.drawLevel(currentLevel) nibble.displayMessage("Level" + str(nibble.level) + ", Push Space") nibble.drawLevel(currentLevel) # Create a Snake mySnake = Snake(nibble.center_x,nibble.center_y) # Show the first Apple apple = Apple(nibble.total_columns,nibble.total_lines,currentLevel,mySnake) pygame.draw.rect(nibble.screen, (0, 255, 0), pygame.Rect(apple.getX(), apple.getY(), mySnake.size, mySnake.size),0) pygame.mixer.init(48000, -16, 1, 1024) sound_eat = pygame.mixer.Sound(os.path.dirname(os.path.abspath(__file__)) + '/hit.wav') sound_crash = pygame.mixer.Sound(os.path.dirname(os.path.abspath(__file__)) + '/sounds/crash.ogg') sound_game_over = pygame.mixer.Sound(os.path.dirname(os.path.abspath(__file__)) + '/sounds/reverse.ogg') def resetLevel(mySnake): # Recreate Level 1 global currentLevel currentLevel = Level(nibble.level,nibble.total_columns,nibble.total_lines) # Draw level nibble.drawLevel(currentLevel)
def loop(self): clock = pygame.time.Clock() snake = Snake(self.display) apple = Apple(self.display) x_change = 0 y_change = 0 self.score = 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -Config['snake']['speed'] y_change = 0 elif event.key == pygame.K_RIGHT: x_change = Config['snake']['speed'] y_change = 0 elif event.key == pygame.K_UP: x_change = 0 y_change = -Config['snake']['speed'] elif event.key == pygame.K_DOWN: x_change = 0 y_change = Config['snake']['speed'] #Background and game area self.display.fill(Config['colors']['red']) pygame.draw.rect(self.display, Config['colors']['black'], [ Config['game']['bumper_size'], Config['game']['bumper_size'], Config['game']['height'] - Config['game']['bumper_size'] * 2, Config['game']['width'] - Config['game']['bumper_size'] * 2 ]) #apple apple_rect = apple.draw() #move the snake snake.move(x_change, y_change) #Draw the snake snake_rect = snake.draw() snake.draw_body() #collision bumper_x = Config['game']['width'] - Config['game']['bumper_size'] bumper_y = Config['game']['height'] - Config['game']['bumper_size'] if (snake.x_pos < Config['game']['bumper_size'] or snake.y_pos < Config['game']['bumper_size'] or snake.x_pos + Config['snake']['width'] > bumper_x or snake.y_pos + Config['snake']['height'] > bumper_y): self.loop() # Detect collision with apple if apple_rect.colliderect(snake_rect): apple.randomize() self.score += 1 snake.eat() # Collide with Self if len(snake.body) >= 1: for cell in snake.body: if snake.x_pos == cell[0] and snake.y_pos == cell[1]: self.loop() # Initialize font and draw title and score text pygame.font.init() font = pygame.font.Font('./assets/Now-Regular.otf', 28) score_text = 'Score: {}'.format(self.score) score = font.render(score_text, True, Config['colors']['white']) title = font.render('Snake Game', True, Config['colors']['white']) title_rect = title.get_rect(center=(Config['game']['width'] / 2, Config['game']['bumper_size'] / 2)) score_rect = score.get_rect( center=(500 / 2, Config['game']['height'] - Config['game']['bumper_size'] / 2)) self.display.blit(score, score_rect) self.display.blit(title, title_rect) pygame.display.update() clock.tick(Config['game']['fps'])