console_snake/player.py

63 lines
2.1 KiB
Python
Raw Permalink Normal View History

2022-10-26 21:57:29 +03:00
from settings import *
from point import Point
from food import Food
class Player:
2023-03-06 01:30:06 +03:00
def __init__(self) -> None:
self.start_direciton = MAIN_DIRECTION
2022-10-26 21:57:29 +03:00
self.direction = MAIN_DIRECTION
self.body = [Point(MAIN_X, MAIN_Y)]
self.food = Food(0, 0)
2022-10-26 21:57:29 +03:00
self.food.generate_new()
2022-10-27 00:29:36 +03:00
self.score = 1
2022-10-26 21:57:29 +03:00
2022-10-27 00:29:36 +03:00
def input(self) -> None:
2022-10-26 21:57:29 +03:00
if self.direction == D_UP:
self.body.append(Point(self.body[-1].x, self.body[-1].y - 1))
elif self.direction == D_DOWN:
self.body.append(Point(self.body[-1].x, self.body[-1].y + 1))
elif self.direction == D_LEFT:
self.body.append(Point(self.body[-1].x - 1, self.body[-1].y))
elif self.direction == D_RIGHT:
self.body.append(Point(self.body[-1].x + 1, self.body[-1].y))
2022-10-27 15:29:28 +03:00
def _check_collision(body: list[Point]) -> None:
for point in body:
if point.x < 0 or point.y < 0:
raise IndexError("Snake has collision with walls")
elif point.x >= WIDTH or point.y >= HEIGHT:
raise IndexError("Snake has collision with walls")
if len(set(body)) != len(body):
raise IndexError("Player has collision with self")
2022-10-27 00:29:36 +03:00
def update(self) -> None:
2023-03-06 01:30:06 +03:00
self.start_direction = self.direction
2022-10-26 21:57:29 +03:00
if self.body[-1] == self.food:
self.food.generate_new()
2022-10-26 23:43:49 +03:00
self.score += 1
2022-10-26 21:57:29 +03:00
else:
self.body.pop(0)
2022-10-27 15:29:28 +03:00
Player._check_collision(self.body)
2022-10-26 21:57:29 +03:00
2022-11-06 22:18:02 +03:00
def left(self, game) -> None:
2023-03-06 01:30:06 +03:00
if not game.is_pause and self.start_direction != D_RIGHT:
2022-11-06 22:18:02 +03:00
self.direction = D_LEFT
2022-10-26 21:57:29 +03:00
2022-11-06 22:18:02 +03:00
def right(self, game) -> None:
2023-03-06 01:30:06 +03:00
if not game.is_pause and self.start_direction != D_LEFT:
2022-11-06 22:18:02 +03:00
self.direction = D_RIGHT
2022-10-26 21:57:29 +03:00
2022-11-06 22:18:02 +03:00
def up(self, game) -> None:
2023-03-06 01:30:06 +03:00
if not game.is_pause and self.start_direction != D_DOWN:
2022-11-06 22:18:02 +03:00
self.direction = D_UP
2022-10-26 21:57:29 +03:00
2022-11-06 22:18:02 +03:00
def down(self, game) -> None:
2023-03-06 01:30:06 +03:00
if not game.is_pause and self.start_direction != D_UP:
2022-11-06 22:18:02 +03:00
self.direction = D_DOWN