Python Forum
[Tkinter] Loop help in game
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Loop help in game
#1
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.
Reply
#2
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.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  If 2nd input in the game is correct, replace with 1st input and loop the game tylerdurdane 11 4,028 Jul-17-2022, 04:55 AM
Last Post: deanhystad
  [PyGame] Problem With Entering Game Loop ElevenDecember 3 2,607 Jan-19-2020, 08:25 AM
Last Post: michael1789

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020