Score/points update in beginner python turtle game - python

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.

Related

I imported images from google as ".gif," and wanted to add a detection collision into my python turtle program. Can anyone assist?

#This section of the code enables the user to Start the game (Added Function)
def askToPlayGame(game):
response = input("Want to play SpaceWars? (Y/N)")
if response == "Y":
print("The Game Is Activated")
else:
# Responses other than "Y" (includes "N")
print("User Doesn't Want To Play SpaceWars")
print("Too Bad, May The Force Be With You!")
return response
GamePartsList = ["1"]
shouldShowEverything = True
for part in GamePartsList:
answer = (askToPlayGame(part) == "Y") #Is true if response was a yes.
shouldShowEverything = answer and True # Makes shouldShowEverything stay true only if all responses are True
# List OF Game Characters - (User Input)
print("Choose A SpaceWars Character!: ")
selected_character = ""
my_charectors = ["kylo-ren", "darth-vader", "luke-skywalker", "obi-wan"]
for character in range(0,len(my_charectors)):
print(str(character) +". " + my_charectors[character])
chosenCharacter = input("Chosen character: ")
selected_character = my_charectors[int(chosenCharacter)]
#All Imported Turtles
import turtle as trtl
import math
import time
import sys
import winsound
winsound.PlaySound("soundtrack.wav", winsound.SND_ASYNC)
#This Portion Of The Code Aids In Python Errors
print(sys.getrecursionlimit())
sys.setrecursionlimit(2000)
print(sys.getrecursionlimit())
wn = trtl.Screen()
wn.setup(width=1.0, height=1.0)
wn.bgpic("background.gif")
#this Portion Of The Code Adds The 2 SpaceShips
import turtle, os
spaceship = turtle.Turtle()
spaceship.penup()
spaceship.setposition(-650, -120)
spaceship.speed(10000)
wn.addshape(os.path.expanduser("spaceship.gif"))
spaceship.shape(os.path.expanduser("spaceship.gif"))
import turtle, os
spaceship_two = turtle.Turtle()
spaceship_two.penup()
spaceship_two.setposition(-650, 200)
spaceship_two.speed(10000)
wn.addshape(os.path.expanduser("spaceship2.gif"))
spaceship_two.shape(os.path.expanduser("spaceship2.gif"))
#This Portion Of The Code Creates The Charector's Shape And Position
import turtle, os
wn = turtle.Screen()
playercharacter = turtle.Turtle()
playercharacter.penup()
playercharacter.setposition(600, -85)
wn.addshape(os.path.expanduser(selected_character+".gif"))
playercharacter.shape(os.path.expanduser(selected_character+".gif"))
playercharacter_state = "steady"
time = 0
timeToWait = 0
#This portion of the code creates the timer, adds lasers, and ends the game at Survival Score 250
laser1 = trtl.Turtle()
laser1.penup()
laser1.setposition(-500, -120)
laser1.shape("arrow")
laser1.color("Red")
laser2 = trtl.Turtle()
laser2.penup()
laser2.setposition(-500, 200)
laser2.shape("arrow")
laser2.color("Red")
timer = 0
counter_interval = 550 #1000 = 1 second
timer_up = False
counter = turtle.Turtle()
counter.color("Dark Red")
counter.hideturtle()
counter.penup()
counter.goto(-775,350)
font_setup = ("Arial", 20, "normal")
def countdown():
global timer, timer_up, laser1, laser2
counter.clear()
counter.write("Survival Score: " + str(timer), font=font_setup)
timer += 1
counter.getscreen().ontimer(countdown, counter_interval)
if laser1.xcor() > 800 and laser2.xcor() > 800:
laser1.setposition(-500, -120)
laser2.setposition(-500, 200)
# Divides time by 50, gets the closest whole number, and multiplies that by 20 / As score goes up by +50, laser speed goes up by +20.
speedFactor = math.ceil(timer/50) * 20
laser1.forward(150 + speedFactor) #speed
laser2.forward(110 + speedFactor) #speed
countdown()
#This portion of the code enables the playercharacter to jump
def jump_playercharacter():
global playercharacter_state
if playercharacter_state == "steady":
playercharacter_state = "jump"
playercharacter.penup()
playercharacter.speed(1)
x = playercharacter.xcor()
y = playercharacter.ycor() + 410
playercharacter.setposition(x, y)
y = playercharacter.ycor() - 410
playercharacter.setposition(x, y)
# function for keys commands
def RunnerLeft():
playercharacter.setheading(180)
playercharacter.forward(15)
def RunnerRight():
playercharacter.setheading(0)
playercharacter.forward(15)
def RunnerMove():
playercharacter.forward(15)
wn = turtle.Screen()
wn.onkeypress(RunnerRight, "D")
wn.onkeypress(RunnerLeft, "A")
wn.onkeypress(RunnerRight, "d")
wn.onkeypress(RunnerLeft, "a")
wn.onkey(jump_playercharacter, "space")
wn.delay(-100)
wn.update()
wn.listen()
wn.mainloop()
I adeeded two turtles as spaceships, and with my timer, I made the "arrow" turtle shoot at my other turtle with imported starwars charectors at certiant cords specific to the tip of the spaceship while one goes faster than the other so I could jump over one while dodging the other. How could I define my image length and width for all my four charectors, as well as my "arrow" lasers, and add a collision detection to python turtle?

Make a score system

How can I make a score system, that increases by one, when I hit square1. A score system, that restart back to 0, when I hit square2. And also loop back to the beginning position, when I hit square2. So loop back and restart the score to 0, when I hit square 2.
import turtle
import math
from time import sleep
wn = 0
player = turtle.Turtle()
square1 = turtle.Turtle()
square2 = turtle.Turtle()
speed = 1
def init():
wn = turtle.Screen()
wn.bgcolor("blue")
wn.tracer(3)
turtle.listen()
turtle.onkey(turnLeft, "Left")
turtle.onkey(turnRight, "Right")
def initCharacters():
player.color("red")
player.shape("circle")
player.penup()
player.speed(0)
player.setposition(25, 20)
square1.color("white")
square1.shape("square")
square1.penup()
square1.speed(0)
square1.setposition(100, 100)
square2.color("yellow")
square2.shape("square")
square2.penup()
square2.speed(0)
square2.setposition(150, 50)
def distanceIsLessThan(p, q, distance):
return math.pow(p.xcor() - q.xcor(), 2) + math.pow(p.ycor() - q.ycor(), 2) < math.pow(distance, 2)
def turnLeft():
player.left(90)
def turnRight():
player.right(90)
def main():
init()
initCharacters()
while True:
player.forward(speed)
if distanceIsLessThan(player, square1, 20) or \
distanceIsLessThan(player, square2, 20):
# print("Touch")
initCharacters()
sleep(0.02)
if __name__ == "__main__":
main()
This is basically what you want:
import turtle
import math
from time import sleep
#Adding the integer for the score
score=0
wn = 0
player = turtle.Turtle()
square1 = turtle.Turtle()
square2 = turtle.Turtle()
speed = 1
#Here Im making a new turtle for showing the score
turtle_score=turtle.Turtle()
turtle_score.penup()
turtle_score.hideturtle()
turtle_score.goto(-300.00,-245.00)
turtle_score.write("")
def init():
wn = turtle.Screen()
wn.bgcolor("blue")
wn.tracer(3)
turtle.listen()
turtle.onkey(turnLeft, "Left")
turtle.onkey(turnRight, "Right")
def initCharacters():
player.color("red")
player.shape("circle")
player.penup()
player.speed(0)
player.setposition(25, 20)
square1.color("white")
square1.shape("square")
square1.penup()
square1.speed(0)
square1.setposition(100, 100)
square2.color("yellow")
square2.shape("square")
square2.penup()
square2.speed(0)
square2.setposition(150, 50)
def distanceIsLessThan(p, q, distance):
return math.pow(p.xcor() - q.xcor(), 2) + math.pow(p.ycor() - q.ycor(), 2) < math.pow(distance, 2)
def turnLeft():
player.left(90)
def turnRight():
player.right(90)
def main():
init()
initCharacters()
global score
while True:
player.forward(speed)
#Checking which square the player collided with and updating the score.
if distanceIsLessThan(player, square1, 20):
score=score+1
player.fd(40)
turtle_score.undo()
turtle_score.write(str(score))
if distanceIsLessThan(player, square2, 20):
score=0
turtle_score.undo()
turtle_score.write(str(score))
# print("Touch")
initCharacters()
sleep(0.02)
if __name__ == "__main__":
main()
The score shows up at the bottom left corner of the screen.

Use of ontimer function to make two turtles move at same time

I 've been struggling to make both turtles move at the same time. Either one moves or they are both are frozen. I'm currently using the ontimer() function but still don't understand it completely.
The game is if you are wondering based of the paperio game but two players go against each other on the same keyboard and screen
My code:
from turtle import *
import turtle
p1f = True
p2f = True
title("1v1 Paperio")
p1move = Turtle()
p2move = Turtle()
t1 = Turtle()
t2 = Turtle()
screen = Screen()
def Setup1():
t1.pencolor("aquamarine")
t1.pensize(5)
t1.speed(10)
t1.fillcolor("light sea green")
t1.hideturtle()
t1.penup()
t1.goto(-200, -200)
t1.pendown()
t1.begin_fill()
for i in range(4):
t1.forward(50)
t1.left(90)
t1.end_fill()
p1move.penup()
p1move.goto(-175, -175)
p1move.pendown()
def Setup2():
t2.pencolor("crimson")
t2.pensize(5)
t2.speed(10)
t2.fillcolor("red")
t2.hideturtle()
t2.penup()
t2.goto(200, 200)
t2.pendown()
t2.begin_fill()
for i in range(4):
t2.forward(50)
t2.left(90)
t2.end_fill()
p2move.penup()
p2move.goto(225, 225)
p2move.pendown()
def p1setup():
p1move.pencolor("aquamarine")
p1move.pensize(5)
p1move.speed(10)
p1move.fillcolor("light sea green")
def p2setup():
p2move.pencolor("crimson")
p2move.pensize(5)
p2move.speed(10)
p2move.fillcolor("red")
# ycord
# heading
def p1moving():
def p1k1():
p1x1 = p1move.xcor()
p1y1 = p1move.ycor()
while p1f == True:
p1move.forward(1)
screen.ontimer(p1moving, 1)
def p1k2():
p1move.left(90)
def p1k3():
p1move.right(90)
def p2moving():
def p2k1():
p2f = True
p2x2 = p2move.xcor()
p2y2 = p2move.ycor()
while p2f == True:
p2move.forward(1)
screen.ontimer(p2moving, 1)
def p2k2():
p2move.left(90)
def p2k3():
p2move.right(90)
screen.listen()
screen.onkey(p1k1, "w")
screen.onkey(p1k2, "a")
screen.onkey(p1k3, "d")
screen.onkey(p2k1, "Up")
screen.onkey(p2k2, "Left")
screen.onkey(p2k3, "Right")
if __name__ == "__main__":
Setup1()
Setup2()
p1setup()
p2setup()
screen.mainloop()
Most of your code seems reasonable until you get to the key and timer event functions -- you have unused variables and functions that don't get called. Your functions defined inside functions are particularly problematic. I've reworked your code below to run as you describe. I've also done some speed optimizations to make it "play" a little better:
from turtle import Screen, Turtle
def setup1():
base1.hideturtle()
base1.color("light sea green", "aquamarine")
base1.pensize(5)
base1.penup()
base1.goto(-200, -200)
base1.pendown()
base1.begin_fill()
for _ in range(4):
base1.forward(50)
base1.left(90)
base1.end_fill()
pen1.color("light sea green", "aquamarine")
pen1.pensize(5)
pen1.setheading(0)
pen1.penup()
pen1.goto(-175, -175)
pen1.pendown()
def setup2():
base2.hideturtle()
base2.color("red", "pink")
base2.pensize(5)
base2.penup()
base2.goto(200, 200)
base2.pendown()
base2.begin_fill()
for _ in range(4):
base2.forward(50)
base2.left(90)
base2.end_fill()
pen2.color("red", "pink")
pen2.pensize(5)
pen2.setheading(180)
pen2.penup()
pen2.goto(225, 225)
pen2.pendown()
def p1k1():
screen.onkey(None, 'w')
def p1forward():
pen1.forward(1)
screen.update()
screen.ontimer(p1forward, 10)
p1forward()
def p1k2():
pen1.left(90)
screen.update()
def p1k3():
pen1.right(90)
screen.update()
def p2k1():
screen.onkey(None, 'Up')
def p2forward():
pen2.forward(1)
screen.update()
screen.ontimer(p2forward, 10)
p2forward()
def p2k2():
pen2.left(90)
screen.update()
def p2k3():
pen2.right(90)
screen.update()
screen = Screen()
screen.title("1v1 Paperio")
screen.tracer(False)
base1 = Turtle()
pen1 = Turtle()
setup1()
base2 = Turtle()
pen2 = Turtle()
setup2()
screen.onkey(p1k1, 'w')
screen.onkey(p1k2, 'a')
screen.onkey(p1k3, 'd')
screen.onkey(p2k1, 'Up')
screen.onkey(p2k2, 'Left')
screen.onkey(p2k3, 'Right')
screen.update()
screen.listen()
screen.mainloop()

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

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: ")

Counting down lives in python turtle

I am trying to create a simple python turtle game where the turtle needs to make it to the circle, while avoiding the moving square. I would like the code to count down lives and move the turtle back to the beginning until there are 0 lives left. The code below allows for one play and then the motion loop does not repeat.
I have tried a recursive function (move(3)), but then the onkey commands don't work....
import turtle, random, time
#background
canvas = turtle.Screen()
canvas.bgcolor('black')
#Pen
pen = turtle.Turtle()
pen.penup()
pen.color('white')
pen.hideturtle()
pen.penup()
#Lilypad
pad = turtle.Turtle()
pad.hideturtle()
pad.color('yellow')
pad.shape('circle')
pad.penup()
pad.setposition(0,290)
pad.showturtle()
#Turtle
player = turtle.Turtle()
player.hideturtle()
player.shape('turtle')
player.color('green')
player.penup()
player.left(90)
player.setposition(0, -290)
player.showturtle()
#truck
truck1 = turtle.Turtle()
truck1.hideturtle()
truck1.shape('square')
truck1.color('blue')
truck1.penup()
truck1.showturtle()
speed = random.randint(1,5)
def move():
#move player and truck
player.forward(2)
truck1.forward(speed)
if truck1.xcor() > 300 or truck1.xcor() < -300:
truck1.right(180)
#win if hit the lilypad
if player.distance(pad)<10:
pen.penup()
pen.setposition(0,-50)
pen.write('You win!', align='left', font=('Arial', 36, 'normal'))
done()
#lose a life if hit the truck
if player.distance(truck1) < 30:
player.setposition(0,-290)
life = life - 1
while life > 0:
pen.penup()
pen.setposition(0,-60)
pen.write('Try again', align='left', font=('Arial', 36, 'normal'))
time.sleep(1)
pen.clear()
move()
#game over if 0 lives left
pen.penup()
pen.setposition(0,-60)
pen.write('Game over!', align='left', font=('Arial', 36, 'normal'))
done()
canvas.ontimer(move,10)
canvas.onkey(lambda:player.setheading(90),'Up')
canvas.onkey(lambda:player.setheading(180),'Left')
canvas.onkey(lambda:player.setheading(0),'Right')
canvas.onkey(lambda:player.setheading(270),'Down')
canvas.listen()
life = 3
move()
canvas.mainloop()
The key to this is to move all your initialization code into a function, which invokes your move() function as it's last step. The first thing that the initialization code does is call canvas.clear() which pretty much wipes out everything. Then your move() function makes a choice at the end whether to call itself on the next timer iteration, or call the initialize code on the next timer iteration to reset everything and start a new game.
Below is your code reworked along the above lines as well as various teaks:
from turtle import Screen, Turtle
from random import randint
from time import sleep
FONT = ('Arial', 36, 'normal')
def initialize():
global pen, pad, player, truck, speed, life
canvas.clear() # assume that this resets *everything*
# background
canvas.bgcolor('black')
# Pen
pen = Turtle(visible=False)
pen.color('white')
pen.penup()
# Lilypad
pad = Turtle('circle', visible=False)
pad.color('yellow')
pad.penup()
pad.setposition(0, 290)
pad.showturtle()
# Turtle
player = Turtle('turtle', visible=False)
player.color('green')
player.penup()
player.setheading(90)
player.setposition(0, -290)
player.showturtle()
# truck
truck = Turtle('square', visible=False)
truck.color('blue')
truck.penup()
truck.showturtle()
speed = randint(1, 5)
canvas.onkey(lambda: player.setheading(90), 'Up')
canvas.onkey(lambda: player.setheading(180), 'Left')
canvas.onkey(lambda: player.setheading(0), 'Right')
canvas.onkey(lambda: player.setheading(270), 'Down')
canvas.listen()
life = 3
move()
def move():
global life
# move player and truck
player.forward(2)
truck.forward(speed)
if not -300 < truck.xcor() < 300:
truck.right(180)
# lose a life if hit the truck
if player.distance(truck) < 20:
player.setposition(0, -290)
life -= 1
if life > 0:
pen.setposition(0, -60)
pen.write('Try again', font=FONT)
sleep(1)
pen.clear()
# win if hit the lilypad
if player.distance(pad) < 20:
pen.setposition(0, -50)
pen.write('You win!', font=FONT)
canvas.ontimer(initialize, 1000)
elif life == 0: # game over if 0 lives left
pen.setposition(0, -60)
pen.write('Game over!', font=FONT)
canvas.ontimer(initialize, 1000)
else:
canvas.ontimer(move, 10)
canvas = Screen()
pen = None
pad = None
player = None
truck = None
speed = -1
life = -1
initialize()
canvas.mainloop()
This should let you play over again whether you win or run out of lives.

Categories