90 lines
2.4 KiB
Python
90 lines
2.4 KiB
Python
import os
|
|
import time
|
|
from random import choice
|
|
|
|
import pygame as pg
|
|
|
|
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(choice(pg.font.get_fonts()), 72)
|
|
self.score = 0
|
|
|
|
self.title = 'Snakessss'
|
|
self.done = 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
|
|
|
|
def game_init(self):
|
|
pg.init()
|
|
|
|
def set_title(self):
|
|
pg.display.set_caption(self.title)
|
|
|
|
def set_bg(self):
|
|
self.screen.blit(self.bg, (0, 0))
|
|
|
|
def gameover(self):
|
|
self.done = True
|
|
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(5)
|
|
pg.quit()
|
|
|
|
|
|
def mainloop():
|
|
game = Game()
|
|
snake =Snake(90, 300)
|
|
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:
|
|
for event in pg.event.get():
|
|
if event.type == pg.QUIT:
|
|
game.done = True
|
|
pressed = pg.key.get_pressed()
|
|
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)
|