day 20
This commit is contained in:
71
020/game.py
Normal file
71
020/game.py
Normal file
@ -0,0 +1,71 @@
|
||||
from turtle import Screen, Turtle
|
||||
from snake import Snake
|
||||
from food import Food
|
||||
import time
|
||||
|
||||
class GameManager:
|
||||
|
||||
BOARD_WIDTH=600
|
||||
BOARD_HEIGHT=600
|
||||
|
||||
def __init__(self):
|
||||
self.screen = Screen()
|
||||
|
||||
self.screen.setup(width=self.BOARD_WIDTH, height=self.BOARD_HEIGHT)
|
||||
self.screen.bgcolor("black")
|
||||
self.screen.title("Snake game")
|
||||
self.screen.tracer(0)
|
||||
self.snake = Snake()
|
||||
self.screen.update()
|
||||
|
||||
self.food_on_screen = False
|
||||
|
||||
self.game_on = True
|
||||
|
||||
def control_snake(self):
|
||||
self.screen.listen()
|
||||
self.screen.onkey(self.snake.up, "Up")
|
||||
self.screen.onkey(self.snake.right, "Right")
|
||||
self.screen.onkey(self.snake.down, "Down")
|
||||
self.screen.onkey(self.snake.left, "Left")
|
||||
self.snake.move()
|
||||
self.screen.update()
|
||||
|
||||
def check_collision(self):
|
||||
x, y = self.snake.get_head_position()
|
||||
wall_collision = x >= self.BOARD_WIDTH/2 or x <= -self.BOARD_WIDTH/2 or y >= self.BOARD_HEIGHT/2 or y <= -self.BOARD_HEIGHT/2
|
||||
snake_collision = self.snake.tailbite()
|
||||
|
||||
return wall_collision or snake_collision
|
||||
|
||||
def is_food_eaten(self):
|
||||
snake_x, snake_y = self.snake.get_head_position()
|
||||
food_x, food_y = self.food.get_position()
|
||||
|
||||
if int(snake_x) == int(food_x) and int(snake_y) == int(food_y):
|
||||
print("Yihaa")
|
||||
self.food.hide()
|
||||
self.snake.extend()
|
||||
self.food_on_screen = False
|
||||
|
||||
def game_round(self):
|
||||
if not self.food_on_screen:
|
||||
self.food = Food(self.BOARD_WIDTH, self.BOARD_HEIGHT)
|
||||
self.food_on_screen = True
|
||||
|
||||
self.control_snake()
|
||||
if self.check_collision():
|
||||
self.game_on = False
|
||||
self.game_over()
|
||||
|
||||
self.is_food_eaten()
|
||||
time.sleep(0.1)
|
||||
|
||||
def get_screen(self):
|
||||
return self.screen
|
||||
|
||||
def game_over(self):
|
||||
turtle = Turtle()
|
||||
turtle.color("yellow")
|
||||
turtle.write("Game over!", move=False, align='center', font=('Arial', 32, 'normal'))
|
||||
|
||||
Reference in New Issue
Block a user