Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Pandas Panel.add()
Next article icon

Python Arcade - Adding Levels

Last Updated : 23 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to add different levels to our arcade games in Python.

Adding Levels

We can easily add multiple levels to our Arcade game by following the below steps:

  • Create a new variable to store the current level.
self.level = 1
  • Load the sprites you are going to use in the current level with the help of self.level variable. For this example, we are going to load 'Platform1' named sprites for level 1, 'Platform2' named sprite for level 2, and so on.  For this, we can load the platforms using the below code.
platform = arcade.Sprite(f"Platform{self.level}.png", 1)
  • If the player crosses the right side of the screen then we are going to increase the value of self.level variable to go to the next level.
 if self.player_sprite.center_x>690:      self.level += 1

Functions Used:

  • Camera(): The Camera class is used for controlling the visible viewport.

Syntax: arcade.Camera( width , height, window)

Parameters:

  • width: width of the viewport
  • height: height of the viewport
  • window: Window to associate with this camera
  • Scene(): A class that represents a scene object.

Syntax: arcade.Scene(sprite_lists , name_mapping)

Parameters:

  • sprite_lists: A list of SpriteList objects
  • name_mapping: A dictionary of SpriteList objects
  • PhysicsEnginePlatformer(): Simplistic physics engine for use in a platformer.

Syntax: arcade.PhysicsEnginePlatformer( player_sprite , platforms, gravity, ladders)

Parameters:

  • player_sprite: sprite of the player
  • platforms: The sprites it can’t move through
  • gravity: Downward acceleration per frame
  • ladders: Ladders the user can climb on

Sprites Used:

In the below example, we are going to create a MainGame() class. Inside this class first, we are going to initialize some variables for velocity, camera, level, and player's sprite then we will create 6 functions inside this class.

  • on_draw(): Inside this function, we will use our camera and draw the scene.
  • setup(): In this function, we will initialize our camera and scene object then we will load our player and platform's sprites. After that, we will call the  PhysicsEnginePlatformer() function.
  • on_update(): In this function, we will update the x coordinates of the player's sprite, camera, and physics engine. We will also change our level in this function.
  • on_key_press() and on_key_release(): In this function, we will change the value of the velocity variable according to the keyboard key that is pressed or released.
  • camera_move(): In this function, we will move our camera according to our player's current position.

Below is the implementation:

Python3
# Importing arcade module import arcade  # Creating MainGame class class MainGame(arcade.Window):     def __init__(self):         super().__init__(600, 600,                          title = "Player Movement")          # Initializing a variable to store         # the velocity of the player         self.vel_x = 0          # Creating variable for Camera         self.camera = None          # Creating variable to store current level         self.level = 1          # Creating scene object         self.scene = None          # Creating variable to store player sprite         self.player = None          # Creating variable for our game engine         self.physics_engine = None      # Creating on_draw() function to draw on the screen     def on_draw(self):         arcade.start_render()          # Using the camera         self.camera.use()                  # Drawing our scene         self.scene.draw()      def setup(self):          # Initialize Scene object         self.scene = arcade.Scene()                  # Using Camera() function         self.camera = arcade.Camera(600, 600)          # Creating different sprite lists         self.scene.add_sprite_list("Player")         self.scene.add_sprite_list("Platforms",                                    use_spatial_hash=True)          # Adding player sprite         self.player_sprite = arcade.Sprite("Player.png", 1)          # Adding coordinates for the center of the sprite         self.player_sprite.center_x = 64         self.player_sprite.center_y = 600          # Adding Sprite in our scene         self.scene.add_sprite("Player", self.player_sprite)          # Adding platform sprite according to level         platform = arcade.Sprite(f"Platform{self.level}.png", 1)                  # Adding coordinates for the center of the platform         platform.center_x = 300         platform.center_y = 32         self.scene.add_sprite("Platforms", platform)          # Creating Physics engine         self.physics_engine = arcade.PhysicsEnginePlatformer(             self.player_sprite, self.scene.get_sprite_list("Platforms"), 0.5         )      # Creating on_update function to     # update the x coordinate     def on_update(self, delta_time):          # Changing x coordinate of player         self.player_sprite.center_x += self.vel_x * delta_time                  # Updating the physics engine to move the player         self.physics_engine.update()          # Calling the camera_move function         self.camera_move()          # Changing level if player crosses the right         # end of screen         if self.player_sprite.center_x > 690:             self.level += 1             self.setup()      # Creating function to change the velocity     # when button is pressed     def on_key_press(self, symbol, modifier):          # Checking the button pressed         # and changing the value of velocity         if symbol == arcade.key.LEFT:             self.vel_x = -300         elif symbol == arcade.key.RIGHT:             self.vel_x = 300      # Creating function to change the velocity     # when button is released     def on_key_release(self, symbol, modifier):          # Checking the button released         # and changing the value of velocity         if symbol == arcade.key.LEFT:             self.vel_x = 0         elif symbol == arcade.key.RIGHT:             self.vel_x = 0      def camera_move(self):                # Getting the x coordinate for the center of camera         screen_x = self.player_sprite.center_x - \             (self.camera.viewport_width / 2)                  # Getting the y coordinate for the center of camera         screen_y = self.player_sprite.center_y - \             (self.camera.viewport_height / 2)          # Moving the camera         self.camera.move_to([screen_x, screen_y])   # Calling MainGame class game = MainGame() game.setup() arcade.run() 

Output:


Next Article
Python | Pandas Panel.add()

I

imranalam21510
Improve
Article Tags :
  • Python
  • Python-Arcade
Practice Tags :
  • python

Similar Reads

  • Iterate over a list in Python
    Python provides several ways to iterate over list. The simplest and the most common way to iterate over a list is to use a for loop. This method allows us to access each element in the list directly. Example: Print all elements in the list one by one using for loop. [GFGTABS] Python a = [1, 3, 5, 7,
    3 min read
  • Python | Pandas Panel.add()
    In Pandas, Panel is a very important container for three-dimensional data. The names for the 3 axes are intended to give some semantic meaning to describing operations involving panel data and, in particular, econometric analysis of panel data. In Pandas Panel.add() function is used for element-wise
    2 min read
  • Python | Pandas MultiIndex.nlevels
    Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas MultiIndex.nlevels attribute returns the integer number of levels in the MultiI
    2 min read
  • Extending a list in Python
    In Python, a list is one of the most widely used data structures for storing multiple items in a single variable. Often, we need to extend a list by adding one or more elements, either from another list or other iterable objects. Python provides several ways to achieve this. In this article, we will
    2 min read
  • Python __add__() magic method
    Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator "+" in Python. Python __add__() Syntax Syntax: obj1.__add__(self, obj2) obj1: First object to add in the second object.obj2
    1 min read
  • Python3 Intermediate Level Topics
    After going through the basics of python, you would be interested to know more about further and bit more advance topics of the Python3 programming language. This article covers them. Please remember that Python completely works on indentation and it is advised to practice it a bit by running some p
    4 min read
  • Namedtuple in Python
    Python supports a type of container dictionary called "namedtuple()" present in the module "collections". In this article, we are going to see how to Create a NameTuple and operations on NamedTuple. What is NamedTuple in Python?In Python, NamedTuple is present inside the collections module. It provi
    8 min read
  • Python - Change List Item
    Lists in Python are mutable meaning their items can be changed after the list is created. Modifying elements in a list is a common task, whether we're replacing an item at a specific index, updating multiple items at once, or using conditions to modify certain elements. This article explores the dif
    3 min read
  • Python Nested Dictionary
    A Dictionary in Python works similarly to the Dictionary in the real world. The keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key values can be repeated and be of any type. What is Python in Nested Dictionary? Nesting Dictionary means
    3 min read
  • Declaring an Array in Python
    An array is a container used to store the same type of elements such as integer, float, and character type. An Array is one of the most important parts of data structures. In arrays, elements are stored in a contiguous location in a memory. We can access the array elements by indexing from 0 to (siz
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences