import pygame
import random
# Initialize Pygame
pygame.init()
# --- Game Settings ---
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30 # Size of each block
GRID_WIDTH = SCREEN_WIDTH // BLOCK_SIZE
GRID_HEIGHT = SCREEN_HEIGHT // BLOCK_SIZE
FPS = 60
TITLE = "Pycraft"
# --- Colors ---
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (100, 100, 100)
GREEN = (0, 200, 0)
BROWN = (150, 75, 0)
BLUE = (0, 0, 255)
LIGHT_BLUE = (100, 100, 255)
# --- Fonts ---
FONT_SMALL = pygame.font.Font(None, 30)
FONT_MEDIUM = pygame.font.Font(None, 50)
FONT_LARGE = pygame.font.Font(None, 70)
# --- Game Variables ---
game_state = "MENU" # MENU, PLAYING, PAUSED, GAME_OVER
score = 0
inventory = {"grass": 10, "stone": 5, "dirt": 15} # Simple inventory
selected_block_type = "grass" # Block type to place
# --- Create Window ---
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption(TITLE)
clock = pygame.time.Clock()
# --- World Generation ---
world = [[None for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
def generate_world():
global world
world = [[None for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
for y in range(GRID_HEIGHT):
for x in range(GRID_WIDTH):
if y > GRID_HEIGHT // 2:
if random.randint(0, 4) == 0: # Add some variation
world[y][x] = "stone"
else:
world[y][x] = "dirt"
elif y == GRID_HEIGHT // 2:
world[y][x] = "grass"
else:
world[y][x] = None # Air
generate_world() # Initial world generation
# --- Functions ---
def draw_block(surface, block_type, x, y):
block_rect = pygame.Rect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)
if block_type == "grass":
pygame.draw.rect(surface, GREEN, block_rect)
pygame.draw.rect(surface, BROWN, block_rect, 2) # Brown border
elif block_type == "stone":
pygame.draw.rect(surface, GRAY, block_rect)
elif block_type == "dirt":
pygame.draw.rect(surface, BROWN, block_rect)
elif block_type == "water":
pygame.draw.rect(surface, LIGHT_BLUE, block_rect)
pygame.draw.rect(surface, BLUE, block_rect, 2) # Darker blue border
def draw_grid(surface):
for x in range(0, SCREEN_WIDTH, BLOCK_SIZE):
pygame.draw.line(surface, BLACK, (x, 0), (x, SCREEN_HEIGHT))
for y in range(0, SCREEN_HEIGHT, BLOCK_SIZE):
pygame.draw.line(surface, BLACK, (0, y), (SCREEN_WIDTH, y))
def draw_world(surface):
for y in range(GRID_HEIGHT):
for x in range(GRID_WIDTH):
block_type = world[y][x]
if block_type:
draw_block(surface, block_type, x, y)
def draw_menu():
screen.fill(BLUE) # Menu background color
title_text = FONT_LARGE.render(TITLE, True, WHITE)
start_text = FONT_MEDIUM.render("Press SPACE to Start", True, WHITE)
controls_text = FONT_SMALL.render("Controls: WASD to Move, Mouse to Break/Place, 1-3 to Select Block", True, WHITE)
title_rect = title_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 3))
start_rect = start_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
controls_rect = controls_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT * 3 // 4))
screen.blit(title_text, title_rect)
screen.blit(start_text, start_rect)
screen.blit(controls_text, controls_rect)
def draw_hud():
score_text = FONT_SMALL.render(f"Score: {score}", True, WHITE)
inventory_text = FONT_SMALL.render(f"Inv: Grass({inventory['grass']}), Stone({inventory['stone']}), Dirt({inventory['dirt']})", True, WHITE)
selected_block_text = FONT_SMALL.render(f"Selected: {selected_block_type}", True, WHITE)
screen.blit(score_text, (10, 10))
screen.blit(inventory_text, (10, 40))
screen.blit(selected_block_text, (10, 70))
def handle_input():
global game_state, score, selected_block_type
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if game_state == "MENU":
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
game_state = "PLAYING"
generate_world() # Regenerate world when starting a new game
score = 0 # Reset score
inventory = {"grass": 10, "stone": 5, "dirt": 15} # Reset inventory
elif game_state == "PLAYING":
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
game_state = "PAUSED"
if event.key == pygame.K_1:
selected_block_type = "grass"
if event.key == pygame.K_2:
selected_block_type = "stone"
if event.key == pygame.K_3:
selected_block_type = "dirt"
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = pygame.mouse.get_pos()
grid_x = mouse_x // BLOCK_SIZE
grid_y = mouse_y // BLOCK_SIZE
if event.button == 1: # Left click - break block
if world[grid_y][grid_x]:
block_broken = world[grid_y][grid_x]
world[grid_y][grid_x] = None # Remove block
score += 10
if block_broken in inventory:
inventory[block_broken] += 1 # Add broken block to inventory
else:
inventory[block_broken] = 1
elif event.button == 3: # Right click - place block
if not world[grid_y][grid_x] and inventory[selected_block_type] > 0: # Only place if air and have block
world[grid_y][grid_x] = selected_block_type
inventory[selected_block_type] -= 1
elif game_state == "PAUSED":
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
game_state = "PLAYING"
if event.key == pygame.K_q: # 'Q' to quit to menu from pause
game_state = "MENU"
# --- Game Loop ---
running = True
while running:
handle_input()
if game_state == "MENU":
draw_menu()
elif game_state == "PLAYING" or game_state == "PAUSED":
screen.fill(LIGHT_BLUE) # Sky color
draw_world(screen)
#draw_grid(screen) # Optional grid lines
if game_state == "PLAYING":
draw_hud()
elif game_state == "PAUSED":
pause_text = FONT_LARGE.render("PAUSED", True, WHITE)
pause_rect = pause_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
screen.blit(pause_text, pause_rect)
draw_hud() # Still show HUD when paused
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
Explanation:
-
Initialization:
pygame.init(): Initializes Pygame modules.
- Game settings are defined (screen size, block size, FPS, title).
- Colors and fonts are defined for later use.
- Game state variables are initialized (
game_state, score, inventory, selected_block_type).
- The display window is created using
pygame.display.set_mode().
- The game clock is set up for controlling FPS.
-
World Generation (generate_world()):
- Creates a 2D list called
world to represent the game world grid.
- Iterates through each cell in the grid (
y for rows, x for columns).
- Simple terrain generation:
- Upper half of the world is "air" (None).
- Middle row is "grass".
- Lower half is mostly "dirt" with some random "stone" blocks.
- This function is called at the start and when restarting the game.
-
Drawing Functions (draw_block, draw_grid, draw_world, draw_menu, draw_hud):
draw_block(surface, block_type, x, y):
- Draws a rectangle for a block at given grid coordinates
(x, y).
- Uses different colors based on
block_type (grass, stone, dirt).
- Adds a brown border to grass blocks for visual distinction.
draw_grid(surface): (Optional) Draws grid lines to visualize the block grid.
draw_world(surface):
- Iterates through the
world grid.
- If a block type is present in a cell (
world[y][x] is not None), it calls draw_block to draw it.
draw_menu():
- Fills the screen with blue (menu background).
- Renders title, "Start" text, and controls instructions using fonts.
- Blits (draws) the text surfaces onto the screen at centered positions.
draw_hud():
- Renders the
score, inventory content, and selected_block_type as text.
To Run the Code:
- Install Pygame: If you don't have it installed, run:
pip install pygame in your terminal or command prompt.
- Save the code: Save the code as a Python file (e.g.,
pycraft.py).
- Run from terminal: Navigate to the directory where you saved the file in your terminal and run:
python pycraft.py
Key Improvements and Further Ideas:
- More Block Types: Add more block types (water, wood, leaves, etc.) with different colors and properties.
- Better World Generation: Implement more sophisticated terrain generation algorithms (e.g., Perlin noise) for more interesting landscapes.
- Player Movement: Add a player character that can move around the world (currently you are just breaking/placing from a static view). You could implement WASD movement to scroll the world view or have a player entity.
- Inventory System: Enhance the inventory to be more visual and allow scrolling or more complex selection.
- Tools: Add tools (pickaxe, shovel, axe) that are needed to break certain block types more efficiently.
- Crafting: Implement a simple crafting system to create new items from collected resources.
- Enemies/Mobs: Add simple enemies or creatures to make the game more challenging.
- Sound Effects and Music: Add sound effects for breaking blocks, placing blocks, and background music to improve the atmosphere.
- Isometric Perspective: To make it look more like Minecraft, you would need to draw blocks in an isometric perspective (3D-like projection). This would involve more complex drawing calculations but would improve the visual style significantly. You could also use pre-rendered isometric block images.
- UI Improvements: Make the menu and HUD more visually appealing.
This code provides a basic foundation for a Minecraft-like game in Pygame. You can expand upon it by adding more features and complexity as you learn more about game development and Pygame!