I get an unwanted grey square at position 0,0 in my snake game. Why doesn't Python work?

import turtle
import time
import random
import winsound
from playsound import playsound

""" Copyright (c) 2023 Roy Evert """
""" All Rights Reserved """

# set up the screen
win = turtle.Screen()
win.title("The Snake Game")
win.bgcolor("blue")
win.setup(width=600,height=600)

# Define the variables
delay = 0.3
global score, high_score, flag, num1
score = 0
high_score = 0
sound_code = 0
champ = "God"
eat_self = 0
flag = True
num1 = 0

# Bring in the Snake head views
up_head = r"C:/Users/royev/Desktop/Python/Snake_Head_UP.gif"
lt_head = r"C:/Users/royev/Desktop/Python/Snake_Head_LT.gif"
rt_head = r"C:/Users/royev/Desktop/Python/Snake_Head_RT.gif"
dn_head = r"C:/Users/royev/Desktop/Python/Snake_Head_DN.gif"

# Register the snake head image
win.addshape(up_head)
win.addshape(lt_head)
win.addshape(rt_head)
win.addshape(dn_head)

# Open save file & bring in the previous high score
out_file = open('C:/Users/royev/Desktop/Python/high_score.txt','a+')
out_file.seek(0)
Line = out_file.readlines()
for line in Line:
    words = line.split()
    champ = words[0]
    high_score = int(words[1])
out_file.seek(0)
out_file.truncate()
print(champ,high_score)

# Get the current player's name
player = turtle.textinput("The Snake Game","Player First Name")

# Put the score on the screen
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Score: {}   High Score: {}   Champ: {}".format(score,high_score,champ), align="center",font=("Courier",16,"normal"))

# Snake segments
segments = []
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
turtle.clear()
turtle.reset()

tail_segment = turtle.Turtle()
tail_segment.speed(0)
tail_segment.shape("square")
tail_segment.color("")
tail_segment.penup()
tail_segment.goto(0,100)
segments.append(tail_segment)
turtle.reset()

# Snake head
head = turtle.Turtle()
head.shape(dn_head)
head.speed(0)
head.penup()
head.goto(0,100)
head.direction = "stop"
turtle.reset()

# Snake food
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("gold") # Note the color!
food.penup()
food.shapesize(0.80, 0.80)
food.goto(0,-80)
turtle.reset()

# Blue square
#blue = turtle.Turtle()
#blue.speed(0)
#blue.shape("square")
#blue.color("blue")
#blue.penup()
#blue.goto(0,0)    

# Set the direction of the snake head   
def exit():
    head.direction = "stop"
    out_check(1) # Send exit code to game loop (out_check) function
def stop():
    head.direction = "stop"    
def go_up():
    if head.direction != "down":
        head.direction = "up"
def go_left():
    if head.direction != "right":
        head.direction = "left"
def go_right():
    if head.direction != "left":
        head.direction = "right"
def go_down():
    if head.direction != "up":
        head.direction = "down"
        
# Get player keystroke and go to appropriate direction function above
win.listen()
win.onkey(exit, "x")
win.onkey(stop, "q")
win.onkey(go_up, "w")
win.onkey(go_down, "z")
win.onkey(go_left, "a")
win.onkey(go_right, "s")
    
def move():
    global score, high_score, champ, eat_self, sound_code
    if head.direction == "up":
        y = head.ycor() # y coordinate of the snake
        head.sety(y + 20)
        head.shape(up_head)
    elif head.direction == "down":
        y = head.ycor() # y coordinate of the snake
        head.sety(y - 20)
        head.shape(dn_head)
    elif head.direction == "left":
        x = head.xcor() # x coordinate of the snake
        head.setx(x - 20)
        head.shape(lt_head)
    elif head.direction == "right":
        x = head.xcor() # x coordinate of the snake
        head.setx(x + 20)
        head.shape(rt_head)
    if head.distance(food) < 15: # If snake is close, consume & move the food
        winsound.PlaySound('C:/Windows/Media/Gulp.wav',winsound.SND_ASYNC)
        sound_code = 1
        x = (random.randint(-14, 14) * 20) # Keep the food on the screen and in the snake's path
        y = (random.randint(-14, 14) * 20)
        food.goto(x, y)
        score += 10
        if score > high_score: # Refresh the score
            champ = player
            high_score = score
        pen.clear()
        pen.write("Score: {}   High Score: {}   Champ: {}".format(score,high_score,champ), align="center",font=("Courier",16,"normal"))
        tail0 = segments[0]
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape("square")
        new_segment.color("grey")
        new_segment.penup()
        segments.append(new_segment) # Add a new tail segment to the snake
    if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290: # Check for out of bounds collision
        playsound(u'C:/Users/royev/Desktop/Python/Impact.wav')
        sound_code = 2 # Yup, out of bounds
        head.shape(dn_head)
        head.goto(0, 100)
        head.direction = "stop"
        score = 0
        eat_self = 1
        tail0 = segments[0]
        pen.clear()
        pen.write("Score: {}   High Score: {}   Champ: {}".format(score,high_score,champ), align="center",font=("Courier",16,"normal"))
        for segment in segments: # Hide the old segments
            segment.goto(1000, 1000)
            segment.clear()
    if head.direction != "stop":
        for index in range(len(segments)-1, 0, -1): # Move the tail segments in reverse order
            x = segments[index-1].xcor()
            y = segments[index-1].ycor()
            segments[index].goto(x,y)
            if index > 0:
                if segments[index].distance(head) < 20: # Check for collision of snake head with tail
                    playsound(u'C:/Users/royev/Desktop/Python/Ouch.mp3')
                    sound_code = 1 # Yup, collision with tail
                    head.shape(dn_head)
                    head.goto(0, 100)
                    head.direction = "stop"
                    score = 0
                    eat_self = 1
                    tail0 = segments[0]
                    pen.clear()
                    pen.write("Score: {}   High Score: {}   Champ: {}".format(score,high_score,champ), align="center",font=("Courier",16,"normal"))
                    index = len(segments)-1
        if sound_code < 1: # Make sure the movement sound is the only sound
            winsound.PlaySound('C:/Windows/Media/Move.wav',winsound.SND_ASYNC)
        else:
            sound_code = 0 # Set sound code to movement
    if eat_self == 1:
        if len(segments) > 0:
            for segment in segments: # Hide the old segments
                segment.goto(1000,1000)
                segment.clear
        segments.clear()
        segments.append(tail0)
        eat_self = 0
    if len(segments) > 0 and head.direction != "stop": # Move tail segment 0 to where the snake's head is
        x = head.xcor()
        y = head.ycor()
        segments[0].goto(x,y)
        head.goto(x,y)

# Receive code from exit key, and check code from main game loop
def out_check(num0):
    global num1
    if num0 == 1:
        num1 = 1
    return num1

# Main game loop
while flag:
    win.update()
    move()
    num_ck = out_check(0) # Is it time to exit the game?
    if num_ck == 1:
        flag = False
    time.sleep(delay)
else:
    out_file.write(champ+" "+str(high_score)) # Save the score
    out_file.close()
    exit()
    turtle.bye() # Kill the screen

Hi Roy, and welcome!

It doesn’t? Thank goodness you’re here to tell us, I guess the tens of thousands of people programming in Python can just stop, now that we know it doesn’t work! :grin: :wink:

I can’t run your code right now, but at a glance my guess is that your unwanted grey square might have something to do with your code here:

new_segment.shape(“square”)
new_segment.color(“grey”)

where, I think, you create and draw a grey square. What happens if you remove those two lines?

In future, please format your code correctly, as Python code, using the </> button. You can see a preview of the code to the side of the text entry widget on the Discuss website, so you can check to see how it looks before posting.

(You might need to close the " Your topic is similar to…" window which pops up and obscures the preview.)

It might also help us all if you can simplify your example code to the minimal reproducible example that demonstrates the problem. That makes it easier for us to help you.

In your post’s case, Steven is referring to your code fence, which was:

 '''

which is 3 ASCII single quote/apostrophe marks. A code fence uses the
ASCII backtick:

 ```

which on my keyboard is at top left under the tilde (~).

But if you’re posting from the web forum, the </> button in the
compose bar is the easy way to insert a section for pasting your code.

Cheers,
Cameron Simpson cs@cskk.id.au

(I fixed their code fencing; I also always add the appropriate lexer name to the code fence, i.e.

```python
<CODE HERE>
```

to get proper syntax highlighting)

Yes, you are correct. The grey square was from those two lines of code. To correct my problem I sent my new_segment to (1000, 1000) with a goto. That got it off the screen. Now what remains is an arrow head. I tried turtle.hideturtle() and food.hideturtle() and neither works. The second attempt to hide turtle also hid the food. Thanks for your help.

Roy

For a second I thought you meant kind of goto that’s considered harmful, and was very confused (and at least mildly alarmed).

Is there a reason you do that instead of simply not adding the segment at all?

I would love to add the segment but then I wouldn’t be able to see the snake head. The head segment is a gif picture of a snake head which is mutually exclusive with a tail segment and mutually exclusive with .tracer(). I am moving on from Python, so please don’t reply. I find Python not yet ready for prime time.

Roy

A word of advice that applies to any language you use, then: if you completely give up on one as soon as you get stuck on a minor issue with one ancillary piece of it—and then conclude that the fault lies in a fundamental issue with one of the most widely used (and beginner friendly) languages in the world, rather than maybe something more proximate—then you’re likely to continue to find future languages you try “not ready for primetime”.

Best of luck.