📜  pygame rect follower - Python (1)

📅  最后修改于: 2023-12-03 15:33:49.876000             🧑  作者: Mango

Pygame Rect Follower

Pygame Rect Follower is a small Python script that demonstrates how to use the Pygame library to create a simple game in which a rectangle follows the position of the mouse on the screen.

Prerequisites

To run Pygame Rect Follower, you'll need:

  • Python 3.x installed on your computer
  • Pygame library installed on your computer

You can download Python from the official website: https://www.python.org/downloads/ To install Pygame, open your terminal/command prompt and type the following command:

pip install pygame
How to Run Pygame Rect Follower

To run Pygame Rect Follower, follow these steps:

  1. Download the script from the github repository: https://github.com/kavishjadon/pygame-rect-follower

  2. Open your terminal/command prompt and navigate to the folder where you saved the script

  3. Type the following command to run the script:

python main.py
  1. Move your mouse around the Pygame window and watch the rectangle follow it!
Code Explanation

Here's a brief explanation of how Pygame Rect Follower works:

  1. First, we import the Pygame library:
import pygame
  1. Then, we initialize Pygame:
pygame.init()
  1. We set up the Pygame window:
size = [700, 500]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pygame Rect Follower")
  1. We create a rectangle object:
rect = pygame.Rect(0, 0, 50, 50)
  1. Inside the game loop, we get the position of the mouse:
mouse_pos = pygame.mouse.get_pos()
  1. We update the position of the rectangle to match the position of the mouse:
rect.centerx = mouse_pos[0]
rect.centery = mouse_pos[1]
  1. Finally, we draw the rectangle to the screen:
pygame.draw.rect(screen, (0, 128, 255), rect)
Conclusion

Pygame Rect Follower is a fun and simple Python script that demonstrates how to use the Pygame library to create a game. It's a great starting point for anyone interested in learning how to program games in Python!