Creating a simple version of "Coinbox Hero" using Pygame involves implementing three main features:
Coinbox: A block that the player can hit to collect coins.
Coin System: Keeping track of the coins collected by the player.
Jump Hit System: Allowing the player to jump and interact with the coinbox.
Below is a step-by-step guide along with the complete code to achieve this functionality.
Prerequisites
Python: Ensure you have Python installed. You can download it from python.org.
Pygame: Install Pygame using pip:
bash
pip install pygame
Project Structure
For simplicity, all the code will be in a single Python file. However, for larger projects, it's recommended to structure your code into multiple modules.
Complete Code
python
import pygame
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60
# Colors
WHITE = (255, 255, 255)
GRAY = (50, 50, 50)
YELLOW = (255, 255, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
# Fonts
FONT = pygame.font.SysFont('Arial', 24)
# Set up the display
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Coinbox Hero")
clock = pygame.time.Clock()
# Define Player properties
PLAYER_WIDTH = 50
PLAYER_HEIGHT = 60
PLAYER_COLOR = BLUE
PLAYER_SPEED = 5
PLAYER_JUMP_SPEED = 15
GRAVITY = 1
# Define Coinbox properties
COINBOX_WIDTH = 50
COINBOX_HEIGHT = 50
COINBOX_COLOR = GRAY
# Define Coin properties
COIN_RADIUS = 10
COIN_COLOR = YELLOW
COIN_FALL_SPEED = 5
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.width = PLAYER_WIDTH
self.height = PLAYER_HEIGHT
self.image = pygame.Surface((self.width, self.height))
self.image.fill(PLAYER_COLOR)
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
self.vel_y = 0
self.on_ground = False
self.coins = 0
def update(self, keys_pressed):
# Horizontal movement
if keys_pressed[pygame.K_LEFT]:
self.rect.x -= PLAYER_SPEED
if self.rect.x < 0:
self.rect.x = 0
if keys_pressed[pygame.K_RIGHT]:
self.rect.x += PLAYER_SPEED
if self.rect.x + self.width > SCREEN_WIDTH:
self.rect.x = SCREEN_WIDTH - self.width
# Apply gravity
if not self.on_ground:
self.vel_y += GRAVITY
self.rect.y += self.vel_y
# Check for collision with the ground
if self.rect.y + self.height >= SCREEN_HEIGHT - ground_height:
self.rect.y = SCREEN_HEIGHT - ground_height - self.height
self.on_ground = True
self.vel_y = 0
def jump(self):
if self.on_ground:
self.vel_y = -PLAYER_JUMP_SPEED
self.on_ground = False
class Coinbox(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.width = COINBOX_WIDTH
self.height = COINBOX_HEIGHT
self.image = pygame.Surface((self.width, self.height))
self.image.fill(COINBOX_COLOR)
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
self.hit = False
self.bounce = False
self.bounce_count = 0
def update(self):
if self.bounce:
self.rect.y -= 5
self.bounce_count +=1
if self.bounce_count >= 10:
self.bounce = False
self.bounce_count = 0
self.rect.y += 5
class Coin(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.radius = COIN_RADIUS
self.color = COIN_COLOR
self.image = pygame.Surface((self.radius*2, self.radius*2), pygame.SRCALPHA)
pygame.draw.circle(self.image, self.color, (self.radius, self.radius), self.radius)
self.rect = self.image.get_rect(center=(x, y))
self.vel_y = COIN_FALL_SPEED
def update(self):
self.rect.y += self.vel_y
# Remove the coin if it falls below the screen
if self.rect.y > SCREEN_HEIGHT - ground_height:
self.kill()
# Ground properties
ground_height = 50
# Create sprite groups
all_sprites = pygame.sprite.Group()
coinboxes = pygame.sprite.Group()
coins = pygame.sprite.Group()
# Create player
player = Player(100, SCREEN_HEIGHT - ground_height - PLAYER_HEIGHT)
all_sprites.add(player)
# Create a coinbox
coinbox = Coinbox(400, SCREEN_HEIGHT - ground_height - COINBOX_HEIGHT)
all_sprites.add(coinbox)
coinboxes.add(coinbox)
def draw_ground():
pygame.draw.rect(screen, BLACK, (0, SCREEN_HEIGHT - ground_height, SCREEN_WIDTH, ground_height))
def draw_coin_count():
text = FONT.render(f"Coins: {player.coins}", True, BLACK)
screen.blit(text, (10, 10))
def main():
running = True
while running:
clock.tick(FPS)
keys_pressed = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.jump()
# Update sprites
all_sprites.update(keys_pressed)
coins.update()
# Handle player collision with coinboxes
collided_coinboxes = pygame.sprite.spritecollide(player, coinboxes, False)
for cb in collided_coinboxes:
# Check if the player is hitting from below
if player.vel_y < 0 and player.rect.top <= cb.rect.bottom:
cb.bounce = True
# Spawn a coin
coin = Coin(cb.rect.centerx, cb.rect.top)
all_sprites.add(coin)
coins.add(coin)
# Handle collision between player and coins
collected_coins = pygame.sprite.spritecollide(player, coins, True, pygame.sprite.collide_circle)
player.coins += len(collected_coins)
# Clear the screen
screen.fill(WHITE)
# Draw ground
draw_ground()
# Draw all sprites
all_sprites.draw(screen)
coins.draw(screen)
# Update coinboxes (for bounce effect)
for cb in coinboxes:
cb.update()
# Draw coin count
draw_coin_count()
# Update the display
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Explanation of the Code
Initialization:
Pygame Initialization: Initializes all Pygame modules.
Screen Setup: Sets up the game window with defined width and height.
Colors and Fonts: Defines basic colors and the font used for displaying the coin count.
Player Class:
Attributes: Width, height, color, position, velocity, and coin count.
Movement: Handles left and right movement based on key presses and applies gravity.
Jumping: Allows the player to jump if they are on the ground.
Coinbox Class:
Represents the coin box that the player can hit.
When hit from below, it bounces to simulate hitting and spawns a coin.
Coin Class:
Represents the coin that appears when the coinbox is hit.
The coin falls down and disappears if it goes below the ground.
Ground:
A simple rectangle at the bottom of the screen represents the ground.
Sprite Groups:
Organizes different sprites for efficient updating and drawing.
Main Game Loop:
Event Handling: Handles quitting the game and the jump action.
Updating: Updates all sprites and checks for collisions.
Collision Detection:
Player and Coinbox: Detects if the player hits the coinbox from below to spawn a coin.
Player and Coins: Detects if the player collects a coin to increment the coin count.
Rendering: Clears the screen, draws the ground, all sprites, and the coin count, then updates the display.
Running the Game
Save the Code: Save the above code in a file named coinbox_hero.py.
Run the Game:
bash
python coinbox_hero.py
Controls:
Left Arrow (←): Move the player left.
Right Arrow (→): Move the player right.
Spacebar: Make the player jump and hit the coinbox.
Objective:
Jump and hit the coinbox from below to spawn coins.
Collect the falling coins to increase your coin count displayed at the top-left corner.
Enhancements and Extensions
This is a basic implementation. Here are some ideas to enhance the game:
Multiple Coinboxes: Add more coinboxes at different positions.
Animations: Add animations for the player and coinboxes.
Sound Effects: Play sounds when hitting the coinbox or collecting coins.
Levels and Scoring: Introduce multiple levels with increasing difficulty.
Obstacles and Enemies: Add obstacles or enemies to make the game more challenging.
Conclusion
This guide provides a foundational structure for creating a simple "Coinbox Hero" game using Pygame. By understanding the core components—player movement, collision detection, and sprite management—you can expand and build upon this to create more complex and engaging games.
Feel free to modify and enhance the code to suit your needs. Happy coding!