示例#1
0
文件: Game.py 项目: Puzhaev/3semestr
    def loop(self):
        flag = False

        clock = pygame.time.Clock()
        pygame.font.init()
        font = pygame.font.Font('materials/text.ttf', 25)

        title = font.render('Snake', True, Config['col_dark'])
        title_rect = title.get_rect(center=(Config['w_g'] / 2,
                                            Config['front'] / 2 + 5))

        file = open('materials/high_score.txt')
        high_score = int(file.readline())
        file.close()

        pygame.mixer.music.load('materials/music.wav')
        pygame.mixer.music.play(-1)
        eat_apple = pygame.mixer.Sound('materials/sound.wav')

        snake = Snake(Config['w_g'] / 2, Config['h_g'] / 2, self.display)
        dx = 0
        dy = 0
        self.score = 0

        apple = Apple(self.display)

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT and dx != Config['sp']:
                        dx = -Config['sp']
                        dy = 0
                    elif event.key == pygame.K_RIGHT and dx != -Config['sp']:
                        dx = Config['sp']
                        dy = 0
                    elif event.key == pygame.K_UP and dy != Config['sp']:
                        dx = 0
                        dy = -Config['sp']
                    elif event.key == pygame.K_DOWN and dy != -Config['sp']:
                        dx = 0
                        dy = Config['sp']

            pygame.draw.rect(self.display, Config['col_light'],
                             [0, 0, Config['h_g'], Config['w_g']])

            snake.update(dx, dy)
            snake_rect = snake.draw()
            apple_rect = apple.draw()

            if apple_rect.colliderect(snake_rect):
                apple.randomize()
                self.score += 1
                snake.eat()
                eat_apple.play()
            if len(snake.body) > 1:
                for cell in snake.body:
                    if snake.x_pos == cell[0] and snake.y_pos == cell[1]:
                        if self.score > high_score:
                            os.remove('materials/high_score.txt')
                            f = open('materials/high_score.txt', mode='w')
                            print(str(self.score), file=f)
                            f.close()
                        self.loop()

            score_text = 'Score: {}'.format(self.score)
            score = font.render(score_text, True, Config['col_dark'])

            high_score_text = 'High score: {}'.format(str(high_score))
            high_score_font = font.render(high_score_text, True,
                                          Config['col_dark'])

            score_rect = score.get_rect(center=(Config['score_x'],
                                                Config['h_g'] -
                                                Config['front'] / 2 - 30))
            high_score_rect = high_score_font.get_rect(
                center=(Config['high_x'],
                        Config['h_g'] - Config['front'] / 2 - 5))

            self.display.blit(score, score_rect)
            self.display.blit(title, title_rect)
            self.display.blit(high_score_font, high_score_rect)

            pygame.display.update()

            if flag:
                if self.score > high_score:
                    os.remove('data/high_score.txt')
                    f = open('data/high_score.txt', mode='w')
                    print(str(self.score), file=f)
                    f.close()
                self.loop()

            clock.tick_busy_loop(Config['fps'])
示例#2
0
文件: game.py 项目: fransfreij/snake
class Game:
    def __init__(self, running):
        pygame.init()
        self.running = running
        self.apples = []

    def create_window(self):
        pygame.display.set_caption("Snake")
        self.window = pygame.display.set_mode(
            (constants['GAME_WIDTH'], constants['GAME_HEIGHT']))

    def create_apple(self):
        apple = Apple()
        apple.create_apple()
        self.apples.append(apple)

    def create_snake(self):
        self.snake = Snake()

    def create_textmanager(self):
        self.textmanager = Textmanager()

    def run(self):
        clock = pygame.time.Clock()
        self.create_window()
        self.create_snake()
        self.create_textmanager()

        # game loop
        while self.running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False

                self.snake.on_event(event)

            # we always want a apple on the screen
            if len(self.apples) <= 0:
                self.create_apple()

            # grow the snake
            self.snake.grow()

            # collision detection
            for apple in self.apples:
                if apple.get_rect().colliderect(self.snake.get_rect()):
                    self.apples.remove(apple)
                    self.snake.increase_score()
                else:
                    self.snake.shrink()

            # update the snake movement direction
            self.snake.update()

            # if snake is not alive, quit the game
            if self.snake.get_alive_status() is False:
                self.running = False

            # render score and it's x, y position
            self.textmanager.render_text(self.snake.get_score(),
                                         (constants['GAME_WIDTH'] - 40), 0)

            # drawables
            self.window.fill(constants['BLACK'])
            self.snake.draw(self.window)
            self.textmanager.draw(self.window)
            for apple in self.apples:
                apple.draw(self.window)

            # update and fps
            pygame.display.update()
            clock.tick(60)