Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import turtle
- import time
- import random
- delay = 0.1
- wn = turtle.Screen()
- wn.title("My first Snake game!")
- wn.bgcolor("blue")
- wn.setup(width=600, height=600)
- wn.tracer(0)
- #Note: wn.tracer turns off the animations/screen updates
- #Note:This is a setup for the screen so mess around with the colors, width, height!
- #Snake head time!
- head = turtle.Turtle()
- head.speed( 0)
- #note: head.speed is the speed of the animation
- head.shape("square")
- head.color("yellow")
- head.penup()
- #Note: Penup is for writing on the screen thats why i didnt put anything
- head.goto(0,0)
- #Note: head.goto is the location
- head.direction = "stop"
- #Snake food
- food = turtle.Turtle()
- food.speed( 0)
- food.shape("circle")
- food.color("red")
- food.penup()
- food.goto(0,100)
- segments = []
- # Functions
- def go_up():
- head.direction = "up"
- def go_down():
- head.direction = "down"
- def go_right():
- head.direction = "right"
- def go_left():
- head.direction = "left"
- # Functions
- def move():
- if head.direction == "up":
- y = head.ycor()
- head.sety(y + 20) #When I call a move function if the head direction is up it will move 20 pixels
- if head.direction == "down":
- y = head.ycor()
- head.sety(y - 20)
- if head.direction == "right":
- x = head.xcor()
- head.setx(x + 20)
- if head.direction == "left":
- x = head.xcor()
- head.setx(x - 20) #This code can also work to reduce one line. The code is head.sety(head.xcor() - 20)
- #Important: if it left/right its x and up and down is y so you'll need to change it from head.ycor to head.xcor, aswell as head.sety to head.setx
- # Keybinds
- wn.listen()
- wn.onkeypress(go_up, "w") #note: at line 29, it is go_up() while its (go_up,. dont make that mistake or it will not run.
- wn.onkeypress(go_down, "s")
- wn.onkeypress(go_right, "d")
- wn.onkeypress(go_left, "a")
- #Main game loop
- while True:
- wn.update() #This updates the screen so our snake can move
- # Check for a collision with the food
- if head.distance(food) < 20:
- #Move the food to a random spot
- x = random.randint(-290, 290)
- y = random.randint(-290, 290)
- food.goto(x,y)
- # Add a segemnt
- new_segment = turtle.Turtle()
- new_segment.speed(0)
- new_segment.shape("square")
- new_segment.color("grey")
- new_segment.penup()
- segments.append(new_segment)
- # Move the end segments first
- for index in range(len(segments)-1, 0, -1)
- x = segments[index-1].xcor()
- y = segments[index-1].ycor()
- segments[index].goto(x, y)
- # Move segment 0 to where the head is
- if len(segments > 0:)
- x = head.xcor()
- y = head.ycor()
- segments[0].goto(x, y)
- move()
- time.sleep(delay)
- wn.mainloop()
- #Note: wn.mainloop() keeps the window open for us
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement