How to reset the turtles and erase the text in turtle graphics? - python

I made this turtle game
import turtle
import random
import time
from turtle import Turtle
# Window
window = turtle.Screen()
window.title("Turtle Race")
window.bgcolor("forestgreen")
turtle.color("white")
turtle.speed(0)
turtle.penup()
turtle.setposition(-140, 200)
turtle.write("Turtle Race", font=("Arial", 40, "bold"))
# Dirt
turtle.setposition(-400, -180)
turtle.color("chocolate")
turtle.begin_fill()
turtle.pendown()
turtle.forward(800)
turtle.right(90)
turtle.forward(300)
turtle.right(90)
turtle.forward(800)
turtle.right(90)
turtle.forward(300)
turtle.end_fill()
# Finish line
stamp_size = 20
square_size = 15
finish_line = 200
turtle.color("black")
turtle.shape("square")
turtle.shapesize(square_size / stamp_size)
turtle.penup()
for i in range(10):
turtle.setposition(finish_line, (150 - (i * square_size * 2)))
turtle.stamp()
for j in range(10):
turtle.setposition(finish_line + square_size, ((150 - square_size) - (j * square_size * 2)))
turtle.stamp()
turtle.hideturtle()
def play():
# Turtle 1
turtle1 = Turtle()
turtle1.speed(0)
turtle1.color("black")
turtle1.shape("turtle")
turtle1.penup()
turtle1.goto(-250, 100)
turtle1.pendown()
# Turtle 2
turtle2 = Turtle()
turtle2.speed(0)
turtle2.color("cyan")
turtle2.shape("turtle")
turtle2.penup()
turtle2.goto(-250, 50)
turtle2.pendown()
# Turtle 3
turtle3 = Turtle()
turtle3.speed(0)
turtle3.color("magenta")
turtle3.shape("turtle")
turtle3.penup()
turtle3.goto(-250, 0)
turtle3.pendown()
# Turtle 4
turtle4 = Turtle()
turtle4.speed(0)
turtle4.color("yellow")
turtle4.shape("turtle")
turtle4.penup()
turtle4.goto(-250, -50)
turtle4.pendown()
time.sleep(1) # pausing the game for 1 sec before game starts
# Asking user to play
print("Please choose one colour out of \nBlack \nCyan \nMagenta \nYellow ")
user_bet = input("Place your bet on your any one colour turtle: ").upper()
while not(user_bet == "BLACK" or user_bet == "CYAN" or user_bet == "MAGENTA" or user_bet == "YELLOW"):
print("Please choose one colour out of \nBlack \nCyan \nMagenta \nYellow ")
user_bet = input("Place your bet on your any one colour turtle: ").upper()
# Initial distance covered by turtles
tut1_len = 0
tut2_len = 0
tut3_len = 0
tut4_len = 0
# Moving the turtles
for _i in range(145):
tut1 = random.randint(1, 5)
tut2 = random.randint(1, 5)
tut3 = random.randint(1, 5)
tut4 = random.randint(1, 5)
turtle1.forward(tut1)
tut1_len += tut1
turtle2.forward(tut2)
tut2_len += tut2
turtle3.forward(tut3)
tut3_len += tut3
turtle4.forward(tut4)
tut4_len += tut4
# Deciding the winner
result_dic = {"black": tut1_len, "cyan": tut2_len, "magneta": tut3_len, "yellow": tut4_len}
winner = max(result_dic, key=lambda x: result_dic[x]).upper()
turtle.penup()
turtle.color("blue")
if user_bet == winner:
turtle.goto(-140, 50)
turtle.write("You won the bet", font=("Arial", 30, "bold"))
else:
turtle.goto(-140, 50)
turtle.write("You lost the bet", font=("Arial", 30, "bold"))
turtle.pendown()
play()
choice = input("Do you want to play again?\n Press y for yes and n for no: ").upper()
while choice == "y".upper() or choice == "yes".upper():
play()
else:
quit()
The game works and i wanted the game to ask user to play again and it does that but every time the game reruns the turtles run over previous turtle the the text which display ** You won the bet** or ** You lost the bet** is also written over previous another one.
I din't find any method to clear text written in screen nor to erase the turtles lines.
Please help me.
And it would me really helpful if you guys give me suggestion on how to improve this code like how to make it more short and i am little confused about my own logic on line 106 about that or operator but this is secondary please help me on my primary problem first.

My recommendation in a situation like this, where text is being updated on the screen, is that you have a turtle dedicated just to writing that text. Put that turtle into position before the action starts and then just use clear() and write() on that turtle from then on. Don't use it for anything else.
it would me really helpful if you guys give me suggestion on how to
improve this code
One key thing with a program like this is to not assume how many racers there will be, and write your code accordingly. You should be able to adjust the number up or down slightly (or just change your color choices) without having to do a major rewrite.
I've reworked your code to address both of the above issues:
from turtle import Screen, Turtle
from random import randint
STAMP_SIZE = 20
SQUARE_SIZE = 15
FINISH_LINE = 200
LANE_WIDTH = 50
BIG_FONT = ('Arial', 40, 'bold')
MEDIUM_FONT = ('Arial', 30, 'bold')
COLORS = ['black', 'cyan', 'magenta', 'yellow', 'white']
def play():
pen.clear()
lane = LANE_WIDTH
for n, color in enumerate(COLORS, start=1):
turtle = turtles[color]
turtle.hideturtle()
turtle.goto(-250, n // 2 * lane)
turtle.showturtle()
lane = -lane
# Asking user to play
user_bet = None
while user_bet not in COLORS:
print("Please choose one colour out of", *["\n" + color.title() for color in COLORS])
user_bet = input("Place your bet on your any one colour turtle: ").lower()
# Moving the turtles
for _ in range(145):
for turtle in turtles.values():
distance = randint(1, 5)
turtle.forward(distance)
# Deciding the winner
winner = max(turtles, key=lambda x: turtles[x].xcor())
pen.clear()
if user_bet == winner:
pen.write("You won the bet!", align='center', font=MEDIUM_FONT)
else:
pen.write("You lost the bet.", align='center', font=MEDIUM_FONT)
# Screen
screen = Screen()
screen.title("Turtle Race")
screen.bgcolor('forestgreen')
turtle = Turtle()
turtle.hideturtle()
turtle.speed('fastest')
turtle.penup()
# Dirt
turtle.setposition(-400, -180)
turtle.color('chocolate')
turtle.begin_fill()
for _ in range(2):
turtle.forward(800)
turtle.right(90)
turtle.forward(300)
turtle.right(90)
turtle.end_fill()
# Finish line
turtle.color('black')
turtle.shape('square')
turtle.shapesize(SQUARE_SIZE / STAMP_SIZE)
for i in range(10):
turtle.setposition(FINISH_LINE, 150 - i * SQUARE_SIZE*2)
turtle.stamp()
turtle.setposition(FINISH_LINE + SQUARE_SIZE, (150 - SQUARE_SIZE) - i * SQUARE_SIZE*2)
turtle.stamp()
turtle.setposition(0, 200)
turtle.write("Turtle Race", align='center', font=BIG_FONT)
pen = Turtle()
pen.hideturtle()
pen.color('blue')
pen.penup()
pen.setposition(0, 50)
turtle_prototype = Turtle()
turtle_prototype.hideturtle()
turtle_prototype.shape('turtle')
turtle_prototype.speed('fastest')
turtle_prototype.penup()
turtles = {}
for color in COLORS:
turtle = turtle_prototype.clone()
turtle.color(color)
turtles[color] = turtle
choice = 'yes'
while choice.lower() in ('y', 'yes'):
play()
choice = input("Do you want to play again?\nPress y for yes and n for no: ")

Related

Score/points update in beginner python turtle game

I'm a newbie to python and I'm having a problem with the score in my turtle game. The score is updated the first time I collect the ball, but it does not update when I collect the ball on any subsequent occasion. I would like the score to increase by a number e.g. 2 every time a ball is collected.
Might someone be able to offer a solution?
I suspect the issue could lie in:
the scope of the variable 'score
the improper looping of any/some function
import turtle
import random
import math
screen = turtle.Screen()
screen.title("My game by python code")
screen.bgcolor("black")
screen.setup(width=600, height=600)
# Making the user 'bubble'
bubble = turtle.Turtle()
bubble.color("red")
bubble.shape("circle")
bubble.penup()
speed = 3
# Making the collection balls
collection_ball = turtle.Turtle()
collection_ball.color("red")
collection_ball.penup()
collection_ball.shape("circle")
collection_ball.shapesize(0.5, 0.5, 0.5)
ball_cor1 = random.randint(30, 280)
ball_cor2 = random.randint(30, 280)
collection_ball.setposition(ball_cor1, ball_cor2)
collection_ball.color("yellow")
# Scoring
points = turtle.Turtle()
points.color("yellow")
style = ('Courier', 30, 'italic')
points.penup()
points.goto(-200, 250)
points.write("Points: 0", font=style)
points.hideturtle()
# Turning
def turn_left():
bubble.left(90)
def turn_right():
bubble.right(90)
# Collection of the balls
def collection(a, b):
return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 20
def collection_ball_restart():
collection_ball.color("black")
ball_cor1 = random.randint(30, 280)
ball_cor2 = random.randint(30, 280)
collection_ball.goto(ball_cor1, ball_cor2)
collection_ball.color("yellow")
bubble.forward(speed)
screen.ontimer(play_game, 10)
def play_game():
if collection(bubble, collection_ball):
score = 0
score += 2
points.clear()
points.write("Points: " + str(score), font=style)
collection_ball_restart()
bubble.forward(speed)
else:
bubble.forward(speed)
screen.ontimer(play_game, 10)
turtle.onkeypress(turn_left, "Left")
turtle.onkeypress(turn_right, "Right")
screen.listen()
play_game()
screen.mainloop()
In addition to the score initialization issue that #TimRoberts points out (+1), below is a rework of your code to simplify the logic:
from turtle import Screen, Turtle
from random import randint
FONT_STYLE = ('Courier', 30, 'italic')
screen = Screen()
screen.title("My game by python code")
screen.bgcolor('black')
screen.setup(width=600, height=600)
# Making the user 'bubble'
bubble = Turtle()
bubble.color('red')
bubble.shape('circle')
bubble.penup()
# Making the collection balls
collection_ball = Turtle()
collection_ball.color('yellow')
collection_ball.shape('circle')
collection_ball.shapesize(0.5)
collection_ball.penup()
ball_cor1 = randint(30, 280)
ball_cor2 = randint(30, 280)
collection_ball.setposition(ball_cor1, ball_cor2)
# Scoring
score = 0
speed = 3
points = Turtle()
points.hideturtle()
points.color('yellow')
points.penup()
points.goto(-200, 250)
points.write("Points: 0", font=FONT_STYLE)
# Turning
def turn_left():
bubble.left(90)
def turn_right():
bubble.right(90)
# Collection of the balls
def was_collected(bubble):
return bubble.distance(collection_ball) < 15
def collection_ball_reset():
collection_ball.hideturtle()
collection_ball.goto(randint(30, 280), randint(30, 280))
collection_ball.showturtle()
def play_game():
global score
if was_collected(bubble):
score += 2
points.clear()
points.write("Points: " + str(score), font=FONT_STYLE)
collection_ball_reset()
bubble.forward(speed)
screen.ontimer(play_game, 10)
screen.onkeypress(turn_left, 'Left')
screen.onkeypress(turn_right, 'Right')
screen.listen()
play_game()
screen.mainloop()
E.g. use hideturtle() and showturtle() instead of color tricks; minimize necessary calls to ontimer(); use built-in distance function.

I need to figure out a way for my program to tell the user that they win or lose depending on if the turtle is in the circle or not

This code has the turtle make a shape and then gives the user ten moves to go forward, back, right, and left to move the turtle back into the circle. I need to figure out a way for my program to tell the user that they win or lose depending on if the turtle is in the circle or not I am trying to use the xpos and ypos commands to tell where the turtle is but I'm not sure how to use them so that I can make it tell when the turtle is in teh circle or not.
#Importing the package
import turtle
shape = str()
direction = str()
#Change turtle color and background color
turtle.color("green")
turtle.Screen().bgcolor("blue")
screen = turtle.Screen()
#Ask the user what shape they want the turtle to be
shape = turtle.textinput("Enter a shape", "Enter a shape: classic, arrow, turtle, circle, square, or triangle.")
turtle.shape(shape)
#Making a circle
turtle.penup()
turtle.goto(-200, -100)
turtle.pendown()
turtle.fillcolor("red")
turtle.begin_fill()
turtle.circle(100)
turtle.end_fill()
turtle.penup()
turtle.color("green")
#Move turtle back to start
turtle.goto(0, 0)
#Moving the turtle into the circle
for counter in range(1, 11, 1):
#getting the direction from the user
direction = screen.textinput("Direction", "Enter F for Forward, B for Backward, R for Right and L for Left")
if direction == "F":
turtle.forward(100)
elif direction == "B":
turtle.backward(100)
elif direction == "R":
turtle.right(90)
turtle.forward(100)
else:
turtle.left(90)
turtle.forward(100)
#end if
#Find where the turtles ending position is
xpos = turtle.xcor()
ypos = turtle.ycor()
turtle.write("Sorry You Lost", align="center", font=('Arial', '16', 'bold'))
turtle.write("Good Job You Won!", align="center", font=('Arial', '16', 'bold'))
turtle.exitonclick()
from turtle import Screen, Turtle
#Change turtle color and background color
tim = Turtle()
screen = Screen()
tim.color("green")
screen.bgcolor("blue")
#Ask the user what shape they want the turtle to be
shape = screen.textinput("Enter a shape", "Enter a shape: classic, arrow, turtle, circle, square, or triangle: ")
tim.shape(shape)
#Making a circle
tim.penup()
tim.goto(-200, -100)
tim.pendown()
tim.fillcolor("red")
tim.begin_fill()
tim.circle(100)
tim.end_fill()
tim.penup()
tim.color("green")
#Move turtle back to start
tim.goto(0, 0)
#Moving the turtle into the circle
for counter in range(1, 11, 1):
#getting the direction from the user
direction = screen.textinput("Direction", "Enter F for Forward, B for Backward, R for Right and L for Left")
if direction == "F":
tim.forward(100)
elif direction == "B":
tim.backward(100)
elif direction == "R":
tim.right(90)
tim.forward(100)
else:
tim.left(90)
tim.forward(100)
#end if
#Find where the turtles ending position is
xpos = tim.xcor()
ypos = tim.ycor()
print(xpos)
print(ypos)
tim.write("Sorry You Lost", align="center")
tim.write("Good Job You Won!", align="center")
screen.exitonclick()
Here, I fixed your code and I think it is now working what you exactly wanted.

Python turtle race: go to a point and turn back

Hi I have another question: how do you make a turtle go to a point and turn back? I want the turtles to go to the point with x coordinate 160 and turn back, continuing the race at the same time (meaning that they don't all move at the same speed).
Here is my code:
import turtle
from random import randint
turtle.speed(0)
turtle.penup()
turtle.goto(-140,140)
for step in range(15):
turtle.write(step,align='center')
turtle.right(90)
turtle.forward(10)
turtle.pendown()
turtle.forward(180)
turtle.penup()
turtle.backward(190)
turtle.left(90)
turtle.forward(20)
roy = turtle.Turtle()
roy.color('red')
roy.shape('turtle')
roy.penup()
roy.goto(-160,100)
roy.pendown()
bob = turtle.Turtle()
bob.color('blue')
bob.shape('turtle')
bob.penup()
bob.goto(-160,70)
bob.pendown()
oreo = turtle.Turtle()
oreo.color('orange')
oreo.shape('turtle')
oreo.penup()
oreo.goto(-160,40)
oreo.pendown()
yay = turtle.Turtle()
yay.color('yellow')
yay.shape('turtle')
yay.penup()
yay.goto(-160,10)
yay.pendown()
go = turtle.Turtle()
go.color('green')
go.shape('turtle')
go.penup()
go.goto(-160,-20)
go.pendown()
for turn in range(100):
roy.forward(randint(1,5))
bob.forward(randint(1,5))
oreo.forward(randint(1,5))
yay.forward(randint(1,5))
go.forward(randint(1,5))
if roy.xcor() >= 160:
roy.left(180)
else:
break
if bob.xcor() >= 160:
bob.left(180)
else:
break
if yay.xcor() >= 160:
yay.left(180)
else:
break
if oreo.xcor() >= 160:
oreo.left(180)
else:
break
if go.xcor() >= 160:
go.left(180)
else:
break
I know there's something wrong with my "if" loop in the end, but I don't know what happened.
By the way my turtle turns out like this
Help is appreciated!
Your else break is a problem, it ends the race when the first turtle tries to turn around. Also, left(180) can be problematic if the turtle overshoots the turn point a bit as it will start to spin. Using setheading(180) is safer as it will avoid the spin and send the turtle back towards the starting line:
from turtle import Screen, Turtle
from random import randint, choice
screen = Screen()
turtle = Turtle()
turtle.hideturtle()
turtle.speed('fastest')
turtle.penup()
turtle.goto(-140, 140)
for step in range(15):
turtle.write(step, align='center')
turtle.right(90)
turtle.forward(10)
turtle.pendown()
turtle.forward(180)
turtle.penup()
turtle.backward(190)
turtle.left(90)
turtle.forward(20)
roy = Turtle()
roy.color('red')
roy.shape('turtle')
roy.penup()
roy.goto(-160, 100)
roy.pendown()
bob = Turtle()
bob.color('blue')
bob.shape('turtle')
bob.penup()
bob.goto(-160, 70)
bob.pendown()
oreo = Turtle()
oreo.color('orange')
oreo.shape('turtle')
oreo.penup()
oreo.goto(-160, 40)
oreo.pendown()
yay = Turtle()
yay.color('yellow')
yay.shape('turtle')
yay.penup()
yay.goto(-160, 10)
yay.pendown()
go = Turtle()
go.color('green')
go.shape('turtle')
go.penup()
go.goto(-160, -20)
go.pendown()
while True:
racer = choice([roy, bob, oreo, yay, go])
racer.forward(randint(1, 5))
if racer.xcor() > 160:
racer.setheading(180)
elif racer.xcor() < -160:
break # we have a winner!
screen.mainloop()
Your while True: doesn't really belong in an event-driven environment like turtle and can be replaced with an ontimer() event. But, one step at a time.

How to create a while loop for a dice roll in python turtle?

I have two turtles set up and the goal of the game is to see which turtle can reach their home first. I have to use a dice roll mechanic to determine this but I do not know how to add one while using a while-loop. Once turtle 1 rolls it is supposed to be turtle 2's turn. They keep doing this until one of the turtles reaches their home. That is when the game ends.
import turtle
import random
turtle.hideturtle()
turtle.penup()
turtle.setpos(300,80)
turtle.pendown()
turtle.speed(9)
turtle.circle(30)
turtle.hideturtle()
turtle.penup()
turtle.setpos(300,-125)
turtle.pendown()
turtle.speed(9)
turtle.circle(30)
p1 = turtle.Turtle()
p1.shape("turtle")
p2 = turtle.Turtle()
p2.shape("turtle")
def p1_start():
p1.speed(9)
p1.penup()
p1.goto(-200,100)
p1.pendown()
p1_start()
def p2_start():
p2.speed(9)
p2.penup()
p2.goto(-200,-100)
p2.pendown()
p2_start()
player1 = input("Player 1 enter name: ")
turtle.penup()
turtle.setpos(-207, 50)
turtle.write(player1, font=('Arial', 16, 'normal'))
turtle.hideturtle()
player2 = input("\nPlayer 2 enter name: ")
turtle.penup()
turtle.setpos(-207, -150)
turtle.write(player2, font=('Arial', 16, 'normal'))
turtle.hideturtle()
player1_color = raw_input("\nPlayer 1 enter color: ")
p1.color(player1_color)
player2_color = raw_input("\nPlayer 2 enter color: ")
p2.color(player2_color)
player1_dict = {"Name": player1, "Color": player1_color}
print("\nPLAYER 1 INFO: ")
print(player1_dict)
player2_dict = {"Name": player2, "Color": player2_color}
print("\nPLAYER 2 INFO: ")
print(player2_dict)
print('\n')
print('Player 1 is now rolling')
roll = int (random.randint (1,6))
if roll==1:
print('The number on the die is',roll)
elif roll== 2:
print('The number on the die is',roll)
elif roll == 3:
print('The number on the die is',roll)
elif roll == 4:
print('The number on the die is',roll)
elif roll == 5:
print('The number on the die is',roll)
else:
print('The number on the die is',roll)
p1.forward(roll*20)
I see a number of problems: you added too much fine detail before working out big picture issues -- it should be the other way around; you created a data structure to represent your players but in the end you didn't really use it; you designed this for a fixed number of players when you really should have designed it for an unknown (but reasonable) number of players to keep your code honest.
Let's take your code apart and put it back together again to address the above issues:
from turtle import Screen, Turtle
from random import randint
NUMBER_PLAYERS = 3
POLE = 300
FONT = ('Arial', 16, 'normal')
players = []
for player in range(1, NUMBER_PLAYERS + 1):
name = input("\nPlayer " + str(player) + " enter name: ")
color = input("Player " + str(player) + " enter color: ")
players.append({'Name': name, 'Color': color})
for number, player in enumerate(players, 1):
print("\nPlayer", number, "information:", player)
screen = Screen()
height = screen.window_height()
lane_height = height / (NUMBER_PLAYERS + 1) # divide the vertical space into lanes
marker = Turtle()
marker.hideturtle()
marker.speed('fastest')
for number, player in enumerate(players, 1):
y_coordinate = height/2 - lane_height * number
marker.penup()
marker.setpos(-POLE, y_coordinate + 30)
marker.write(player['Name'], align='center', font=FONT)
marker.setpos(POLE, y_coordinate - 30)
marker.pendown()
marker.circle(30)
tortoise = Turtle()
tortoise.hideturtle()
tortoise.shape('turtle')
tortoise.speed('slowest')
tortoise.penup()
tortoise.goto(-POLE, y_coordinate)
tortoise.pendown()
tortoise.color(player['Color'])
tortoise.showturtle()
player['Turtle'] = tortoise
while True:
for number, player in enumerate(players, 1):
y_coordinate = height/2 - lane_height * number
print()
print(player['Name'], 'is now rolling')
roll = randint(1, 6)
print('The number on the die is:', roll)
player['Turtle'].forward(roll * 5)
if player['Turtle'].distance(POLE, y_coordinate) < 30:
print()
print(player['Name'], "is the winner!")
break
else: # no break
continue
break # yes, this is a tricky loop -- take your time with it
screen.exitonclick()

Making snake in Python, can't get bodies to follow head etc

I wanted to make a snake game in turtle but I can't seem to get the tail segments to follow the leader. As if to say I can't get the first body part to follow the head, and then the second body part to follow the first body, etc.
I tried using what maths I have but I can't seem to get it to calculate where the head just was or where the body in front of it just was.
here is my code:
#libraries
import turtle
import random
import math
#screen
the_screen = turtle.Screen()
the_screen.bgcolor("lightgreen")
the_screen.title("Catapillar")
#border
border_writer = turtle.Turtle()
border_writer.speed(0)
border_writer.color("green")
border_writer.penup()
border_writer.setposition(-275, -275)
border_writer.pendown()
border_writer.pensize(7)
for side in range(4):
border_writer.fd(550)
border_writer.lt(90)
border_writer.hideturtle()
#player
player = turtle.Turtle()
player.color("yellow")
player.shape("circle")
player.penup()
player.speed(0)
player.setposition(0,0)
player.setheading(0)
playerspeed = 2
#fruit
fruit = 1
fruit = turtle.Turtle()
fruit.color("red")
fruit.shape("circle")
fruit.penup()
fruit.speed(0)
fruit.shapesize(0.6, 0.6)
x = random.randint(-200, 200)
y = random.randint(100, 250)
fruit.setposition(x, y)
#moving and collision checker
def turnleft():
player.left(24.5)
def turnright():
player.right(24.5)
def increasespeed():
global playerspeed
playerspeed += 1
def isCollision(t1, t2):
distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(), 2) + math.pow(t1.ycor()-t2.ycor(), 2))
if distance < 24:
return True
else:
return False
#making the tail(s) and hiding them
tail1 = turtle.Turtle()
tail1.hideturtle()
tail1.color("yellow")
tail1.shape("circle")
tail1.penup()
tail1.speed(0)
tail1.setposition(+700,700)
tail1.shapesize(0.6, 0.6)
tail1state = 'off'
#key presses
turtle.listen()
turtle.onkeypress(turnleft, "Left")
turtle.onkeypress(turnright, "Right")
turtle.onkeypress(increasespeed, "Up")
#main loop player always moves forward, out of bound set, reset fruit
#randomly when collided, create tail1...
while True:
player.forward(playerspeed)
#gameovers'
if (player.xcor() > 275) or (player.xcor() < -275):
playerspeed += 7
print("GAME OVER")
if (player.ycor() > 275) or (player.ycor() < -275):
playerspeed += 7
print("GAME OVER")
#collision check between fruit and head
if isCollision(player, fruit):
#resets the fruit, moves it randomly
fruit.hideturtle()
if tail1state == 'off':
uuu = player.xcor()
vvv = player.ycor()
tail1.setposition(uuu,vvv)
tail1.showturtle()
tail1state = 'on'
#reset the fruit
x = random.randint(-200, 200)
y = random.randint(-100, 250)
fruit.setposition(x, y)
fruit.showturtle()
#playerspeed +=1
If you have any idea on how you think I should approach it, please let me know what you think.
Thank you.
Since this comes up over and over (but effort to effect it is rarely shown) here's my minimal, generic, slithering around a screen effect that you should be able to adapt for your own purposes:
from turtle import Turtle, Screen
SNAKE_LENGTH = 10
SNAKE_SIZE = 15
WIDTH, HEIGHT = 375, 375
CURSOR_SIZE = 20
def slither():
segment = snake[-1].clone() if len(snake) < SNAKE_LENGTH else snake.pop(0)
screen.tracer(False) # segment.hideturtle()
segment.setposition(snake[-1].position())
segment.setheading(snake[-1].heading())
segment.forward(SNAKE_SIZE)
while not -WIDTH/2 < segment.xcor() < WIDTH/2 or not -HEIGHT/2 < segment.ycor() < HEIGHT/2:
segment.undo()
segment.right(95)
segment.forward(SNAKE_SIZE)
screen.tracer(True) # segment.showturtle()
snake.append(segment)
screen.ontimer(slither, 100)
boundary = Turtle(shape='square', visible=False)
boundary.shapesize(HEIGHT / CURSOR_SIZE, WIDTH / CURSOR_SIZE)
boundary.fillcolor("white")
boundary.stamp()
head = Turtle("circle")
head.shapesize(SNAKE_SIZE / CURSOR_SIZE)
head.penup()
snake = [head]
screen = Screen()
slither()
screen.exitonclick()

Categories