Esempio n. 1
0
    def __init__(self):
        super(PySnake, self).__init__(GAME_NAME, SCREEN_SIZE, FPS,
                                      "resources/Minecraft.ttf", 16,
                                      "resources/pysnake.png")
        self.background.fill(BACKGROUND_COLOR)
        for i in range(CELL_SIZE, SCREEN_WIDTH, CELL_SIZE):
            pygame.draw.line(self.background, GRID_COLOR, (i, 0),
                             (i, SCREEN_HEIGHT))
        for i in range(CELL_SIZE, SCREEN_HEIGHT, CELL_SIZE):
            pygame.draw.line(self.background, GRID_COLOR, (0, i),
                             (SCREEN_WIDTH, i))

        self.field = Field(self, COLUMNS, ROWS)
        self.apple_counter = 0
        self.apple = Apple(self)
        # self.snake = Snake(self)
        self.snake = Snake(self, SNAKE_DEFAULT_X, SNAKE_DEFAULT_Y,
                           SNAKE_DEFAULT_LENGTH, RIGHT, SNAKE_DEFAULT_SPEED,
                           SNAKE_COLOR_SKIN, SNAKE_COLOR_BODY,
                           SNAKE_COLOR_HEAD)

        # 控制按键设定
        self.key_bind(KEY_EXIT, self.quit)
        self.key_bind(KEY_UP, self.snake.turn, direction=UP)
        self.key_bind(KEY_DOWN, self.snake.turn, direction=DOWN)
        self.key_bind(KEY_LEFT, self.snake.turn, direction=LEFT)
        self.key_bind(KEY_RIGHT, self.snake.turn, direction=RIGHT)
        self.key_bind(pygame.K_EQUALS, self.snake.speed_up)
        self.key_bind(pygame.K_MINUS, self.snake.speed_down)
        self.key_bind(KEY_RESPAWN, self.restart)

        self.add_draw_action(self.show_score)
Esempio n. 2
0
    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()
Esempio n. 3
0
    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
Esempio n. 4
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)
Esempio n. 5
0
    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
Esempio n. 6
0
class PySnake(MyGame):
    "贪吃蛇游戏"

    def __init__(self):
        super(PySnake, self).__init__(GAME_NAME, SCREEN_SIZE, FPS,
                                      "resources/Minecraft.ttf", 16,
                                      "resources/pysnake.png")
        self.background.fill(BACKGROUND_COLOR)
        for i in range(CELL_SIZE, SCREEN_WIDTH, CELL_SIZE):
            pygame.draw.line(self.background, GRID_COLOR, (i, 0),
                             (i, SCREEN_HEIGHT))
        for i in range(CELL_SIZE, SCREEN_HEIGHT, CELL_SIZE):
            pygame.draw.line(self.background, GRID_COLOR, (0, i),
                             (SCREEN_WIDTH, i))

        self.field = Field(self, COLUMNS, ROWS)
        self.apple_counter = 0
        self.apple = Apple(self)
        # self.snake = Snake(self)
        self.snake = Snake(self, SNAKE_DEFAULT_X, SNAKE_DEFAULT_Y,
                           SNAKE_DEFAULT_LENGTH, RIGHT, SNAKE_DEFAULT_SPEED,
                           SNAKE_COLOR_SKIN, SNAKE_COLOR_BODY,
                           SNAKE_COLOR_HEAD)

        # 控制按键设定
        self.key_bind(KEY_EXIT, self.quit)
        self.key_bind(KEY_UP, self.snake.turn, direction=UP)
        self.key_bind(KEY_DOWN, self.snake.turn, direction=DOWN)
        self.key_bind(KEY_LEFT, self.snake.turn, direction=LEFT)
        self.key_bind(KEY_RIGHT, self.snake.turn, direction=RIGHT)
        self.key_bind(pygame.K_EQUALS, self.snake.speed_up)
        self.key_bind(pygame.K_MINUS, self.snake.speed_down)
        self.key_bind(KEY_RESPAWN, self.restart)

        self.add_draw_action(self.show_score)

    def restart(self):
        if not self.snake.alive:
            self.apple_counter = 0
            self.field.clear()  # 移除尸体
            self.apple.drop()
            self.snake.respawn()

    def show_score(self):
        text = "Apple {}".format(self.apple_counter)
        output = self.font.render(text, True, (255, 255, 33))
        self.screen.blit(output, (0, 0))

        if not self.snake.alive:
            text = " GAME OVER"
            output = self.font.render(text, True, (255, 33, 33), WHITE)
            self.screen.blit(output, (320 - 54, 240 - 10))
            text = " press R to restart"
            output = self.font.render(text, True, GREY, DARK_GREY)
            self.screen.blit(output, (320 - 94, 260 - 10))

        if not self.running and self.snake.alive:
            text = " GAME PAUSED"
            output = self.font.render(text, True, LIGTH_GREY, DARK_GREY)
            self.screen.blit(output, (320 - 54, 240 - 10))
Esempio n. 7
0
def run_game():
    pygame.init()
    pygame.font.init()
    w = s.screen_width * s.cell_size + 1
    h = s.screen_height * s.cell_size + 1
    screen = pygame.display.set_mode((w, h))
    pygame.display.set_caption("Snake")

    myfont = pygame.font.SysFont('Arial', 40)

    clock = pygame.time.Clock()

    snake = Snake()
    apple = Apple(snake)
    snake.apple = apple
    ai = AI()

    while (True):

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    snake.direction = (-1, 0)
                elif event.key == pygame.K_RIGHT:
                    snake.direction = (1, 0)
                elif event.key == pygame.K_UP:
                    snake.direction = (0, -1)
                elif event.key == pygame.K_DOWN:
                    snake.direction = (0, 1)
                elif event.key == pygame.K_ESCAPE:
                    sys.exit()
                elif event.key == pygame.K_SPACE:
                    pause()

        if not snake.dead:
            ai.pass_through(snake.body[:], apple.position[:])
            snake.direction = ai.output()
            snake.move()
        screen.fill(s.bg_color)
        screen = draw_board(screen, snake, apple, ai.path, myfont)
        pygame.display.flip()

        if (snake.dead):
            print("Snake lost, size: ", len(snake))
            apple.randomize()
            snake = Snake()
            apple.snake = snake
            snake.apple = apple
            ai = AI()
        elif len(snake.body) == s.screen_width * s.screen_height:
            print("Snake won! Size: ", len(snake))
            return

        fps = s.FPS
        if ai.mode == "Tail":
            fps *= 2
        clock.tick(fps)
Esempio n. 8
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)
Esempio n. 9
0
 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))
Esempio n. 10
0
    def init(self, winWidth, winHeight):
        self.fieldWidth = winWidth // constants.FIELD_SIZE
        self.fieldHeight = winHeight // constants.FIELD_SIZE

        self.snake = Snake(self.fieldWidth // 2, self.fieldHeight // 2)
        self.apple = Apple(self.snake.getOccupiedCoords(), self.fieldWidth,
                           self.fieldHeight)
        self.currentTick = 0
        self.score = 0
Esempio n. 11
0
def isItApple( patch, motionStep ):
    a = Apple(patch, motionStep=motionStep)
    val = a.fitSphere( minRadius=0.03, maxRadius=0.15, maxDist=0.01, numIter=100 )
    desiredRatio = math.pi/4. # 0.78
    tolerance = 0.1
    if desiredRatio-tolerance < val < desiredRatio+tolerance:
        print "%.2f:" % val, "(%.3f, %.3f, %.3f)" % a.center, "%.3f" % a.radius
        return True
    return False
Esempio n. 12
0
def move_rect():

    global dir

    cur_y = snakeHead.y
    cur_x = snakeHead.x

    if (cur_y >= settings[1] - snakeHead.height) or (cur_y <= 0) or (cur_x >= settings[0] - snakeHead.width) or (cur_x <= 0):
        pygame.quit()
    if dir == DOWN:
        cur_y += 10
    if dir == UP:
        cur_y -= 10
    if dir == LEFT:
        cur_x -= 10
    if dir == RIGHT:
        cur_x += 10

    prev_x = snakeHead.x
    prev_y = snakeHead.y
    snakeHead.y = cur_y
    snakeHead.x = cur_x
    headSprite = SnakePart(head_img, snakeHead)
    pygame.draw.rect(scene, BLACK, snakeHead)
    scene.blit(head_img, snakeHead)
    headSprite.update()

    if len(snake)>1:
        isTail = True
        for j in range(len(snake)-1, 0, -1):
            if (j == 1):
                snake[j].y = prev_y
                snake[j].x = prev_x
            else:
                snake[j].y = snake[j-1].y
                snake[j].x = snake[j-1].x
            pygame.draw.rect(scene, BLACK, snake[j])
            if (isTail == True):
                scene.blit(tail_img, snake[j])
                isTail = False
            else:
                scene.blit(body_img, snake[j])

    appleSprite = Apple(apple_img, apple)

    #if (snakeHead.x == apple.x and snakeHead.y == apple.y):
    if (pygame.sprite.collide_rect(headSprite, appleSprite)):
        snake.append(pygame.Rect(prev_x, prev_y, 10, 10))
        apple.x = randint(3, 87) * 10
        apple.y = randint(3, 47) * 10

    pygame.draw.rect(scene, BLACK, apple)
    scene.blit(apple_img, apple)
    appleSprite.update()

    pygame.display.update()
Esempio n. 13
0
 def __init__(self, config_path):
     with open(config_path) as config_file:
         config = json.load(config_file)
     xiaomi = config['xiaomi']
     self._xiaomi = Xiaomi(xiaomi['client_id'], xiaomi['client_secret'], xiaomi['public_key'],
                           xiaomi['verify_signature'], xiaomi['verify_api'], xiaomi['is_debug'])
     google_play = config['google_play']
     self._google_play = GooglePlay(google_play['public_key'])
     apple_app_store = config['apple_app_store']
     self._apple = Apple(apple_app_store['shared_secret'])
Esempio n. 14
0
 def __init__(self, settings):
     self.width = settings.board_width
     self.height = settings.board_height
     self.board = self.make_board()
     self.snake = Snake(settings)
     self.apple = Apple(settings, self.snake)
     self.score = 0
     self.playtime_started = time.time()
     self.playtime_ended = 0
     self.settings = settings
Esempio n. 15
0
 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()
Esempio n. 16
0
 def __init__(self, w=1000, h=500):
     pygame.init()
     self.s_width = w
     self.s_height = h
     self.crashed = False
     self.speed = 10
     self.clock = pygame.time.Clock()
     self.screen = pygame.display.set_mode([self.s_width, self.s_height])
     self.snake = Snake(self.screen)
     self.apple = Apple(self.screen)
     self.score = 0
Esempio n. 17
0
class Renderer():
    def __init__(self):
        self.window = curses.initscr()
        size = self.window.getmaxyx()
        self.board = Board(size[1], size[0] - 1)
        self.snake = Snake((int(size[1] / 2), int(size[0] / 2)))
        self.apple = Apple(size[1], size[0] - 1)
        self.input = Input()
        curses.noecho()
        curses.cbreak()
        curses.curs_set(0)
        self.window.keypad(True)
        self.window.nodelay(True)
        self.window.scrollok(False)

        self.gameover = False

    def update(self):
        # Propagate user inputs
        try:
            instruction = self.input.get_instruction(self.window)
            self.snake.process_instruction(instruction)
        except exceptions.NoInputException:
            pass  # Just skip if there's no input

        # Update game object state
        self.snake.update()

        # Did the snake eat the apple?
        snakehead = self.snake.get_head_position()
        if self.apple.overlaps(snakehead):
            self.snake.grow()
            self.apple.move()

        # Check for game over
        if self.board.is_outside_bounds(
                snakehead) or self.snake.self_intersects():
            self.gameover = True
            self.board.game_over = True
            self.snake.is_active = False

        # Render
        self.window.erase()
        self.board.render(self.window)
        self.snake.render(self.window)
        self.apple.render(self.window)
        self.input.render(self.window)
        self.window.refresh()

    def terminate(self):
        curses.nocbreak()
        self.window.keypad(False)
        curses.echo()
        curses.endwin()
Esempio n. 18
0
 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)
Esempio n. 19
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()
Esempio n. 20
0
def isItApple(patch, motionStep):
    a = Apple(patch, motionStep=motionStep)
    val = a.fitSphere(minRadius=0.03,
                      maxRadius=0.15,
                      maxDist=0.01,
                      numIter=100)
    desiredRatio = math.pi / 4.  # 0.78
    tolerance = 0.1
    if desiredRatio - tolerance < val < desiredRatio + tolerance:
        print "%.2f:" % val, "(%.3f, %.3f, %.3f)" % a.center, "%.3f" % a.radius
        return True
    return False
Esempio n. 21
0
    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
Esempio n. 22
0
class Board:
    def __init__(self, settings):
        self.width = settings.board_width
        self.height = settings.board_height
        self.board = self.make_board()
        self.snake = Snake(settings)
        self.apple = Apple(settings, self.snake)
        self.score = 0
        self.playtime_started = time.time()
        self.playtime_ended = 0
        self.settings = settings

    def make_board(self):
        board = [[" " for y in range(self.width)] for x in range(self.height)]
        for i in range(self.width):
            board[0][i] = "-"
            board[-1][i] = "-"
        for i in range(self.height):
            board[i][-1] = "|"
            board[i][0] = "|"
        board[0][0] = "+"
        board[0][-1] = "+"
        board[-1][0] = "+"
        board[-1][-1] = "+"
        return board

    def show_board(self):
        self.playtime_ended = int(time.time() - self.playtime_started)
        minutes = self.playtime_ended // 60
        seconds = self.playtime_ended - (minutes * 60)
        print(f"""+-------------------------------------------+
         SCORE:{self.score}   TIME PLAYED: {minutes}:{seconds}""")
        for i in range(self.height):
            for j in range(self.width):
                print(self.board[i][j], end="")
            print("")
        print("""             PRESS 'esc' TO QUIT             """)

    def update_board(self):
        self.board = self.make_board()
        self.snake.move()
        self.snake.wall_detect()
        self.board[self.apple.apple_coords[0]][
            self.apple.apple_coords[1]] = "@"
        for el in self.snake.body:
            self.board[el[0]][el[1]] = "o"
        self.board[self.snake.body[0][0]][self.snake.body[0][1]] = "O"
        if self.snake.body[0] == self.apple.apple_coords:
            self.score += 1
            self.settings.game_speed *= 0.97
            self.snake.grow = True
            self.apple.spawn_apple(self.snake)
Esempio n. 23
0
class PySnake(MyGame):
    """贪吃蛇游戏"""
    def __init__(self):
        super(PySnake, self).__init__(GAME_NAME, ICON,
                                      SCREEN_WIDTH, SCREEN_HEIGHT,
                                      DISPLAY_MODE, LOOP_SPEED,
                                      FONT_NAME, FONT_SIZE)
        self.draw_background_line()
        self.snake = Snake(self)
        self.apple = Apple(self)
        self.apple_count = 0
        # 绑定按键
        self.add_key_binding(KEY_UP, self.snake.turn, direction=UP)
        self.add_key_binding(KEY_DOWN, self.snake.turn, direction=DOWN)
        self.add_key_binding(KEY_LEFT, self.snake.turn, direction=LEFT)
        self.add_key_binding(KEY_RIGHT, self.snake.turn, direction=RIGHT)
        self.add_key_binding(KEY_REBORN, self.restart)
        self.add_key_binding(KEY_EXIT, self.game_quit)
        self.add_draw_action(self.show_score)

    def draw_background_line(self):
        self.background.fill(COLOR_BG)
        for col in range(CELL_SIZE, SCREEN_WIDTH, CELL_SIZE):
            self.draw.line(self.background, COLOR_GRID,
                           (col, 0), (col, SCREEN_HEIGHT))
        for row in range(CELL_SIZE, SCREEN_HEIGHT, CELL_SIZE):
            self.draw.line(self.background, COLOR_GRID,
                           (0, row), (SCREEN_WIDTH, row))

    def show_score(self):
        text = "Apple %d" % self.apple_count
        self.draw_text(text, (0, 0), COLOR_SCORE)

        if not self.snake.alive:
            self.draw_text(" GAME OVER ",
                           (SCREEN_WIDTH // 2 - 65, SCREEN_HEIGHT // 2 - 40),
                           COLOR_DEFEAT, WHITE)
            self.draw_text(" PRESS R TO RESTART ",
                           (SCREEN_WIDTH // 2 - 120, SCREEN_HEIGHT // 2),
                           GREY, LIGHT_GREY)

        if not self.running and self.snake.alive:
            self.draw_text(" GAME PAUSED ",
                           (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20),
                           LIGHT_GREY, DARK_GREY)

    def restart(self):
        if not self.snake.alive:
            self.apple_count = 0
            self.apple.drop()
            self.snake.reborn()
            self.running = True
Esempio n. 24
0
 def test_update(self):
     """Test that apple location is correctly updated"""
     # Logical size of the playfield
     n = 10
     m = 10
     # Create snake and apple
     snake = Snake([(1, 3), (2, 3), (3, 3)])
     apple = Apple((5, 5))
     # Update apple
     apple.update(snake, n, m)
     # Make sure apple is not outside the playfield
     self.assertTrue(0 <= apple.location[0] <= n)
     self.assertTrue(0 <= apple.location[1] <= m)
Esempio n. 25
0
 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)
Esempio n. 26
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))
Esempio n. 27
0
    def __init__(self):
        self.window = curses.initscr()
        size = self.window.getmaxyx()
        self.board = Board(size[1], size[0] - 1)
        self.snake = Snake((int(size[1] / 2), int(size[0] / 2)))
        self.apple = Apple(size[1], size[0] - 1)
        self.input = Input()
        curses.noecho()
        curses.cbreak()
        curses.curs_set(0)
        self.window.keypad(True)
        self.window.nodelay(True)
        self.window.scrollok(False)

        self.gameover = False
Esempio n. 28
0
    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
Esempio n. 29
0
 def resetGame(self):
     #clears the board
     del self.snake
     del self.apple
     self.snake = Snake()
     self.apple = Apple()
     return True
    def add_apple(self, is_red: bool):
        xy = XYPoint(randrange(self.board_width), randrange(self.board_height))
        while (xy.x, xy.y) in self.apples:
            xy = XYPoint(randrange(self.board_width), randrange(self.board_height))

        apple = Apple(xy, 10, is_red)
        self.apples[(apple.xy.x, apple.xy.y)] = apple
Esempio n. 31
0
    def setup(self):
        self.snake = Snake(c.MAP_SIZE, c.SNAKE_COLOR)
        self.apple = Apple(c.MAP_SIZE, c.APPLE_COLOR)
        pause_hint_text = Text(
            0,
            0,
            lambda: "Press p to pause/unpause after game started",
            self.font,
            True,
        )
        start_text = Text(0, 50, lambda: "Press space to start", self.font, True)
        score_text = Text(0, 0, lambda: f"Score: {len(self.snake)}", self.font)
        play_again_text = Text(
            0,
            0,
            lambda: f"You lose! Final Score: {len(self.snake)}. Press space to restart",
            self.font,
            True,
        )
        pause_text = Text(0, 0, lambda: "Game paused", self.font, True)

        self.objects[GameState.MAIN_MENU] = [pause_hint_text, start_text]
        self.objects[GameState.PAUSED] = [score_text, pause_text]
        self.objects[GameState.IN_PROGRESS] = [score_text]
        self.objects[GameState.END] = [play_again_text]
Esempio n. 32
0
    def resetGame(self):
        del self.snake
        del self.apple
        self.snake = Snake()
        self.apple = Apple()

        return True
Esempio n. 33
0
    def __init__(self, width, height):
        # body[0] is the tail, body[-1] is the head
        x = width // 2
        y = height // 2
        self.width = width
        self.height = height

        body = [(x, y + 2), (x, y + 1), (x, y)]
        self.body = body
        self.x = x
        self.y = y
        self.size = 3
        self.alive = True
        self.direction = ""  # don't move yet
        self.direction = 'left'
        self.apple = Apple(width, height, self.body)
Esempio n. 34
0
CHUNK = 9600
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 96000

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
				channels=CHANNELS,
				rate=RATE,
				input=True,
				frames_per_buffer=CHUNK)

pl = Player(0, 0, 10, 10, 0)
ap = Apple(10)

while not done:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			stream.stop_stream()
			stream.close()
			p.terminate()
			done = True

		if event.type == pygame.KEYDOWN and event.key == pygame.K_s:
			pl.orientation = 0
		if event.type == pygame.KEYDOWN and event.key == pygame.K_w:
			pl.orientation = 1
		if event.type == pygame.KEYDOWN and event.key == pygame.K_d:
			pl.orientation = 2
Esempio n. 35
0
class Game(object):
    def __init__(self, window):
        self.snake = Snake()
        self.apple = Apple()
        self.window = window
        self.grid = []
        self.score = 0

    def move_snake(self, key):
        """Manual move of snake"""
        if key in [KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT]:
            self.snake.move(key)
        else:
            self.snake.move(self.snake.last_direction)

        if self.snake.head == self.apple.position:
            self.snake.eat(self.apple, self.grid)
            self.score += 1

        if self.snake.is_collide():
            self.reset()

    def automove(self):
        """Deplace position of the snake with A* algorithm"""
        path = find_path(tuple(self.snake.head), tuple(self.apple.position), self.grid)
        move = path[0] if path else False

        if not move:
            move = self.any_possible_move()

        if move:
            if not self.snake.is_eating:
                self.snake.position.pop(0)

            self.snake.is_eating = False
            self.snake.position.append(move)
            self.snake.head = self.snake.position[-1]
            self.snake.tail = self.snake.position[0]

        if self.snake.head == self.apple.position:
            self.snake.eat(self.apple, self.grid)
            self.score += 1

        if self.snake.is_collide() or not move:
            self.reset()

    def any_possible_move(self):
        """Return any possible position"""
        neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        for i, j in neighbors:
            neighbor = self.snake.head[0] + i, self.snake.head[1] + j
            if self.grid[neighbor[0]][neighbor[1]] == 0:
                return [neighbor[0], neighbor[1]]
        return False

    def display(self):
        """display game"""
        self.grid[:] = []
        for line in range(HEIGHT):
            self.grid.append([])
            for column in range(WIDTH):
                if column == 0 or line == 0 or column == WIDTH - 1 or line == HEIGHT - 1:
                    self.grid[line].append(1)
                else:
                    self.grid[line].append(0)

        for line, column in self.snake.position:
            self.grid[line][column] = 1
            self.window.addstr(line, column, 's')

        line, column = self.apple.position
        self.window.addstr(line, column, 'a')

    def reset(self):
        """Reset game"""
        self.apple.reset()
        self.snake.reset()
        self.score = 0
Esempio n. 36
0
class Snake:

    def __init__(self, width, height):
        # body[0] is the tail, body[-1] is the head
        x = width // 2
        y = height // 2
        self.width = width
        self.height = height

        body = [(x, y + 2), (x, y + 1), (x, y)]
        self.body = body
        self.x = x
        self.y = y
        self.size = 3
        self.alive = True
        self.direction = ""  # don't move yet
        self.direction = 'left'
        self.apple = Apple(width, height, self.body)

    def move(self, by_dir=True):
        # since curses is based off of the top left corner, we need to make
        # these functions appear to be backwards
        if by_dir:
            if self.direction == 'up':
                self.y -= 1
            elif self.direction == 'down':
                self.y += 1
            elif self.direction == 'left':
                self.x -= 1
            elif self.direction == 'right':
                self.x += 1
            else:
                # you made a typo, or didn't choose a way to go yet
                pass
        #check if ate apple
        if self.position == self.apple.pos:
            self.size += 1
            if self.apple.gold: #increase size by total of 5
                self.size += 4
            self.apple.set_new_pos(self.body)
        #check dead
        if self.out_of_bounds or self.position in self.body:
            self.alive = False
            #delete current head to prevent index out of bound
            del self.body[-1]
        #update head (head at end of list, tail at beginning)
        self.body.append((self.x, self.y))
        #if the snake size is too big, delete its tail, otherwise let it grow to however many units
        if len(self.body) > self.size:
            del self.body[0]

    def set_direction(self, direction):
        if not direction:
            return
        if self.direction == 'up' and direction == 'down':
            return
        if self.direction == 'left' and direction == 'right':
            return
        if self.direction == 'right' and direction == 'left':
            return
        if self.direction == 'down' and direction == 'up':
            return
        self.direction = direction
        return True

    @property
    def out_of_bounds(self):
        if self.x < 0 or self.y < 0:
            return True
        return self.x >= self.width or self.y >= self.height

    @property
    def position(self):
        return self.x, self.y
Esempio n. 37
0
 def __init__(self, window):
     self.snake = Snake()
     self.apple = Apple()
     self.window = window
     self.grid = []
     self.score = 0