StudyRepo_Synergy/part2_OOP/lesson6/snake/game.py

135 lines
3.6 KiB
Python

import os
import time
from random import choice
import pygame as pg
import pygame_menu as pgm
from .snake import Snake
from .food import Food
class Game:
def __init__(self) -> None:
self.screen_widht = 780
self.screen_hight = 600
self.clock = pg.time.Clock()
pg.font.init()
self.font = pg.font.SysFont('arial', 72)
self.score = 0
self.paused = True
self.title = 'Snakessss'
self.done = False # Флаг главного цикла
self.need_reset = False
self.bg = pg.image.load(os.path.join(os.curdir, 'snake', 'img', 'bg.png'))
self.screen = pg.display.set_mode((self.screen_widht, self.screen_hight))
self.fps = 60
self.set_title()
self.menu = None
def game_init(self):
pg.init()
def get_menu(self):
self.set_bg()
self.menu = pgm.Menu('Snakessss game', 400, 300, theme=pgm.pygame_menu.themes.THEME_DARK)
self.menu.add.button('Start new game', self.start_new_game)
self.menu.add.button('Restore game', self.restore_game)
self.menu.add.button('Exit', pgm.pygame_menu.events.EXIT)
self.menu.mainloop(self.screen)
def disable_menu(self):
self.menu.disable()
def set_title(self):
pg.display.set_caption(self.title)
def set_bg(self):
self.screen.blit(self.bg, (0, 0))
def start_new_game(self):
self.paused = False
self.disable_menu()
self.need_reset = True
def restore_game(self):
self.disable_menu()
self.paused = False
def save_game(self):
pass
def load_game(self):
pass
def gameover(self):
surf = self.font.render('Game over', True, (20, 20, 20))
rect = surf.get_rect()
rect.midtop = (390, 250)
self.screen.blit(surf, rect)
pg.display.flip()
time.sleep(3)
self.get_menu()
def mainloop():
game = Game()
game.game_init()
game.set_title()
game.get_menu()
snake =Snake()
foods_array = []
def update_game_window():
while len(foods_array) < 2:
food = Food()
if food.get_coords() not in snake.get_coords():
foods_array.append(food)
for f in foods_array:
if snake.get_head_coords() == f.get_coords():
foods_array.remove(f)
snake.length += 1
game.set_bg()
snake.draw(game.screen)
for f in foods_array:
f.draw(game.screen)
pg.display.update()
if snake.impacted:
game.gameover()
while not game.done:
if game.need_reset:
snake.reset()
game.start_new_game()
game.need_reset = False
for event in pg.event.get():
if event.type == pg.QUIT:
game.done = True
pressed = pg.key.get_pressed()
if pressed[pg.K_ESCAPE]:
game.paused = False if game.paused else True
if game.paused:
game.get_menu()
if pressed[pg.K_UP]:
if snake.direction != 'down':
snake.direction = 'up'
if pressed[pg.K_DOWN]:
if snake.direction != 'up':
snake.direction = 'down'
if pressed[pg.K_LEFT]:
if snake.direction != 'right':
snake.direction = 'left'
if pressed[pg.K_RIGHT]:
if snake.direction != 'left':
snake.direction = 'right'
update_game_window()
game.clock.tick(game.fps)