Python Forum

Full Version: Loop help in game
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import time
from tkinter import *
tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()
rectangle = canvas.create_rectangle(350, 10, 375, 200, fill="blue")
canvas.itemconfig(rectangle, outline="black")
triangle = canvas.create_polygon(10, 10, 10, 60, 50, 35, fill="red")
canvas.itemconfig(triangle, outline="black")

def startgame():
    while 1:
        for x in range(0, 60):
            canvas.move(rectangle, 0, 4)
            tk.update()
            time.sleep(0.04)
        for x in range(0, 60):
            canvas.move(rectangle, 0, -4)
            tk.update()
            time.sleep(0.04)

        time.sleep(20)
        canvas.create_text(200, 200, text="GAME OVER", font=('Times', 30), fill="red")
        canvas.delete(rectangle)
        canvas.delete(triangle)

btn = Button(tk, text="Start Game", command=startgame)
btn.pack()
Currently this is the beginning of my simple game. When I try to create the loop it stops afterwards(moving rectangle) and prints "Game Over" after a few seconds. I need it to continue and then print game over after the specified time. Thank you very much for the help.
Hello!
I don't know Tk but I see the two for loops? Each of it loops 60 times and waits for 0.04 sec. So execution time for the first one is about 2.4 sec.  The same for the second. Roughly speaking that makes 5 sec.