Código para Crear Snake en Python Con El Módulo Turtle
Código para Crear Snake en Python Con El Módulo Turtle
MAIN (main.py)
import time
screen = Screen()
screen.setup(600, 600)
screen.title("Snake")
screen.colormode(255)
screen.tracer(0)
snake = Snake()
screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
score = Score()
food = Food()
game_is_on = True
while game_is_on:
time.sleep(0.1)
screen.update()
snake.move()
snake.add_segments()
food.refresh()
score.increase_score()
if game_mode == 'y':
game_is_on = False
score.high_s()
game_is_on = False
score.high_s()
else:
snake.head.goto(-280, snake.head.ycor())
snake.head.goto(snake.head.xcor(), -280)
snake.head.goto(280, snake.head.ycor())
score.high_s()
game_is_on = False
screen.exitonclick()
FOOD (food.py)
import random
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.penup()
self.color(255, 128, 0)
self.shapesize(0.5)
self.refresh()
def refresh(self):
self.goto(pos_x, pos_y)
SCORE (score.py)
ALIGNMENT = "center"
class Score(Turtle):
def __init__(self):
super().__init__()
self.score = 0
self.high_score = int(data.read())
self.hideturtle()
self.penup()
self.goto(0, 270)
self.update_score()
def update_score(self):
self.clear()
def increase_score(self):
self.score += 1
self.clear()
self.update_score()
def high_s(self):
self.high_score = self.score
with open("data.txt", "w") as hs:
hs.write(str(self.score))
SNAKE (snake.py)
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake:
def __init__(self):
self.segments = []
self.create_snake()
self.head = self.segments[0]
def create_snake(self):
segment = Turtle("turtle")
segment.penup()
segment.goto(position)
segment.color(153, 0, 153)
self.segments.append(segment)
self.segments[0].color(0, 0, 0)
def add_segments(self):
segment = Turtle("turtle")
segment.penup()
segment.goto(self.segments[1].xcor(), self.segments[1].ycor())
segment.color(153, 0, 153)
self.segments.append(segment)
def move(self):
self.segments[segment].goto(x_cor, y_cor)
self.head.forward(20)
def up(self):
if self.head.heading() != DOWN:
self.head.setheading(UP)
def down(self):
if self.head.heading() != UP:
self.head.setheading(DOWN)
def left(self):
if self.head.heading() != RIGHT:
self.head.setheading(LEFT)
def right(self):
if self.head.heading() != LEFT:
self.head.setheading(RIGHT)