ASSISTANT
Certainly! Let's create a simple Python game where a plane flies through clouds and must avoid hitting flying dinosaurs. We'll use the **Pygame** library, which is great for creating games in Python.
**Prerequisites:**
1. Ensure you have Python installed (preferably Python 3.6 or later).
2. Install Pygame if you haven't already:
```bash
pip install pygame
```
---
### **Game Overview**
- **Player Controls:** The player controls a plane that can move up and down.
- **Objective:** Avoid colliding with flying dinosaurs that approach from the right side of the screen.
- **Scoring:** The game keeps track of how long you survive.
---
### **Code Implementation**
Below is the complete code for the game:
```python
import pygame
import random
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# Colors
WHITE = (255, 255, 255)
SKY_BLUE = (135, 206, 235)
BLACK = (0, 0, 0)
# Load images
plane_img = pygame.image.load("plane.png") # Replace with your plane image
dino_img = pygame.image.load("dino.png") # Replace with your dinosaur image
cloud_img = pygame.image.load("cloud.png") # Replace with your cloud image
# Scale images
plane_img = pygame.transform.scale(plane_img, (100, 50))
dino_img = pygame.transform.scale(dino_img, (80, 60))
cloud_img = pygame.transform.scale(cloud_img, (120, 80))
# Create the game window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Plane vs Flying Dinosaurs")
# Clock object to control game frame rate
clock = pygame.time.Clock()
# Font for displaying score
font = pygame.font.SysFont(None, 36)
def draw_text(text, font, color, surface, x, y):
"""Helper function to draw text on the screen."""
textobj = font.render(text, True, color)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
class Plane(pygame.sprite.Sprite):
"""Player's plane."""
def __init__(self):
super().__init__()
self.image = plane_img
self.rect = self.image.get_rect()
self.rect.center = (100, SCREEN_HEIGHT//2)
self.speed = 5
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
if self.rect.top > 0:
self.rect.y -= self.speed
if keys[pygame.K_DOWN]:
if self.rect.bottom < SCREEN_HEIGHT:
self.rect.y += self.speed
class Dinosaur(pygame.sprite.Sprite):
"""Flying dinosaur enemy."""
def __init__(self):
super().__init__()
self.image = dino_img
self.rect = self.image.get_rect()
self.rect.x = SCREEN_WIDTH + random.randint(0, 100)
self.rect.y = random.randint(50, SCREEN_HEIGHT - 50)
self.speed = random.randint(3, 7)
def update(self):
self.rect.x -= self.speed
if self.rect.right < 0:
self.kill()
class Cloud(pygame.sprite.Sprite):
"""Clouds for background effect."""
def __init__(self):
super().__init__()
self.image = cloud_img
self.rect = self.image.get_rect()
self.rect.x = SCREEN_WIDTH + random.randint(0, 300)
self.rect.y = random.randint(0, SCREEN_HEIGHT // 2)
self.speed = random.randint(1, 3)
def update(self):
self.rect.x -= self.speed
if self.rect.right < 0:
self.kill()
def main():
# Sprite groups
all_sprites = pygame.sprite.Group()
dinos = pygame.sprite.Group()
clouds = pygame.sprite.Group()
# Create player plane
plane = Plane()
all_sprites.add(plane)
# Game variables
ADDENEMY = pygame.USEREVENT + 1
pygame.time.set_timer(ADDENEMY, 1500) # Spawn a dinosaur every 1.5 seconds
ADDCLOUD = pygame.USEREVENT + 2
pygame.time.set_timer(ADDCLOUD, 2000) # Spawn a cloud every 2 seconds
score = 0
start_ticks = pygame.time.get_ticks() # Starter tick
running = True
while running:
clock.tick(60) # Limit to 60 FPS
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Add a new dinosaur
elif event.type == ADDENEMY:
dino = Dinosaur()
all_sprites.add(dino)
dinos.add(dino)
# Add a new cloud
elif event.type == ADDCLOUD:
cloud = Cloud()
all_sprites.add(cloud)
clouds.add(cloud)
# Update sprites
all_sprites.update()
# Check for collisions
if pygame.sprite.spritecollideany(plane, dinos):
draw_text("Game Over!", font, BLACK, screen, SCREEN_WIDTH//2 - 80, SCREEN_HEIGHT//2)
pygame.display.flip()
pygame.time.delay(2000)
running = False
continue
# Clear the screen
screen.fill(SKY_BLUE)
# Draw all sprites
all_sprites.draw(screen)
# Calculate score
seconds = (pygame.time.get_ticks() - start_ticks) // 1000
draw_text(f"Time Survived: {seconds} s", font, BLACK, screen, 10, 10)
# Update the display
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
```
---
### **Instructions to Run the Game**
1. **Save Images:**
You'll need three images for the plane, dinosaur, and cloud. You can use any images you like, but for convenience, you can download these sample images:
- [Plane Image](https://example.com/plane.png)
- [Dinosaur Image](https://example.com/dino.png)
- [Cloud Image](https://example.com/cloud.png)
Save these images in the same directory as your Python script and name them `plane.png`, `dino.png`, and `cloud.png` respectively.
2. **Run the Script:**
Navigate to the directory containing your script and images, then run:
```bash
python your_script_name.py
```
3. **Gameplay Controls:**
- **Up Arrow Key:** Move the plane up.
- **Down Arrow Key:** Move the plane down.
4. **Objective:**
- Avoid colliding with the flying dinosaurs that come from the right.
- Clouds are just for visual effect and do not affect the gameplay.
- The game displays how long you've survived in seconds.
---
### **Understanding the Code**
- **Classes:**
- `Plane`: Represents the player's plane, handles movement.
- `Dinosaur`: Represents the flying dinosaurs, moves them to the left.
- `Cloud`: Represents clouds for background effect.
- **Game Loop:**
- Handles events like quitting the game and spawning new dinosaurs and clouds.
- Updates all sprites every frame.
- Checks for collisions between the plane and dinosaurs.
- Renders everything on the screen.
- **Event Timers:**
- `ADDENEMY`: Triggers the addition of a new dinosaur every 1.5 seconds.
- `ADDCLOUD`: Triggers the addition of a new cloud every 2 seconds.
---
### **Customization**
Feel free to customize the game to your liking:
- **Adjust Difficulty:**
- Change the spawn rates by modifying the timers.
- Increase the speed range of dinosaurs.
- **Add Sounds:**
- You can add background music and sound effects using `pygame.mixer`.
- **Enhance Graphics:**
- Use different images or animations for sprites.
- Add a scrolling background.
---
### **Troubleshooting**
- **Module Not Found Error for Pygame:**
- Ensure Pygame is installed correctly. Run `pip install pygame`.
- **Images Not Found:**
- Make sure the image files are in the same directory as the script and are named correctly.
- **Game Window Not Responding:**
- Don't click excessively outside the game window; focus remains within the game. If it freezes, try running the script again.
---
Enjoy your game! If you have any questions or need further assistance, feel free to ask.