My text in my clock python is not aligning properly - python

My text in my turtle module is not aligning properly, it is aligned up and to the left. I want it to align exactly where the turtle is. Can anyone help? I tried setting the xcor and ycor of the turtle up and to the left by 5 units and that did not work. Any help would be greatly appreciated.
Code:
import time
from datetime import datetime,date
import turtle
t = turtle.Pen()
while True:
turtle.tracer(0, 0)
hour_hand = float(datetime.today().hour)
minute_hand = float(datetime.today().minute)
second_hand = float(datetime.today().second)
# Draw circle
t.hideturtle()
t.circle(150)
t.left(90)
t.up()
t.forward(150)
t.down()
# Draw hands
t.right(float(float(minute_hand) * 6))
t.forward(100)
t.backward(100)
t.left(float(float(minute_hand) * 6))
t.right(int(float(hour_hand) * 30 + float(minute_hand) / 60 * 30))
t.forward(50)
t.backward(50)
t.left(int(float(hour_hand) * 30 + float(minute_hand) / 60 * 30))
t.right(second_hand * 6)
t.forward(125)
t.backward(125)
t.left(second_hand * 6)
# Draw ticks
for x in range(0, 12):
t.up()
t.forward(130)
t.down()
t.forward(20)
t.backward(20)
t.up()
t.backward(130)
t.down()
t.right(30)
for y in range(0, 60):
t.up()
t.forward(140)
t.down()
t.forward(10)
t.backward(10)
t.up()
t.backward(140)
t.down()
t.right(6)
t.up()
# Draw numbers
t.right(32.5)
for z in range(1, 12):
t.forward(130)
t.sety(t.ycor() - 5)
t.setx(t.xcor() - 5)
t.write(z, align = 'center', font = ('Times New Roman', 16))
t.sety(t.ycor() + 5)
t.setx(t.xcor() + 5)
t.backward(130)
t.right(30)
t.forward(130)
t.write(12, align = 'center', font = ('Times New Roman', 16))
turtle.update()
t.hideturtle()
time.sleep(0.85)
t.reset()
I don't really want to use tkinter, it is too complicated.

A simpler, though potentially less accurate, way to do this completely within turtle:
FONT_SIZE = 16
FONT = ('Times New Roman', FONT_SIZE)
t.color('red')
t.dot(2) # show target of where we want to center text, for debugging
t.color('black')
t.sety(t.ycor() - FONT_SIZE/2)
t.write(12, align='center', font=FONT)
Now let's address your program as a whole. The primary issues I see is that it flickers and is more complicated than necessary. The first thing to do is to switch turtle into Logo mode, which makes positive angles clockwise and makes 0 degrees at the top (not unlike a clock!).
Then we split the dial drawing onto it's own turtle to be drawn once an we put the hands on their own turtle to be erased and redraw over and over. We all toss the while True: and sleep(), which have no place in an event-driven world like turtle, and use a turtle timer event instead:
from datetime import datetime
from turtle import Screen, Turtle
OUTER_RADIUS = 150
LARGE_TICK = 20
SMALL_TICK = 10
FONT_SIZE = 16
FONT = ('Times New Roman', FONT_SIZE)
def draw_dial():
dial = Turtle()
dial.hideturtle()
dial.dot()
dial.up()
dial.forward(OUTER_RADIUS)
dial.right(90)
dial.down()
dial.circle(-OUTER_RADIUS)
dial.up()
dial.left(90)
dial.backward(OUTER_RADIUS)
for mark in range(60):
distance = LARGE_TICK if mark % 5 == 0 else SMALL_TICK
dial.forward(OUTER_RADIUS)
dial.down()
dial.backward(distance)
dial.up()
dial.backward(OUTER_RADIUS - distance)
dial.right(6)
dial.sety(-FONT_SIZE/2)
dial.setheading(30) # starting at 1 o'clock
for z in range(1, 13):
dial.forward(OUTER_RADIUS - (LARGE_TICK + FONT_SIZE/2))
dial.write(z, align='center', font=FONT)
dial.backward(OUTER_RADIUS - (LARGE_TICK + FONT_SIZE/2))
dial.right(30)
def tick():
hour_hand = datetime.today().hour
minute_hand = datetime.today().minute
second_hand = datetime.today().second
hands.reset()
hands.hideturtle() # redo as undone by reset()
hands.right(hour_hand * 30 + minute_hand / 60 * 30)
hands.forward(1/3 * OUTER_RADIUS)
hands.backward(1/3 * OUTER_RADIUS)
hands.left(hour_hand * 30 + minute_hand / 60 * 30)
hands.right(minute_hand * 6)
hands.forward(2/3 * OUTER_RADIUS)
hands.backward(2/3 * OUTER_RADIUS)
hands.left(minute_hand * 6)
hands.right(second_hand * 6)
hands.forward(OUTER_RADIUS - (LARGE_TICK + FONT_SIZE))
hands.backward(OUTER_RADIUS - (LARGE_TICK + FONT_SIZE))
hands.left(second_hand * 6)
screen.update()
screen.ontimer(tick, 1000)
screen = Screen()
screen.mode('logo') # make 0 degrees straight up, positive angles clockwise (like a clock!)
screen.tracer(False)
draw_dial()
hands = Turtle()
tick()
screen.mainloop()

I don't really want to use tkinter, it is too complicated.
I don't think it's too complicated and it is the most straight-forward solution to center the text vertically.
Use the following code to get the height of text in your font:
from tkinter import font
t = turtle.Pen()
font_config = font.Font(font=('Times New Roman', 16))
font_height = font_config.metrics("linespace")
Then draw your text using font_height/2 as the vertical offset:
t.sety(t.ycor() - font_height/2)
t.write(z, align="center", font=font_config)
t.sety(t.ycor() + font_height/2)

Related

i wanna draw a chessboard and here is my code(edited)

it has no error now but i want to draw a chess board but this thing just randomly output something else:)))))
i think there is something wrong with the fill function tho
import turtle
screen = turtle.Screen()
screen.setup(800,800)
screen.bgcolor('pink')
screen.colormode(255)
screen.title("chessboard")
turtle = turtle.Turtle()
def draw(length,angle):
for i in range (4):
turtle.forward(length)
turtle.right(angle)
length = 30
angle = 90
coor = -120
num = 64
def board(length):
draw(length,angle)
turtle.forward(length)
def limit():
for q in range (8):
board(length)
def pos(coor,length):
for w in range(8):
turtle.penup()
turtle.setpos(coor,coor+30*w)
turtle.pendown()
limit()
def fill():
for q in range (8):
for w in range(8):
if (q+w)%2==0:
turtle.fillcolor('#000000')
else:
turtle.fillcolor('#FFFFFF')
def repeat():
for h in range (8):
draw(length,angle)
turtle.forward(length)
def color():
turtle.begin_fill()
repeat()
pos(coor,length)
fill()
turtle.end_fill()
turtle.speed(0)
turtle.penup()
turtle.goto(coor, coor)
turtle.pendown()
turtle.hideturtle()
screen.update()
color()
it has no error now but i want to draw a chess board but this thing just randomly output something else:)))))
i think there is something wrong with the fill function tho
I'm just learning python as well, so I found your problem being an interesting thing to try to do myself.
Please see below a solution that works, using some ideas from your code and my own implementation too.
If anything of the above helps you fix your own code, or have any questions I might be able to answer, please let me know :)
import turtle
# draw a square at given pos
def draw_square(t, fwd, angle):
for _ in range(4):
t.forward(fwd)
t.right(angle)
def changePos(t, startPos, endPos, penUp):
if penUp:
t.pu()
t.goto(startPos, endPos)
if penUp:
t.pd()
# Let's skip the drawing all together?
turtle.tracer(0, 0)
# taking input for the side of the square
squareSize = 100
angle = 90
boardSquares = 8
startPos = -(squareSize * (boardSquares/2)), (squareSize * (boardSquares/2)) #start from top-left
print("Start position: ", startPos)
screen = turtle.Screen()
screen.setup(850, 850)
screen.bgcolor('pink')
screen.title("chessboard")
# create the white squares
squares = turtle.Turtle()
squares.hideturtle()
squares.fillcolor("white")
squares.pensize(1)
squares.pencolor("red")
changePos(squares, startPos[0], startPos[1], True)
for r in range(8):
for c in range(8):
if (r + c) % 2 == 0:
squares.fillcolor('#000000')
else:
squares.fillcolor('#FFFFFF')
changePos(squares, startPos[0] + (squareSize * c), startPos[1] - (squareSize * r), True)
squares.begin_fill()
draw_square(squares, squareSize, angle)
squares.end_fill()
# let's draw the board edge
board = turtle.Turtle()
board.hideturtle()
changePos(board, startPos[0], startPos[1], True)
board.pensize(5)
board.pencolor("brown")
draw_square(board, boardSquares * squareSize, angle)
turtle.update()
turtle.exitonclick()

In the turtle module, how to find the maximum values of coordinates?

import turtle as t
from random import randint, random
def draw_star(points, size, col, x, y):
t.penup()
t.goto(x, y)
t.pendown()
angle = 180 - (180 / points)
t.color(col)
t.begin_fill()
for i in range(points):
t.forward(size)
t.right(angle)
t.end_fill()
# Main code
while True:
ranPts = randint(2, 5) * 2 + 1
ranSize = randint(10, 50)
ranCol = (random(), random(), random())
ranX = randint(-350, 300)
ranY = randint(-250, 250)
draw_star(ranPts, ranSize, ranCol, ranX, ranY)
Question:
How could I know the maximum values of coordinates of my screen? So I can have a better idea on how to set the values of ranX and ranY?
Thanks.
You could use t.setworldcoordinates(llx, lly, urx, ury)
The parameters:
llx = x of lower left corner
lly = y of lower left corner
urx= x of upper right corner
ury = y of upper right corner
You can create a function and find the values of coordinates yourself by clicking on the screen like this:
# turtle library
import turtle
#This to make turtle object
tess=turtle.Turtle()
# self defined function to print coordinate
def buttonclick(x,y):
print("You clicked at this coordinate({0},{1})".format(x,y))
#onscreen function to send coordinate
turtle.onscreenclick(buttonclick,1)
turtle.listen() # listen to incoming connections
turtle.speed(10) # set the speed
turtle.done() # hold the screen
This will print everytime you click on the screen and print the coordinates out.
The screensize() function returns the canvas width and the canvas height as a tuple.
You can use this to find the max coordinates of the canvas.
screenSize = t.screensize() #returns (width, height)
# Main code
while True:
ranPts = randint(2, 5) * 2 + 1
ranSize = randint(10, 50)
ranCol = (random(), random(), random())
ranX = randint(50-screenSize[0], screenSize[0] - 100)
ranY = randint(50-screenSize[1], screenSize[1] - 100)
draw_star(ranPts, ranSize, ranCol, ranX, ranY)
I found out this is what I need: t.window_width() and t.window_height().

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

How to draw a clock on python?(one that doesn't have hour hand or minute hand, just a diagram)

I tried to create a picture of a clock face with python 3 turtle, but the numbers aren't correctly aligned. A little help? Thanks! This is what i have so far:
import turtle
screen=turtle.Screen()
screen.bgcolor(135, 205, 250)
clock = turtle.Turtle()
clock.shape("square")
clock.speed(0)
hours = 6
minutes = 30
angle = 12
for i in range(angle):
# draw the leg
clock.forward(65)
clock.right(30)
clock.write(i)
# go back to the middle and turn back around
clock.right(180)
clock.forward(65)
clock.right(180)
clock.write(i+1)
clock.shape("circle")
clock.forward(65)
screen.exitonclick()
Your use of bgcolor(135, 205, 250) without first calling colormode(255) makes me suspect you're using a non-standard (Repl) or older version of Python turtle. If so, you should state such to avoid incompatibilities in the answers provided.
Below is how I might go about this problem. The key is to have a sense of the font height so you can make corrections:
from turtle import Screen, Turtle
FONT_SIZE = 12
FONT = ('Arial', FONT_SIZE, 'normal')
RADIUS = 65
screen = Screen()
clock = Turtle()
clock.shape('circle')
clock.speed('fastest')
for hour, angle in enumerate(range(60, -300, -30), start=1):
clock.setheading(angle)
position = clock.position()
clock.forward(RADIUS)
clock.penup()
clock.forward(FONT_SIZE)
clock.sety(clock.ycor() - 2 * FONT_SIZE/3)
clock.write(hour, align='center', font=FONT)
clock.setposition(position)
clock.pendown()
screen.mainloop()
However, using the stated font size is a rough guess and may work poorly on some systems. If this is the case for you, then you can get an accurate value for the font height using the underpinning tkinter function call in this answer My text in my clock python is not aligning properly which I assume you reviewed in your search of SO before posting your own question.
#cdlane has answered correctly - but here is a clock with the date as well.
from turtle import *
from datetime import datetime
def jump(distanz, winkel=0):
penup()
right(winkel)
forward(distanz)
left(winkel)
pendown()
def hand(laenge, spitze):
fd(laenge*1.15)
rt(90)
fd(spitze/2.0)
lt(120)
fd(spitze)
lt(120)
fd(spitze)
lt(120)
fd(spitze/2.0)
def make_hand_shape(name, laenge, spitze):
reset()
jump(-laenge*0.15)
begin_poly()
hand(laenge, spitze)
end_poly()
hand_form = get_poly()
register_shape(name, hand_form)
def clockface(radius):
reset()
pensize(7)
for i in range(60):
jump(radius)
if i % 5 == 0:
fd(25)
jump(-radius-25)
else:
dot(3)
jump(-radius)
rt(6)
def setup():
global second_hand, minute_hand, hour_hand, writer
mode("logo")
make_hand_shape("second_hand", 125, 25)
make_hand_shape("minute_hand", 130, 25)
make_hand_shape("hour_hand", 90, 25)
clockface(160)
second_hand = Turtle()
second_hand.shape("second_hand")
second_hand.color("gray20", "gray80")
minute_hand = Turtle()
minute_hand.shape("minute_hand")
minute_hand.color("blue1", "red1")
hour_hand = Turtle()
hour_hand.shape("hour_hand")
hour_hand.color("blue3", "red3")
for hand in second_hand, minute_hand, hour_hand:
hand.resizemode("user")
hand.shapesize(1, 1, 3)
hand.speed(0)
ht()
writer = Turtle()
#writer.mode("logo")
writer.ht()
writer.pu()
writer.bk(85)
def wochentag(t):
wochentag = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"]
return wochentag[t.weekday()]
def datum(z):
monat = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "June",
"July", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."]
j = z.year
m = monat[z.month - 1]
t = z.day
return "%s %d %d" % (m, t, j)
def tick():
t = datetime.today()
sekunde = t.second + t.microsecond*0.000001
minute = t.minute + sekunde/60.0
stunde = t.hour + minute/60.0
try:
tracer(False) # Terminator can occur here
writer.clear()
writer.home()
writer.forward(65)
writer.write(wochentag(t),
align="center", font=("Courier", 14, "bold"))
writer.back(150)
writer.write(datum(t),
align="center", font=("Courier", 14, "bold"))
writer.forward(85)
tracer(True)
second_hand.setheading(6*sekunde) # or here
minute_hand.setheading(6*minute)
hour_hand.setheading(30*stunde)
tracer(True)
ontimer(tick, 100)
except Terminator:
pass
def main():
tracer(False)
setup()
tracer(True)
tick()
return "EVENTLOOP"
if __name__ == "__main__":
mode("logo")
msg = main()
print(msg)
mainloop()
You can control the alignment of the text horizontally in your write() statement with align="center". To align it vertically, you will have to adjust the position with .sety(), accounting for the font's vertical dimension, as shown in the answer to How to center text using "turtle" module in Python

How to add a countdown timer to my turtle program?

I'm trying to make a game using turtle where the player has to click as many randomly distributed circles in a set amount of time, but I'm stumped on how to create a timer inside the game. Whenever I try to set the timer, it counts down before the game starts or counts down after 1 circle spawns. I want to have it count down as the game starts, and have the game end once the timer ends.
I'm also trying to create a score counter, but am I using circle.onclick wrong?
This is what I've been trying to do:
from turtle import Turtle, Screen
from random import random, randint
import time
CURSOR_SIZE = 20
def score():
num=0
print("Score: ",num)
def my_circle(color):
radius = randint(10, 50)
circle = Turtle('circle', visible=False)
circle.shapesize(radius / CURSOR_SIZE)
circle.color(color)
circle.penup()
while True:
nx = randint(2 * radius - width // 2, width // 2 - radius * 2)
ny = randint(2 * radius - height // 2, height // 2 - radius * 2)
circle.goto(nx, ny)
for other_radius, other_circle in circles:
if circle.distance(other_circle) < 2 * max(radius, other_radius):
break
else:
break
circle.showturtle()
circle.onclick(lambda x, y, t=circle: t.hideturtle())
circle.onclick(num=num+1)
return radius, circle
screen = Screen()
screen.bgcolor("lightgreen")
screen.title("Speed Clicker")
width, height = screen.window_width(), screen.window_height()
circles = []
for _ in range(0, 20):
for i in range(40):
print(str(40-i)+" seconds remain")
time.sleep(1)
rgb = (random(), random(), random())
circles.append(my_circle(rgb))
screen.mainloop()
The last thing I'm curious about is if it's possible to have the timer and score printed ON the game, rather than on the Python Shell.
I've made a few alterations and this seems to work. I have put the score and the time left in the title bar of the game. Thanks
import turtle
from random import random, randint
import time
CURSOR_SIZE = 20
num=0
def increase_score():
global num
num += 1
def my_circle(color):
radius = randint(10, 50)
circle = turtle.Turtle('circle', visible=False)
circle.shapesize(radius / CURSOR_SIZE)
circle.color(color)
circle.penup()
while True:
nx = randint(2 * radius - width // 2, width // 2 - radius * 2)
ny = randint(2 * radius - height // 2, height // 2 - radius * 2)
circle.goto(nx, ny)
for other_radius, other_circle in circles:
if circle.distance(other_circle) < 2 * max(radius, other_radius):
break
else:
break
circle.showturtle()
circle.onclick(lambda x,y,t=circle: (circle.hideturtle(), increase_score()))
return radius, circle
screen = turtle.Screen()
screen.bgcolor("lightgreen")
screen.title("Speed Clicker")
width, height = screen.window_width(), screen.window_height()
circles = []
gameLength = 5
# Higher number means faster blocks
# 1-10
difficulty = 10
startTime = time.time()
while True:
time.sleep(1/difficulty)
rgb = (random(), random(), random())
timeTaken = time.time() - startTime
circles.append(my_circle(rgb))
screen.title('SCORE: {}, TIME LEFT: {}'.format(num,int(round(gameLength - timeTaken,0))))
if time.time() - startTime > gameLength:
break
screen.title('FINISHED! FINAL SCORE: {}'.format(num))
screen.mainloop()

Categories