خود دا هو الكود
ملف main
import time
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
# Set up window
window=Screen()
window.bgcolor("black")
window.setup(width=600,height=600)
window.title('Snake game')
window.tracer(0)
snake=Snake()
food= Food()
score=Scoreboard()
game_on=True
while game_on:
snake.move()
window.update()
time.sleep(.1)
window.listen()
window.onkey(snake.up,"Up")
window.onkey(snake.down,"Down")
window.onkey(snake.left,"Left")
window.onkey(snake.right,"Right")
if snake.head.distance(food)< 20:
food.appear() # Hide the food and change it place
snake.extend()
score.update_score()
if (
snake.head.xcor() > 280
or
snake.head.xcor() < -280
or
snake.head.ycor() > 280
or
snake.head.ycor() < -280
):
game_on=False
score.game_over()
for segment in snake.turtles[:-1]:
if snake.head.distance(segment) < 10:
score.game_over()
game_on=False
break
window.exitonclick()
ملف الثعبان snake
from turtle import Turtle
class Snake:
def __init__(self):
self.position=[(-20,0),(0,0),(20,0)]
self.turtles=[] # Store snake parts
self.create_snake()
self.head=self.turtles[-1]
def create_snake(self):
for i in range (len(self.position)):
new_turtle=Turtle('square')
new_turtle.color("white")
new_turtle.up()
new_turtle.goto(self.position[i])
self.turtles.append(new_turtle)
def extend(self):
new_segment=Turtle("square")
new_segment.color("white")
new_segment.up()
new_segment.goto(self.turtles[0].pos())
self.turtles.insert(0,new_segment)
def move(self):
for i in range(len(self.turtles)-1):
self.turtles[i].goto(self.turtles[i+1].pos())
self.turtles[-1].fd(20)
def up(self):
self.head.setheading(90)
def down(self):
self.head.setheading(270)
def left(self):
self.head.setheading(180)
def right(self):
self.head.setheading(0)
ملف الطعام food
import random
from turtle import Turtle
class Food(Turtle):
def __init__(self):
super().__init__() # to inhert the attributs and methods of class turtle
self.up()
self.color('gray')
self.shape("circle")
self.shapesize(.5,.5)
self.appear()
def appear(self):
random_coor=random.randint(-280,280)
self.goto(random_coor,random_coor)
ملف النتائج score
from turtle import Turtle
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.score = 0
self.up()
self.hideturtle()
self.color('white')
self.goto(0,260)
self.writing()
def writing(self):
self.clear() # clear the previos write
self.write(f'Score: {self.score}',align="center",font=("Arial",24,'normal'))
def update_score(self):
self.score+=1
self.writing()
def decrease_score(self):
self.score-=1
self.writing()
def game_over(self):
self.getscreen().bgcolor("darkred")
self.home()
self.color('black')
self.write(f"Game over\nFinal score{self.score}",align="center",font=("Arial",24,'normal'))