Exemple #1
0
def main():
    # Обычная инициализация
    pygame.init()  #Ну собственно грузим сам pygame
    screen = pygame.display.set_mode((640, 480))  # Дисплей настраиваем
    pygame.display.set_caption(
        'Заряженый петон')  # Устанавливаем название игры
    # Заливаем фон
    pygame.display.flip()  # А хз чо это
    field = GameField(screen)
    snake = Snake((10, 10))
    clock = pygame.time.Clock()
    move_snake = pygame.USEREVENT + 1
    pygame.time.set_timer(move_snake, 200)
    while 1:
        # Handle Input Events
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:  # Левая стрелочка
                    snake.change_direction(0b11)
                elif event.key == pygame.K_RIGHT:  # Правая стрелочка
                    snake.change_direction(0b10)
                elif event.key == pygame.K_UP:  # Верхняя стрелочка
                    snake.change_direction(0b00)
                elif event.key == pygame.K_DOWN:  # Верхняя стрелочка
                    snake.change_direction(0b01)
            elif event.type == move_snake:
                snake.move(field.game_area)
        clock.tick(60)
        field.draw_frame(screen, snake)
        pygame.display.update()
Exemple #2
0
def gameStart():

    gv.INTRO = False
    gv.DONE = False
    snake = Snake(0)
    food = Food()

    while not gv.DONE:

        clock.tick(gv.SELECTED_LEVEL[1])

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gv.DONE = True
                pygame.quit()
                os._exit(1)
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    snake.switchDirection(Directions.RIGHT)
                elif event.key == pygame.K_LEFT:
                    snake.switchDirection(Directions.LEFT)
                elif event.key == pygame.K_UP:
                    snake.switchDirection(Directions.UP)
                elif event.key == pygame.K_DOWN:
                    snake.switchDirection(Directions.DOWN)

        if snake.move(snake.direction) != False:
            #Game
            gameSurface.fill((0, 0, 0))
            CheckSnakeFoodCollision(snake, food)
            snake.drawSnake(gameSurface)
            food.drawFood(gameSurface)
            screen.blit(gameSurface, (0, gv.TEXT_AREA_HEIGHT))

            pygame.draw.line(screen, Colors.WHITE, (0, gv.TEXT_AREA_HEIGHT),
                             (gv.SURFACE_WIDTH, gv.TEXT_AREA_HEIGHT), 2)

            # Text
            LEVEL_TEXT = FONT.render("Level " + str(gv.SELECTED_LEVEL[0]),
                                     True, Colors.WHITE)
            textSurface.fill(Colors.BLACK)
            SCORE_TEXT = FONT.render(str(snake.score), True, Colors.WHITE)
            textSurface.blit(LEVEL_TEXT, (50, 10))
            textSurface.blit(GAME_TEXT, (gv.SURFACE_WIDTH / 2 - 50, 10))
            textSurface.blit(SCORE_TEXT, (gv.SURFACE_WIDTH - 50, 10))
            screen.blit(textSurface, (0, 0))

            pygame.display.flip()
            pygame.display.update()

        else:
            gv.LAST_SCORE = snake.score
            gameOver()
Exemple #3
0
class Game:
    def __init__(self):
        self.score = 0
        self.grid = Grid(*GRID_SIZE)
        self.snake = Snake(self.grid)
        self.apple = Apple(self.grid)
        self.screen = pg.display.set_mode(SCREEN_SIZE)
        self.clock = pg.time.Clock()
        self.paused = False
        self.curr_events = None
        self.lives = STARTING_LIVES

    def run(self):
        while self.lives > 0:
            self.clock.tick(MAX_FPS)
            self.curr_events = pg.event.get()
            for event in self.curr_events:
                if event.type == pg.QUIT:
                    sys.exit()
                if event.type == pg.KEYDOWN:
                    if event.key in [pg.K_ESCAPE, pg.K_p]:
                        self.paused = not self.paused
            if not self.paused:
                self.update_state()
            self.draw(self.screen)

    def update_state(self):
        for event in self.curr_events:
            if event.type == pg.KEYDOWN:
                self.snake.update_direction(event.key)

        has_collided = self.snake.move(self.grid)
        self.snake.update_color()
        if has_collided:
            self.lives -= 1

        if self.snake.parts[0] == self.apple.pos:
            self.snake.eat()
            self.apple = Apple(self.grid)
            self.score += 1

    def draw(self, screen):
        [item.draw(screen) for item in [self.grid, self.apple, self.snake]]
        screen.blit(FONT.render(f"Score: {self.score}", True, LIGHT_GREY),
                    SCORE_POS)
        screen.blit(FONT.render(f"Lives: {self.lives}", True, LIGHT_GREY),
                    LIVES_POS)

        if self.paused:
            self.screen.blit(FONT.render("Paused", True, RED), (200, 200))
        pg.display.update()

    def show_end_screen(self):
        self.screen.blit(FONT.render("Erneut versagt, du Narr", True, RED),
                         (25, 200))
        self.screen.blit(FONT.render("Klicken zum Beenden", True, RED),
                         (25, 400))
        pg.display.update()
        while True:
            self.clock.tick(MAX_FPS)
            [
                sys.exit() for event in pg.event.get()
                if event.type in [pg.MOUSEBUTTONDOWN, pg.QUIT]
            ]
Exemple #4
0
class Game:
    def __init__(self, display):
        self.display = display
        self.score = 0
        self.done = False
        self.snake = Snake(self.display)
        self.apple = Apple(self.display)

    def start(self):
        return self.generate_observations()

    def loop(self):
        clock = pygame.time.Clock()
        # self.snake = Snake(self.display)
        # self.apple = Apple(self.display)

        x_change = 0
        y_change = 0

        self.score = 0

        while True:
            for event in pygame.event.get():

                if self.done == True or 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']

            # Fill background and draw game area
            self.display.fill(Config['colors']['green'])

            pygame.draw.rect(self.display, Config['colors']['black'], [
                0, Config['game']['bumper_size'], Config['game']['height'],
                Config['game']['width']
            ])

            # Draw an apple
            apple_rect = self.apple.draw()

            # Move and Re-Draw Snake
            self.snake.move(x_change, y_change)
            self.snake_rect = self.snake.draw()
            self.snake.draw_body()

            # Detect with corners
            if (self.snake.x_pos >= Config['game']['width'] and x_change > 0):
                self.snake.x_pos = 0
            if (self.snake.x_pos < 0 and x_change < 0):
                self.snake.x_pos = Config['game']['width'] - 1
            if (self.snake.y_pos >
                    Config['game']['height'] + Config['game']['bumper_size']
                    and y_change > 0):
                self.snake.y_pos = Config['game']['bumper_size']
            if (self.snake.y_pos < Config['game']['bumper_size']
                    and y_change < 0):
                self.snake.y_pos = Config['game']['height'] + Config['game'][
                    'bumper_size'] - 1

            # Detect collision with apple
            if apple_rect.colliderect(snake_rect):
                self.apple.randomize()
                self.score += 1
                self.snake.eat()

            # Collide with Self
            if len(self.snake.body) >= 1:
                for cell in self.snake.body:
                    if self.snake.x_pos == cell[
                            0] and self.snake.y_pos == cell[1]:
                        self.done = True
                        # 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(Config['game']['caption'], True,
                                Config['colors']['white'])

            title_rect = title.get_rect(center=(60,
                                                Config['game']['bumper_size'] /
                                                2))

            score_rect = score.get_rect(center=(Config['game']['width'] / 2,
                                                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'])

    def generate_observations(self):
        return self.done, self.score, self.snake, self.apple