简体   繁体   中英

Snake Game Turtle Graphics in Python

So I have a project where I have to create a game in TURTLE graphics only without using any other modules except turtle and the random module. I am creating the traditional snake game except when the snake "eats" the object it doesn't get bigger. The problem with my game is that when the "snake" gets to the object, the object does not disappear and I want it to disappear and reappear in another position. Please Help. Here is the code:

from turtle import *
import random

setup(700, 700)
title("Snake Game!")
bgcolor("blue")

# Boundary
bPen = Pen()
bPen.color("Orange")
bPen.up()
bPen.goto(-300, -300)
bPen.down()

for i in range(4):
    bPen.ht()
    bPen.fd(600)
    bPen.lt(90)



# Player 
playerPen = Pen()
playerPen.color("Orange")
playerPen.up()
playerPen.width(4)

# Create Circle

circle = Pen()
circle.shape("circle")
circle.color("Red")
circle.up()
circle.speed(0)
circle.goto(-100, 100)



# Speed
speed = 2

# Movement functions

def left():
    playerPen.lt(90)

def right():
    playerPen.rt(90)

def speedBoost():
    global speed
    speed += 1


# Key Prompts
onkey(left, "Left")
onkey(right, "Right")
onkey(speedBoost, "Up")
listen()


# Infinity loop and player knockback
while True:
    playerPen.fd(speed)

    if playerPen.xcor() < -300 or playerPen.xcor() > 300:
        playerPen.rt(180)

    elif playerPen.ycor() < - 300 or playerPen.ycor() > 300:
        playerPen.rt(180)

    # Collision with circle
    if playerPen.xcor() == circle.xcor() and playerPen.ycor() == circle.ycor():
        circle.goto(random.randint(-300, 300), random.randint(-300, 300))


done()

The code works, but hitting the snake exactly on the center of the circle is difficult. To fix this, at the top of your code add a constant:

RADIUS = 10

That is roughly the radius of the circle. Then, change this line:

if playerPen.xcor() == circle.xcor() and playerPen.ycor() == circle.ycor():

to instead be:

if abs(playerPen.xcor() - circle.xcor()) < RADIUS and abs(playerPen.ycor() - circle.ycor()) < RADIUS:

And enjoy the game!

Or if you can't enjoy the game due not being able to use abs() , here's another way to write that same line without it:

if -RADIUS < playerPen.xcor() - circle.xcor() < RADIUS and -RADIUS < playerPen.ycor() - circle.ycor() < RADIUS:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM