Example #1
0
class SnakeGame:
    canvas = (0, 0, 500, 500)
    grid = None
    step = 10

    SPEED = 20
    run = True

    def __init__(self,
                 index,
                 canvas,
                 screen,
                 step=20,
                 showGrid=True,
                 log=True):
        self.clock = pygame.time.Clock()

        self.canvas = canvas
        self.screen = screen
        self.showGrid = showGrid
        self.step = step
        self.index = index
        self.log = log
        self.grid = [i // step for i in canvas[2:]]

        self.printMessage('Initialize grid:', self.grid)

        self.snake = Snake(index, [i // 2 for i in self.grid], step, self.grid,
                           3, log)
        self.apple = Apple(index, self.grid, step, log)

    def printMessage(self, *message):
        if self.log:
            print(f'\033[1;33;40mGame[{self.index}]:\033[0m', *message)

    def listenToEvents(self, events):
        step = None

        for event in events:
            if (event.type == pygame.QUIT):
                self.run = False
            elif event.type == pygame.KEYDOWN:

                if event.key == pygame.K_w:
                    self.SPEED += 10
                    self.printMessage('Speed:', self.SPEED)

                elif event.key == pygame.K_s:
                    self.SPEED -= 10 if self.SPEED - 10 > 0 else 0
                    self.printMessage('Speed:', self.SPEED)

    def moveSnake(self, direction):
        self.snake.move(direction, self.apple.pos, self.apple.setPos)

    def drawGrid(self):
        color = (150, ) * 3
        [x, y, w, h] = self.canvas

        if self.showGrid:
            for i in range(self.grid[1]):
                dy = self.step * i

                for j in range(1, self.grid[0]):
                    dx = self.step * j

                    pygame.draw.line(self.screen, color, (x + dx, y),
                                     (x + dx, y + h - 1))
                    pygame.draw.line(self.screen, color, (x, y + dy),
                                     (x + w - 1, y + dy))

        pygame.draw.rect(self.screen, (255, ) * 3, (x, y, w, h), 1)

    def clean(self):
        # Fill canvas with black
        if self.screen:
            pygame.draw.rect(self.screen, (0, ) * 3, self.canvas)

    def draw(self, events, getDirection):
        if not self.run:
            if self.screen:
                pygame.draw.rect(self.screen, (0, ) * 3, self.canvas)
            return

        self.clean()
        self.clock.tick(self.SPEED)

        # Event Handler
        # events = pygame.event.get()
        self.listenToEvents(events)
        self.moveSnake(getDirection(events))

        # Draw
        if self.screen:
            self.drawGrid()
            self.snake.draw(self.screen, self.canvas[:2])
            self.apple.draw(self.screen, self.canvas[:2])

        # Check if it a game over
        if not self.snake.alive:
            self.run = False

        # Flip the display
        if self.screen:
            pygame.display.flip()
Example #2
0
class App:
    windowWidth = 800
    windowHeight = 600
    player = 0
    apple = 0

    def __init__(self):
        self._running = True
        self._display_surf = None
        self._image_surf = None
        self.player = Player(1)
        self.apple = Apple()
        self.game = Game()

    def on_init(self):
        pygame.init()
        self._display_surf = pygame.display.set_mode(
            (self.windowWidth, self.windowHeight), pygame.HWSURFACE)
        pygame.display.set_caption('SnakePyGame')
        self._running = True

        self._image_surf = pygame.image.load(
            "../static/green-square.png").convert()
        self._apple_surf = pygame.image.load("../static/logo.png").convert()

    def score(self, input_text, font_size, width, height):
        text = pygame.font.Font('freesansbold.ttf', font_size)
        text_surf = text.render(str(input_text), True, (255, 255, 255))
        #text_rect = text_surf.get_rect().center = (width, height)
        self._display_surf.blit(text_surf, (width, height))  #text_rect)
        pygame.display.update()

    def on_event(self, event):
        if event.type == QUIT:
            self._running = False

    def crash(self):
        self.score("YOU LOSE!", 150, self.windowWidth / 50,
                   self.windowHeight / 2.7)
        self.score("Your Score: " + str(self.player.length - 1), 70,
                   (self.windowWidth / 4.2), (self.windowHeight / 1.5))

    def on_loop(self):
        self.player.update()
        apple_step = 25
        eat_flag = True
        flag = True

        #snake eat apple
        for i in range(0, self.player.length):
            if self.game.is_collision(self.apple.x, self.apple.y,
                                      self.player.x[i], self.player.y[i],
                                      apple_step):
                if i != 0:
                    self.game.apple_collision(self.apple, self.player,
                                              apple_step)
                elif i == 0:
                    self.game.apple_collision(self.apple, self.player,
                                              apple_step)
                    self.player.length = self.player.length + 1

        #find collision
        for i in range(2, self.player.length):
            if self.game.is_collision(self.player.x[0], self.player.y[0],
                                      self.player.x[i], self.player.y[i], 40):
                print("You lose! Collision: ")
                print("x[0] (" + str(self.player.x[0]) + "," +
                      str(self.player.y[0]) + ")")
                print("x[" + str(i) + "] (" + str(self.player.x[i]) + "," +
                      str(self.player.y[i]) + ")")
                self.crash()
                sleep(3)
                exit(0)

        if self.game.out_of_map(self.player.x[0], self.player.y[0],
                                self.windowWidth, self.windowHeight):
            self.crash()
            sleep(3)
            exit(0)

    def on_render(self):
        self._display_surf.fill((0, 0, 0))
        self.player.draw(self._display_surf, self._image_surf)
        self.apple.draw(self._display_surf, self._apple_surf)
        #self.score("Score: " + str(self.player.length - 1), 25, (self.windowWidth / 1.2), (self.windowHeight / 50))
        pygame.display.flip()

    def on_cleanup(self):
        pygame.quit()

    def on_execute(self):
        right_flag = True
        left_flag = True
        up_flag = True
        down_flag = True

        if self.on_init() is False:
            self._running = False

        while (self._running):
            pygame.event.pump()
            keys = pygame.key.get_pressed()

            for event in pygame.event.get():
                self.on_event(event)

            if (keys[K_RIGHT] and right_flag):
                self.player.moveRight()
                left_flag = False
                up_flag = True
                down_flag = True

            if (keys[K_LEFT] and left_flag):
                self.player.moveLeft()
                right_flag = False
                up_flag = True
                down_flag = True

            if (keys[K_UP] and up_flag):
                self.player.moveUp()
                down_flag = False
                left_flag = True
                right_flag = True

            if (keys[K_DOWN] and down_flag):
                self.player.moveDown()
                up_flag = False
                right_flag = True
                left_flag = True

            if (keys[K_ESCAPE]):
                self._running = False

            self.on_loop()
            self.on_render()
            #self.score("Score: " + str(self.player.length - 1), 25, (self.windowWidth / 1.2), (self.windowHeight / 50))
            #pygame.display.update()
            sleep(50.0 / 1000.0)
        self.on_cleanup()