Exemplo n.º 1
0
def play():
    pygame.init()  # инициализируем библиотеку pygame
    window = pygame.display.set_mode((441, 480))  # создание окна c размером
    pygame.display.set_caption("Змейка")  # задаём название окна
    control = Control()
    snake = Snake()
    bot = Bot()
    #is_basic True -- запуск обычный, False -- запуск рандомной карты из файлов
    gui = Gui(is_basic=False)
    food = Food()
    gui.init_field()
    food.get_food_position(gui, snake.body, bot.body)
    var_speed = 0  # переменная для регулировки скорости выполнения программы

    #gui.create_image()

    while control.flag_game:
        gui.check_win_lose(snake.body)
        control.control()
        window.fill(pygame.Color(
            "Black"))  # закрашивание предыдущего квадрата чёрным цветом
        if gui.game == "GAME":  # если флаг равен "GAME"
            snake.draw_snake(
                window)  # то вызываем метод отрисовки змеи на экране
            bot.draw_snake(window)  #отрисовка бота-змеи
            if (food.timer <= 0):  # проверка на жизнь еды
                food.get_food_position(gui, snake.body, bot.body)
            food.draw_food(window)  # и метод отрисовки еды
        elif gui.game == "WIN":  # если флаг равен "WIN"
            if (bot.points <=
                    snake.points):  #проверка очков, кто больше набрал
                gui.draw_win(window)
            else:
                gui.draw_lose(window)
        elif gui.game == "LOSE":  # если флаг равен "LOSE"
            gui.draw_lose(window)  # то отрисовываем избражение поражения
        gui.draw_indicator(window)
        gui.draw_level(window)
        if var_speed % 50 == 0 and control.flag_pause:  # если делится без остатка, то производим изменение координаты квадрата and реакция на паузу
            snake.moove(control.flag_direction)
            snake.check_barrier(gui)

            mv = ""  #проверка бота, все ли работает правильно (можно убрать, но так спокойнее)
            try:
                mv = bot.move(food.food_position, gui.level)
            except:
                mv = bot.move(food.food_position, gui.level)
            #print(mv)
            bot.moove(mv)
            #не трубуется, тк бот никогда к ним не подлезет bot.check_barrier(gui)
            #проверка на съедение и генерация новой еды вне тела змеи
            if snake.eat(food, gui) or bot.eat(food, gui):
                food.get_food_position(gui, snake.body, bot.body)

            bot.check_end_window()
            snake.check_end_window()
            bot.animation()
            snake.animation()
        var_speed += 1
        pygame.display.flip()  # метод отображения окна
Exemplo n.º 2
0
def run_game():
    """
    Основной цикл игры.
    """
    global score
    score = 0
    player = Snake()
    food = Food()

    # Цикл игры.
    while True:
        # Закрашиваем экран.
        screen.fill(game_settings.BACKGROUND_COLOR)

        # Проверяем нажатие клавиш.
        check_events(player)

        # Двигаем змейку.
        player.snake_moving()

        # Отрисовываем змейку на актуальных координатах.
        player.draw_snake(screen)

        # Отрисовываем еду.
        food.draw_food(screen)

        # Если есть столкновение головы с телом\краем игрового окна - конец.
        if collision.game_over(player, game_settings.SCREEN_WIDTH_AND_HEIGHT,
                               game_settings.CELL_SIZE):
            break

        # Если змейка поела - растёт и получает баллы.
        if collision.food_eaten(player, food):
            player.add_new_segment()
            food.create_new_food()
            score += 1

            # Не создаем еду поверх змейки.
            while collision.poor_cooking(player, food):
                food.create_new_food()

        # Обновляем экран.
        pygame.display.update()

    play_again()
Exemplo n.º 3
0
window = pygame.display.set_mode((441, 441))
pygame.display.set_caption("Snake")
control = Control()
snake = Snake()
food = Food()
gui = Gui()
gui.init_field()
food.generate_food_position(gui)

while control.flag_game:
    gui.check_win_or_lose()
    control.control()
    window.fill(pygame.Color("Black"))
    if gui.game == "GAME":
        snake.draw_snake(window)
        food.draw_food(window)
        if not control.flag_pause:
            snake.move(control)
            snake.check_barrier(gui)
            snake.eat(food, gui)
            snake.check_end_window()
            snake.animation()
        gui.draw_progress(window)
        gui.draw_level(window)
    elif gui.game == "WIN":
        gui.draw_win(window)
    elif gui.game == "LOSE":
        gui.draw_lose(window)
    pygame.display.flip()
    time.sleep(0.1)
pygame.quit()
Exemplo n.º 4
0
class Snake(object):
    """This class draws and operates the line for Snake game"""
    def __init__(self, pen, food_pen):
        """Constructor for Square class. This funcion is called upon 
        initialization. It saves a turtle object as a class member,
        start line length to 5, creates list of Squares, set direction
        to 'r', default speed to 1, creates food for snake and creates
        snake itself.

        Parameters
        ----------
        pen : turtle
            Turtle object that will draw the square
        food_pen : turtle
            Turtle object that will draw the food
        Returns
        -------
        None
        """
        
        self.speed = 1
        self.snake = []
        self.direction = 'r'
        self.length = 5

        self.pen = pen
        self.food_pen = food_pen

        # creating initial snake
        for i in range(self.length):
            square = Square(self.pen)
            square.set_square(i*-square.size, square.size)
            self.snake.append(square)
        
        self.food = Food(self.food_pen)
        self.food.create_food()
        
    def set_direction(self,value):
        """Change direction of the snake. Possible directions are: 
        `r`, `l`, `u`, `d`.
        Parameters
        ----------
        value : str
            New snake direction
        Returns
        -------
        None
        """
        if self.direction == 'r' and value != 'l':
            self.direction = value
        if self.direction == 'l' and value != 'r':
            self.direction = value
        if self.direction == 'u' and value != 'd':
            self.direction = value
        if self.direction == 'd' and value != 'u':
            self.direction = value
       
    def self_collision(self):
        """Check snake collision with itself.
        Parameters
        ----------
        None
        Returns
        -------
        collision
            bool
        """
        collision = False
        for sqr in range(1,len(self.snake)):
            if self.snake[0].x == self.snake[sqr].x and self.snake[0].y == self.snake[sqr].y:
                collision = True
        return collision
    
    def border_collision(self):
        """Check snake collision with border.
        Parameters
        ----------
        None
        Returns
        -------
        collision
            bool
        """
        collision = False
        if self.snake[0].x > 200 or self.snake[0].x < -200:
            collision = True
        elif self.snake[0].y > 200 or self.snake[0].y < -200:
            collision = True
        
        return collision

    def draw_snake(self):
        """Draw snake.
        Parameters
        ----------
        None
        Returns
        -------
        None
        """
        for i in range(len(self.snake)):
            self.snake[i].draw(self.snake[i].x,self.snake[i].y, "black")

    def move_snake(self):
        """Move snake.
        Parameters
        ----------
        None
        Returns
        -------
        None
        """
        old_x = self.snake[0].x
        old_y = self.snake[0].y
    
        for square in range(len(self.snake)):
            if square == 0: 
                old_x = self.snake[square].x
                if self.direction == "r":  
                    self.snake[square].x += self.snake[0].size
                elif self.direction == "l":
                    self.snake[square].x -= self.snake[0].size
                elif self.direction == "u":
                    self.snake[square].y += self.snake[0].size
                elif self.direction == "d":
                    self.snake[square].y -= self.snake[0].size
            else:
                old_x, self.snake[square].x = self.snake[square].x, old_x
                old_y, self.snake[square].y = self.snake[square].y, old_y

    def food_collision(self,x,y):
        """Check collision with food.
        Parameters
        ----------
        x
            Horisontal Coordinate
        y
            Vertical Coordinate
        Returns
        -------
        collision
            bool
        """
        
        collision = False

        # food_collision
        if self.food.collision_with_food(x,y):
            # add square to the snake
            square = Square(self.pen)
            square.set_square(x,y)
            self.snake.append(square)

            # make snake move faster
            self.increase_speed()    
            
            # make more food
            self.food.create_food()
            self.food.draw_food()

            # increase the length of the snake
            self.length += 1
            
            collision = True
        
        return collision
    
    def increase_speed(self):
        """Incerease speed of the snake.
        Parameters
        ----------
        None
        Returns
        -------
        None
        """
        
        self.speed += 1
Exemplo n.º 5
0
pygame.init()
win = pygame.display.set_mode((441, 441))
pygame.display.set_caption("Змійка")
control = Control()
snake = Snake()
qui = Qui()
food = Food()
qui.init_field()
food = Food()
food.get_food_position(qui)

while control.Flag_game:
    # pygame.time.delay(var_speed0)
    control.control()
    win.fill(pygame.Color("Black"))
    snake.snake_die(qui)
    if qui.game == "GAME":
        snake.draw_snake(win)
        food.draw_food(win)
        # qui.socer(win)
    elif qui.game == 'LOSE':
        win.blit(qui.lose, (23, 100))
    if snake.run % 700 == 0:
        snake.moove(control)
        snake.chec_win()
        snake.eat(food, qui)
        snake.animation()
    # var_speed += 3
    snake.var_s(food)
    pygame.display.flip()
Exemplo n.º 6
0
pygame.display.set_caption("Snake game")
control = Control()  # объект класса
snake = Snake()  # объект класса
gui = Gui()  # объект класса
food = Food()
gui.init_field()
food.get_food_position(gui)
speed = 0

while control.run:
    gui.check_win_lose()
    control.control()
    window.fill((255, 255, 255))
    if gui.game == "GAME":
        snake.draw(window)  # рисуем голову змеи
        food.draw_food(window)  # рисуем еду
    elif gui.game == "WIN":
        gui.draw_win(window)
    elif gui.game == "LOSE":
        gui.draw_lose(window)

    gui.draw_indicator(window)  # рисуем индикатор
    gui.draw_level(window)  # рисуем карту
    pygame.display.update()  # обновление, что бы появился персонаж
    if speed % 10 == 0 and gui.game == "GAME":
        snake.moove_snake(control)
        snake.check_barrier(gui)
        snake.eat(food, gui)
        snake.end_window()
        snake.animation()
    speed += 1
Exemplo n.º 7
0
class Game:
    def __init__(self, game_name):
        self.game_name = game_name
        # задаємо розміри екрану
        self.screen_width = 720
        self.screen_height = 460
        self.play_surface = pygame.display.set_mode(
            (self.screen_width, self.screen_height))

        # необхідні кольори
        self.red = pygame.Color(255, 0, 0)
        self.green = pygame.Color(0, 255, 0)
        self.black = pygame.Color(0, 0, 0)
        self.white = pygame.Color(255, 255, 255)
        self.brown = pygame.Color(165, 42, 42)

        # задає кількість кадрів в секуну
        self.fps_controller = pygame.time.Clock()

        # змінна для відображення результату
        # (скільки їжі зїли)
        self.score = 0
        pygame.display.set_caption(self.game_name)
        self.snake = Snake(self.green)
        self.food = Food(self.brown, self.screen_width, self.screen_height)
        self.wall = Wall(self.white)
        self.difficulty = 10
        self.ratio = 10
        self.playername = "Gamer"
        self.is_wall = False
        self.wall_start_time = None
        pygame.init()

    def init_menu(self):
        self.menu = pygame_menu.Menu(height=400,
                                     width=600,
                                     theme=pygame_menu.themes.THEME_GREEN,
                                     title=self.game_name)

        self.menu.add_image('Images/snake_menu_hard.png', scale=(0.4, 0.4))
        self.menu.add_text_input('Name: ',
                                 default=self.playername,
                                 onchange=self.set_playername)
        self.menu.add_selector('Difficulty: ', [('Easy', 1), ('Hard', 2),
                                                ('Hell', 3)],
                               onchange=self.set_difficulty)
        self.menu.add_button('Play', self.start_the_game)
        self.menu.add_button('Quit', pygame_menu.events.EXIT)
        self.menu.mainloop(self.play_surface)

    def set_difficulty(self, selected, value):
        """
        Встановіть складність гри.
        """
        if value == 1:
            self.difficulty = 10
            self.ratio = 10

        elif value == 2:
            self.difficulty = 20
            self.ratio = 20
        else:
            self.difficulty = 100
            self.ratio = 50

    def set_playername(self, value):
        self.playername = value

    def start_the_game(self):
        """
        Функція, яка починає гру.
        """
        while True:
            self.snake.change_to = self.event_loop(self.snake.change_to)
            self.snake.validate_direction_and_change()
            self.snake.change_head_position()
            self.score, self.food.food_pos = self.snake.snake_body_mechanism(
                self.score, self.food.food_pos, self.screen_width,
                self.screen_height)
            self.play_surface.fill(self.black)
            self.snake.draw_snake(self.play_surface)

            self.food.draw_food(self.play_surface)

            if not self.is_wall:
                self.wall_start_time = datetime.now()
                if randint(1, 100) <= self.ratio:
                    self.wall.wall_generation_mechanism(
                        self.screen_width, self.screen_height, self.ratio)
                    if not self.wall.is_snake_in_wall(self.snake.snake_body):
                        self.is_wall = True
                        self.wall.draw_wall(self.play_surface)
                    else:
                        self.wall.wall_body = []
            else:
                self.wall.draw_wall(self.play_surface)
                if datetime.now() >= self.wall_start_time + timedelta(
                        seconds=randint(5, 45)):
                    self.wall.wall_body = []
                    self.is_wall = False

            self.snake.check_for_death(self.game_over, self.screen_width,
                                       self.screen_height, self.wall)

            self.show_score()
            self.refresh_screen()

    def event_loop(self, change_to):
        """ Функція для відстеження натискань клавіш гравцем """

        # запускаємо цикл по івент
        for event in pygame.event.get():
            # якщо натиснули клавишу
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT or event.key == ord('d'):
                    change_to = "RIGHT"
                elif event.key == pygame.K_LEFT or event.key == ord('a'):
                    change_to = "LEFT"
                elif event.key == pygame.K_UP or event.key == ord('w'):
                    change_to = "UP"
                elif event.key == pygame.K_DOWN or event.key == ord('s'):
                    change_to = "DOWN"
                # натиснули escape
                elif event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        return change_to

    def refresh_screen(self):
        """Оновлюємо екран і задаємо фпс """
        pygame.display.flip()
        self.fps_controller.tick(self.difficulty)

    def show_score(self):
        """Відображення результату"""
        pygame.display.set_caption(f"{self.game_name} Score: {self.score}")

    def game_over(self):
        """Функція для виведення напису Game Over і результатів
        в разі завершення гри і вихід з гри"""
        go_font = pygame.font.SysFont('monaco', 72)
        go_surf = go_font.render('Game over', True, self.red)
        go_rect = go_surf.get_rect()
        go_rect.midtop = (360, 15)
        p_font = pygame.font.SysFont('monaco', 40)
        p_surf = p_font.render('Player: {0}'.format(self.playername), True,
                               self.red)
        p_rect = p_surf.get_rect()
        p_rect.midtop = (360, 90)

        s_font = pygame.font.SysFont('monaco', 24)
        s_surf = s_font.render('Score: {0}'.format(self.score), True, self.red)
        s_rect = s_surf.get_rect()
        s_rect.midtop = (360, 120)
        self.play_surface.blit(go_surf, go_rect)
        self.play_surface.blit(p_surf, p_rect)
        self.play_surface.blit(s_surf, s_rect)
        pygame.display.flip()
        time.sleep(3)
        self.restart_game()

    def restart_game(self):
        self.snake.snake_head_pos = [100, 50]
        self.snake.snake_body = [[100, 50], [90, 50], [80, 50]]
        self.snake.direction = "RIGHT"
        self.snake.change_to = self.snake.direction
        self.wall.wall_body = []
        self.is_wall = False
        self.score = 0
        self.init_menu()
Exemplo n.º 8
0
    # food.present_food
    # food.food_pos.flatten()
    #a1 = np.array(food.present_food)
    #a2 = food.food_pos.flatten()
    #a3 = np.array(snake.snake_head_pos)
    #a4 = np.array(self.snake_body + [0 for i in range(maxlen - #len(self.snake_body))]).flatten()
    #s = np.concatenate((a1, a2, a3, a4), axis=0)
    #s = [acid1(x, y, type), acid2, acid3, goal_food, self.snake_head_pos,
    #                    np.array(self.snake_body + [0 for i in range(maxlen - #len(self.snake_body))]).flatten()])

    #пока игра не окончена, будут повторяться следующие действия - env.step. по сути
    if game.game_is_runned:
        snake.proceed_game()

        snake.draw_snake(game.display)
        food.draw_food(game.display)
        game.show_score()

        if not game.game_is_runned:
            food = Food(game.screen_width, game.screen_height,
                        Snake.dafault_snake_body)
            snake = Snake(game, food)

    #r, done  = env.step()

    #a1 = np.array(food.present_food)
    #a2 = food.food_pos.flatten()
    #a3 = np.array(snake.snake_head_pos)
    #a4 = np.array(self.snake_body + [0 for i in range(maxlen - #len(self.snake_body))]).flatten()
    #next_s = np.concatenate((a1, a2, a3, a4), axis=0)
    def main(self):
        pygame.init()

        gameClock = pygame.time.Clock()

        gameClock.tick(60)

        field, x, y = [], 5, 5
        while x < 495:
            while y < 495:
                field.append([x, y])
                y += 10
            y = 5
            x += 10

        window = pygame.display.set_mode((500, 500))  # Экран
        pygame.display.set_caption('Змейка')

        control = Control()  #Создаем персонажей
        snake = Snake()
        food = Food()
        food.get_food_pos(field)

        sound1 = pygame.mixer.Sound('music\punch.wav')
        sound2 = pygame.mixer.Sound('music\st.wav')

        var_speed = 0
        end = True

        while control.done:  #Цикл программы
            control.control()
            window.fill(pygame.Color("Black"))
            food.draw_food(window)
            snake.draw_snake(window)

            gameT = pygame.time.get_ticks()
            self.drawTime(gameT, window)
            self.drawGameScore(snake.score, window)

            if not control.fl_pause and var_speed % 10 == 0 and end:
                if snake.head in snake.body[
                        1:]:  #Движение змеи и поглощение еды
                    end = False
                snake.move(control)
                snake.eat(food, field)
                snake.animation()
            elif control.fl_pause and end:  #Пауза
                self.pause(window)
            elif not end and snake.score != 4:  #Проигрыш
                self.bad_end(window, sound1)
            elif snake.score == 4:  #Победа
                end = False
                self.good_end(window, field, sound2)

            var_speed += 1

            if control.ng and (not end
                               or snake.score == 4):  #Конец или новая игра
                endgame = EndGame()
                endgame.new_game(self)
                break
            elif control.end and not end:
                control.done = False

            pygame.display.update()
            all_sprites.update()
        pygame.quit()