Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # I want YOU to try complete this game.
- # 1. Make the food eating system work
- # 2. When the obstacle/enemy touches you, lose.
- # 3. [OPTIONAL CHALLENGE] Make a level system that gets harder and harder.
- # 4. [OPTIONAL CHALLENGE] Make cleaner UI
- # WHEN DONE, WRITE A COMMENT TO THE PASTEBIN URL OF YOUR CODE!
- import tkinter as tk
- import random
- import math
- # Initialize the window
- window = tk.Tk()
- window.title("Retro Game")
- window.geometry("500x500")
- # Game variables
- character_pos = [50, 50]
- character_speed = 2
- food_pos = [random.randint(50, 450), random.randint(50, 450)]
- obstacle_pos = [random.randint(50, 450), random.randint(50, 450)]
- obstacle_speed = 0.5
- score = 0
- score_label = None # Declare score_label as a global variable
- # Function to move the character
- def move_character(event):
- key = event.keysym
- if key == "Up":
- character_pos[1] -= character_speed
- elif key == "Down":
- character_pos[1] += character_speed
- elif key == "Left":
- character_pos[0] -= character_speed
- elif key == "Right":
- character_pos[0] += character_speed
- check_collision()
- # Function to update the obstacle's position
- def update_obstacle():
- global obstacle_pos
- dx = character_pos[0] - obstacle_pos[0]
- dy = character_pos[1] - obstacle_pos[1]
- angle = math.atan2(dy, dx)
- obstacle_pos[0] += obstacle_speed * math.cos(angle)
- obstacle_pos[1] += obstacle_speed * math.sin(angle)
- check_collision()
- # Function to check collision between character and objects/obstacles
- def check_collision():
- global score
- if character_pos[0] == food_pos[0] and character_pos[1] == food_pos[1]:
- score += 1
- food_pos[0] = random.randint(50, 450)
- food_pos[1] = random.randint(50, 450)
- update_game()
- # Function to update the game
- def update_game():
- canvas.delete("all")
- canvas.create_rectangle(character_pos[0] - 10, character_pos[1] - 10,
- character_pos[0] + 10, character_pos[1] + 10,
- fill="blue")
- canvas.create_oval(food_pos[0] - 5, food_pos[1] - 5,
- food_pos[0] + 5, food_pos[1] + 5,
- fill="green")
- canvas.create_rectangle(obstacle_pos[0] - 10, obstacle_pos[1] - 10,
- obstacle_pos[0] + 10, obstacle_pos[1] + 10,
- fill="red")
- score_label.config(text="Score: {}".format(score))
- # Create the canvas for drawing
- canvas = tk.Canvas(window, bg="white", width=500, height=500)
- canvas.pack()
- # Create a label to display the score
- score_label = tk.Label(window, text="Score: 0")
- score_label.pack(pady=10)
- # Bind keyboard events to the character movement function
- window.bind("<KeyPress>", move_character)
- window.focus_set()
- # Start the game loop
- def game_loop():
- update_obstacle()
- window.after(10, game_loop)
- game_loop()
- # Start the game
- update_game()
- # Run the tkinter event loop
- window.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement