[ad_1]
import tkinter as tk import random # Create the Tkinter window root = tk.Tk() root.title("Character Movement") canvas = tk.Canvas(root, width=400, height=400) canvas.pack() # Create the character (rectangle) character = canvas.create_rectangle(180, 180, 220, 220, fill="blue") # Create a list to keep track of falling blocks falling_blocks = [] # Function to move the character def move(event): x, y = 0, 0 if event.keysym == 'Up': y = -10 elif event.keysym == 'Down': y = 10 elif event.keysym == 'Left': x = -10 elif event.keysym == 'Right': x = 10 # Check if the character is within the window boundaries before moving if 0 < canvas.coords(character)[0] + x < 400 and 0 < canvas.coords(character)[1] + y < 400: canvas.move(character, x, y) check_collision() # Function to create falling blocks def create_falling_block(): x = random.randint(0, 400) block = canvas.create_rectangle(x, 0, x+30, 30, fill="red") falling_blocks.append(block) animate_falling_block(block) # Function to animate the falling blocks def animate_falling_block(block): if canvas.coords(block)[3] < 400: canvas.move(block, 0, 5) if check_collision(block): end_game() else: root.after(100, animate_falling_block, block) # Function to check for collisions def check_collision(block=None): character_coords = canvas.coords(character) if block: block_coords = canvas.coords(block) if (character_coords[0] < block_coords[2] and character_coords[2] > block_coords[0] and character_coords[1] < block_coords[3] and character_coords[3] > block_coords[1]): return True return False # Function to end the game def end_game(): canvas.create_text(200, 200, text="You lose!", font=("Helvetica", 20), fill="red") # Create falling blocks every 2 seconds root.after(2000, create_falling_block) # Bind arrow key presses to the move function root.bind('<Up>', move) root.bind('<Down>', move) root.bind('<Left>', move) root.bind('<Right>', move) # Run the Tkinter main loop root.mainloop()
एक से अधिक कैसे पैदा करें
मैंने क्या प्रयास किया है:
लूप जोड़ना जैसे while true और sys.sleep इत्यादि
समाधान 1
अजगर
# Create falling blocks every 2 seconds root.after(2000, create_falling_block)
आप इसे शुरुआत में केवल एक बार ही करें। आपको इसे अधिक बार करने की आवश्यकता है।
[ad_2]
コメント