Platformer Template#
Quickly get started creating your own platformer!

About This Template#
This is a template to get you started coding a side-scrolling platformer as quickly as possible. I recommend the following steps:
Create a folder to hold the code. Copy this example to that folder, and call it
main.py
.Make sure the example code runs fine.
Copy the tile images you want to use to a subdirectory of the folder that holds your code.
Create a very simple Tiled Map using the Tiled Map Editor. I suggest just creating a floor and nothing else. For more detail on how to create a tiled map, see Step 9 - Use Tiled Map Editor.
Save the file to the same directory as your source code. If you create a separate tileset, also save it to the same directory as your code.
Update the code to load your file instead of the map.
Test and make sure it works.
Now that you are sure things work, make your own platformer!
Warning
Watch the directories!
One of the most frequent mistakes is to save maps and tile sets to a directory that isn’t the same directory as your code. Or to not have the tile images in that folder. If everything isn’t in the same folder (or a subfolder of that) it is hard to package it up later.
For more detailed instructions, see the tutorial Simple Platformer.
Source Code#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | """
Platformer Template
"""
import arcade
# --- Constants
SCREEN_TITLE = "Platformer"
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 650
# Constants used to scale our sprites from their original size
CHARACTER_SCALING = 1
TILE_SCALING = 0.5
COIN_SCALING = 0.5
SPRITE_PIXEL_SIZE = 128
GRID_PIXEL_SIZE = SPRITE_PIXEL_SIZE * TILE_SCALING
# Movement speed of player, in pixels per frame
PLAYER_MOVEMENT_SPEED = 10
GRAVITY = 1
PLAYER_JUMP_SPEED = 20
class MyGame(arcade.Window):
"""
Main application class.
"""
def __init__(self):
# Call the parent class and set up the window
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT,
SCREEN_TITLE, resizable=True)
# Our TileMap Object
self.tile_map = None
# Our Scene Object
self.scene = None
# Separate variable that holds the player sprite
self.player_sprite = None
# Our physics engine
self.physics_engine = None
# A Camera that can be used for scrolling the screen
self.camera_sprites = None
# A non-scrolling camera that can be used to draw GUI elements
self.camera_gui = None
# Keep track of the score
self.score = 0
# What key is pressed down?
self.left_key_down = False
self.right_key_down = False
def setup(self):
"""Set up the game here. Call this function to restart the game."""
# Setup the Cameras
self.camera_sprites = arcade.Camera(self.width, self.height)
self.camera_gui = arcade.Camera(self.width, self.height)
# Name of map file to load
map_name = ":resources:tiled_maps/map.json"
# Layer specific options are defined based on Layer names in a dictionary
# Doing this will make the SpriteList for the platforms layer
# use spatial hashing for detection.
layer_options = {
"Platforms": {
"use_spatial_hash": True,
},
}
# Read in the tiled map
self.tile_map = arcade.load_tilemap(map_name, TILE_SCALING, layer_options)
# Initialize Scene with our TileMap, this will automatically add all layers
# from the map as SpriteLists in the scene in the proper order.
self.scene = arcade.Scene.from_tilemap(self.tile_map)
# Set the background color
if self.tile_map.background_color:
arcade.set_background_color(self.tile_map.background_color)
# Keep track of the score
self.score = 0
# Set up the player, specifically placing it at these coordinates.
src = ":resources:images/animated_characters/female_adventurer/femaleAdventurer_idle.png"
self.player_sprite = arcade.Sprite(src, CHARACTER_SCALING)
self.player_sprite.center_x = 128
self.player_sprite.center_y = 128
self.scene.add_sprite("Player", self.player_sprite)
# --- Other stuff
# Create the 'physics engine'
self.physics_engine = arcade.PhysicsEnginePlatformer(
self.player_sprite, gravity_constant=GRAVITY, walls=self.scene["Platforms"]
)
def on_draw(self):
"""Render the screen."""
# Clear the screen to the background color
self.clear()
# Activate the game camera
self.camera_sprites.use()
# Draw our Scene
# Note, if you a want pixelated look, add pixelated=True to the parameters
self.scene.draw()
# Activate the GUI camera before drawing GUI elements
self.camera_gui.use()
# Draw our score on the screen, scrolling it with the viewport
score_text = f"Score: {self.score}"
arcade.draw_text(score_text,
start_x=10,
start_y=10,
color=arcade.csscolor.WHITE,
font_size=18)
def update_player_speed(self):
# Calculate speed based on the keys pressed
self.player_sprite.change_x = 0
if self.left_key_down and not self.right_key_down:
self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED
elif self.right_key_down and not self.left_key_down:
self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED
def on_key_press(self, key, modifiers):
"""Called whenever a key is pressed."""
# Jump
if key == arcade.key.UP or key == arcade.key.W:
if self.physics_engine.can_jump():
self.player_sprite.change_y = PLAYER_JUMP_SPEED
# Left
elif key == arcade.key.LEFT or key == arcade.key.A:
self.left_key_down = True
self.update_player_speed()
# Right
elif key == arcade.key.RIGHT or key == arcade.key.D:
self.right_key_down = True
self.update_player_speed()
def on_key_release(self, key, modifiers):
"""Called when the user releases a key."""
if key == arcade.key.LEFT or key == arcade.key.A:
self.left_key_down = False
self.update_player_speed()
elif key == arcade.key.RIGHT or key == arcade.key.D:
self.right_key_down = False
self.update_player_speed()
def center_camera_to_player(self):
# Find where player is, then calculate lower left corner from that
screen_center_x = self.player_sprite.center_x - (self.camera_sprites.viewport_width / 2)
screen_center_y = self.player_sprite.center_y - (self.camera_sprites.viewport_height / 2)
# Set some limits on how far we scroll
if screen_center_x < 0:
screen_center_x = 0
if screen_center_y < 0:
screen_center_y = 0
# Here's our center, move to it
player_centered = screen_center_x, screen_center_y
self.camera_sprites.move_to(player_centered)
def on_update(self, delta_time):
"""Movement and game logic"""
# Move the player with the physics engine
self.physics_engine.update()
# See if we hit any coins
coin_hit_list = arcade.check_for_collision_with_list(
self.player_sprite, self.scene["Coins"]
)
# Loop through each coin we hit (if any) and remove it
for coin in coin_hit_list:
# Remove the coin
coin.remove_from_sprite_lists()
# Add one to the score
self.score += 1
# Position the camera
self.center_camera_to_player()
def on_resize(self, width, height):
""" Resize window """
self.camera_sprites.resize(int(width), int(height))
self.camera_gui.resize(int(width), int(height))
def main():
"""Main function"""
window = MyGame()
window.setup()
arcade.run()
if __name__ == "__main__":
main()
|