Пример #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
class Board(object):
    snake = None
    snack = None

    def __init__(self,
                 surface,
                 width,
                 height,
                 rows,
                 cols,
                 colour,
                 human_playing=True,
                 timeout=200):
        self.surface = surface
        self.colour = colour
        self.human_playing = human_playing
        self.timeout = timeout

        self.width = width
        self.height = height
        self.rows = rows
        self.cols = cols
        self.squareWidth = self.width // self.cols
        self.squareHeight = self.height // self.rows

        self.reset_game()

    def update_network(self, network):
        self.network = network

    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)

    def redraw_surface(self):
        self.surface.fill((0, 0, 0))
        self.draw_grid()

        if self.human_playing:
            self.snake.update_dir_human()
            self.move_snake_human()
        else:
            self.snake.update_dir_ai(self.network, self.snack.x, self.snack.y,
                                     self.cols, self.rows)
            self.move_snake_ai()

        self.draw_snake()
        self.draw_snack()
        pygame.display.update()

    def draw_grid(self):
        for x in range(1, self.rows):
            pygame.draw.line(self.surface, WHITE, (0, x * self.squareHeight),
                             (self.width, x * self.squareHeight))

        for y in range(1, self.cols):
            pygame.draw.line(self.surface, WHITE, (y * self.squareWidth, 0),
                             (y * self.squareWidth, self.height))

    def move_snake_ai(self):
        self.snake.move()

        if self.count > self.timeout:
            self.finished = True

        elif not self.snake.valid() or not self.snake_inbounds():
            self.finished = True

        elif [self.snake.head.x,
              self.snake.head.y] == [self.snack.x, self.snack.y]:
            self.score += 100
            self.count = 0
            self.snake.addSquare()
            self.random_snack()

        else:
            new_dist = math.sqrt((self.snake.head.x - self.snack.x)**2 +
                                 (self.snake.head.y - self.snack.y)**2)

            if new_dist > self.snake_snack_dist:
                self.score -= 3
            else:
                self.score += 2

            self.snake_snack_dist = new_dist

        if [self.snake.head.x, self.snake.head.y] == self.sample:
            self.resample = 0
            self.sample_repeat += 1

        elif self.resample == self.resample_limit:
            self.resample = 0
            self.sample_repeat = 0
            self.sample = [self.snake.head.x, self.snake.head.y]

        else:
            self.resample += 1

        if self.sample_repeat >= 3:
            self.score -= 50
            self.finished = True

        self.count += 1

    def move_snake_human(self):
        self.snake.move()

        if not self.snake.valid() or not self.snake_inbounds():
            message_box(
                "You Died!",
                "Your final score was: {}, Start Over?".format(self.score))
            self.reset_game()

        elif [self.snake.head.x,
              self.snake.head.y] == [self.snack.x, self.snack.y]:
            self.score += 100
            self.snake.addSquare()
            self.random_snack()

    def snake_inbounds(self):
        if self.snake.head.x < 0 or self.snake.head.x >= self.cols or self.snake.head.y < 0 or self.snake.head.y >= self.rows:
            return False

        return True

    def draw_snake(self):
        self.snake.draw(self.surface)

    def draw_snack(self):
        self.snack.draw(self.surface)

    def random_snack(self):
        new_x = self.snake.head.x
        new_y = self.snake.head.y

        while [new_x, new_y] in map(lambda square: [square.x, square.y],
                                    self.snake.body):
            new_x = randrange(self.cols)
            new_y = randrange(self.rows)

        self.snack.x = new_x
        self.snack.y = new_y
Пример #7
0
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)
Пример #8
0
 def create_snake(self):
     self.snake = Snake()