Пример #1
0
    def _create_snake(self, settings):
        """Create snake from settings"""
        # Create list with snake elements images for animation
        step_images_sets = []
        for row_element in settings['game_screen']['snake']['snake_elements']:
            steps_for_element = []
            for row_step in settings['game_screen']['snake']['snake_elements'][
                    row_element]:
                steps_for_element.append(
                    pygame.image.load(
                        settings['game_screen']['snake']['snake_elements']
                        [row_element][row_step]))
            step_images_sets.append(steps_for_element)

        # Translate starting snake direction from settings to game constants
        if settings['game_screen']['snake']['direction'] == "up":
            direction = constants.DIRECTION_UP
        elif settings['game_screen']['snake']['direction'] == "right":
            direction = constants.DIRECTION_RIGHT
        elif settings['game_screen']['snake']['direction'] == "down":
            direction = constants.DIRECTION_DOWN
        elif settings['game_screen']['snake']['direction'] == "left":
            direction = constants.DIRECTION_LEFT

        return Snake(self.screen, self.background_image,
                     settings['game_screen']['snake']['step_length'],
                     self.grid_size,
                     settings['game_screen']['snake']['starting_position_x'],
                     settings['game_screen']['snake']['starting_position_y'],
                     direction, step_images_sets)
Пример #2
0
    def reset_game(self):
        self.score = 0
        self.finished = False
        self.count = 0

        self.resample = 20
        self.resample_limit = 50
        self.sample = [-1, -1]
        self.sample_repeat = 0

        snake_x, snake_y = randrange(3, self.cols - 3), randrange(
            3, self.rows - 3)
        snack_x, snack_y = snake_x, snake_y

        while [snack_x, snack_y] == [snake_x, snake_y]:
            [snack_x, snack_y] = [randrange(self.cols), randrange(self.rows)]

        if self.snake:
            del self.snake
        if self.snack:
            del self.snack

        init_dir_x = choice([0, choice([1, -1])])

        if init_dir_x != 0:
            init_dir_y = 0
        else:
            init_dir_y = choice([1, -1])

        self.snake = Snake(snake_x, snake_y, init_dir_x, init_dir_y, GREEN,
                           self.squareHeight, self.squareWidth)

        self.snack = Square(snack_x, snack_y, 0, 0, RED, self.squareHeight,
                            self.squareWidth)

        self.snake_snack_dist = math.sqrt((snake_x - snack_x)**2 +
                                          (snake_y - snack_y)**2)
Пример #3
0
    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'])
Пример #4
0
import pygame
import time
pygame.init()

from classes.snake import Snake
from classes.food import Food

from modules.constants import *
from modules.colors import *

pygame.display.set_caption('Snake')

clock = pygame.time.Clock()

snake = Snake()
current_food = Food()
current_food.new_position(snake.body)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        keys = pygame.key.get_pressed()
        if keys[pygame.K_RIGHT]:
            snake.h_vel = 1
            snake.v_vel = 0
        elif keys[pygame.K_LEFT]:
            snake.h_vel = -1
            snake.v_vel = 0
Пример #5
0
import random
import pygame
from classes.snake import Snake
from classes.frutinha import Frutinha

if __name__ == "__main__":
    pygame.init()

    resolucao = (500, 500)
    screen = pygame.display.set_mode(resolucao)
    pygame.display.set_caption('Snake')
    clock = pygame.time.Clock()
    preto = (0, 0, 0)

    cobrinha = Snake()
    frutinha = Frutinha(cobrinha)

    while True:
        clock.tick(cobrinha.velocidade)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP or event.key == pygame.K_w:
                    cobrinha.cima()
                    break
                elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
                    cobrinha.baixo()
                    break
                elif event.key == pygame.K_LEFT or event.key == pygame.K_a:
Пример #6
0
 def create_snake(self):
     self.snake = Snake()