Python Forum
[Tkinter] Loop help in game - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Game Development (https://python-forum.io/forum-11.html)
+--- Thread: [Tkinter] Loop help in game (/thread-2225.html)



Loop help in game - Kgranulo1 - Feb-28-2017

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.


RE: Loop help in game - wavic - Feb-28-2017

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.