Pygame
Author: i | 2025-04-24
pygame._sdl2.controller: pygame module to work with controllers pygame._sdl2.touch pygame module to work with touch input pygame._sdl2.video Experimental pygame module for porting
GitHub - pygame/pygame: pygame (the library) is a
One error that you might encounter when working with Python is:ModuleNotFoundError: No module named 'pygame'This error occurs when Python can’t find the pygame module in your current Python environment.This tutorial shows examples that cause this error and how to fix it.How to reproduce the errorSuppose you want to use the pygame module to develop a video game using Python.You import the pygame module in your code as follows:import pygamepygame.init()But you get the following error when running the code:Traceback (most recent call last): File "main.py", line 1, in import pygameModuleNotFoundError: No module named 'pygame'This error occurs because the pygame module is not a built-in Python module, so you need to install it before using it.To see if you have the pygame module installed, you can run the pip show pygame command from the terminal as follows:$ pip3 show pygame WARNING: Package(s) not found: pygameIf you get the warning as shown above, then you need to install the pygame module.How to fix this errorTo resolve this error, you need to install the pygame library using pip as shown below:pip install pygame# For pip3:pip3 install pygameOnce the module is installed, you should be able to run the code that imports pygame without receiving the error.Install commands for other environmentsThe install command might differ depending on what environment you used to run the Python code.Here’s a list of common install commands in popular Python environments to install the pygame module:# if you don't have pip in your PATH:python -m pip install pygamepython3 -m pip install pygame# Windowspy -m pip install pygame# apt-get mirror for Ubuntu/Debian/Mintsudo apt-get install python3-pygame# yum mirror for CentOS/Fedora/Red hatsudo yum install python3-pygameOnce the module is installed, you should be able to run the code without receiving this error.Other common causes for this errorIf you still see the error even after installing the module, it means that the pygame module can’t be found in your Python environment.There are several reasons why this error can happen:You may have multiple versions of Python installed on your system, and you are using a different version of Python than the one where pygame is installed.You might have pygame installed in a virtual environment, and you are not activating the virtual environment before running your code.Your IDE uses a different version of Python from the one that has pygameLet’s see how to fix these errors in practice.1. You have multiple versions of PythonIf you have multiple versions of Python installed on your system, you need to make sure that you are using the specific version where the pygame module is available.You can test this by running the which -a python or which -a python3 command from the terminal:$ which -a python3/opt/homebrew/bin/python3/usr/bin/python3In the example above, there are two versions of Python installed on /opt/homebrew/bin/python3 and /usr/bin/python3.Suppose you run the following steps in your project:Install pygame with pip using /usr/bin/ Python versionInstall Python using Homebrew, you have Python in /opt/homebrew/Then you run import pygame in your codeThe steps above will cause the error because pygame is installed in /usr/bin/, and your code is probably executed using Python from /opt/homebrew/ path.To solve this error, you need to run the pip install pygame command again so that pygame is installed and accessible by the active Python version.2. Python virtual environment is activeAnother scenario that could cause this error is you may have pygame installed in a virtual environment.Python venv package allows you to create a virtual environment where you can install different versions of packages required by your project.If you are installing pygame inside a virtual environment, then the module won’t be accessible outside of that environment.You can see if a virtual environment is active or not by looking at your prompt in the terminal.When a virtual environment is active, the name of that environment will be shown inside parentheses as shown below:In the picture above, the name of the virtual environment (demoenv) appears, indicating that the virtual environment is currently active.If you run pip install while the virtual environment is active, then the package is installed only for that environmentLikewise, any package installed outside of that virtual environment won’t be accessible from the virtual environment. The solution is to run the pip install command on the environment you want to use.If you want to install pygame globally, then turn off the virtual environment by running the deactivate command before running the pip install command.3. IDE using a different Python versionFinally, the IDE from where you run your Python code may use a different Python version when you have multiple versions installed.For example, you can check the Python interpreter used in VSCode by opening the command palette (CTRL + Shift + P for Windows and ⌘ + Shift + P for Mac) then run the Python: Select Interpreter command.You should see all available Python versions listed as follows:You need to use the same version where you installed pygame so that the module can be found when you run the code from VSCode.Once done, you should be able to import pygame into your code.ConclusionIn summary, the ModuleNotFoundError: No module named 'pygame' error occurs when the pygame library is not available in your Python environment. To fix this error, you need to install pygame using pip.If you already have the module installed, make sure you are using the correct version of Python, check if the virtual environment is active if you have one, and check for the Python version used by your IDE.By following these steps, you should be able to import the pygame module in your code successfully.I hope this tutorial is helpful. Until next time! 👋GitHub - pygame/pygame: pygame (the library) is a Free and
Possible_moves def valid_moves(self): tile_moves = [] moves = self._possible_moves() for move in moves: tile_pos = (self.x + move[0], self.y + move[-1]) if tile_pos[0] 7 or tile_pos[-1] 7: pass else: tile = self.board.get_tile_from_pos(tile_pos) if tile.occupying_piece == None: tile_moves.append(tile) return tile_moves def valid_jumps(self): tile_jumps = [] moves = self._possible_moves() for move in moves: tile_pos = (self.x + move[0], self.y + move[-1]) if tile_pos[0] 7 or tile_pos[-1] 7: pass else: tile = self.board.get_tile_from_pos(tile_pos) if self.board.turn == self.color: if tile.occupying_piece != None and tile.occupying_piece.color != self.color: next_pos = (tile_pos[0] + move[0], tile_pos[-1] + move[-1]) next_tile = self.board.get_tile_from_pos(next_pos) if next_pos[0] 7 or next_pos[-1] 7: pass else: if next_tile.occupying_piece == None: tile_jumps.append((next_tile, tile)) return tile_jumpsAnd now the game is done! You can try the game by running the Main.py on your terminal:$ python Main.pyHere are some of the game snapshots:Starting the game:Pawn's move:Pawn's Jump:Pawn Promotion:King's moves:King's Jump:ConclusionIn this tutorial, we've explored how to implement a checkers game in Python using the Pygame library. We've covered how to create the game board, pieces, and their movements, as well as the basic rules of the game. Playing checkers is an enjoyable way to pass the time and test your strategy and critical thinking skills. We hope this article has been helpful in understanding the basics of checkers programming in Python. See you on the next one!We also have a chess game tutorial, if you want to build one!Get the complete code here.Here is a list of other pygame tutorials:How to Make a Chess Game with Pygame in PythonHow to Build a Tic Tac Toe Game in PythonHow to Make a Tetris Game using PyGame in PythonHow to Create a Hangman Game using PyGame in PythonHow to Make a Drawing Program in PythonHow to Make a Planet Simulator with PyGame in PythonHappy coding ♥Want to code smarter? Our Python Code Assistant is waiting to help you. Try it now! View Full Code Analyze My CodeRead Also Comment panel. pygame._sdl2.controller: pygame module to work with controllers pygame._sdl2.touch pygame module to work with touch input pygame._sdl2.video Experimental pygame module for porting Pygame Download Tutorial – How to in 3 Steps. Pygame Transform Tutorial – Complete Guide. Categories Pygame. Pygame Clock Tutorial – Complete Guide. Pygamepygame-community/pygame-ce: pygame - GitHub
Of the game loop.Below is a short video, show casing what we’ve accomplished so far.If you have any trouble with some of the code above, I recommend you try running it piece by piece and experimenting with it on your own. Leave out certain lines to discover their effect on the game. Game development in Pygame is a skill learnt best when you’re the one tinkering with the Platformer (or any game) code yourself.Click on the button below to head over to the next Part in this series of Game Development with Pygame Platformer. The complete code for this article is also available in Part 2.Related Articles:Pygame – The full tutorialPygame projects with source codeAudio and Sound – Pygame MixerPygame RPG Tutorial SeriesInterested in taking things to the next level? Check out this article on Game Development Books to become a real Game Developer!This marks the end of the Pygame Platformer Game Development article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article material can be asked in the comments section below. This article covers the game development of a Platformer game in Pygame.Welcome to the Pygame Platformer Game Development! In this section, we’ll be building a 2D Platformer game using the Python game library, Pygame. Fair warning to all our readers, this article is primarily targeted towards people already somewhat familiar with Pygame.We will only be skimming over basic pygame concepts, reserving most of our time for the more advanced concepts. If you’re quick and intuitive you’ll probably be able to follow along, but I still recommend you read our Pygame Tutorial (aimed towards absolute beginners) first.This article will cover some advanced concepts (listed below). Due to the sheer size of the code (300+ lines) and the explanation required, we’ll be splitting the game across several articles, each tackling a certain number of problems and features.About the GameA sneak peek at the final version game we’ll be buildingChances are you’ve played one of these platformer games before. It’s a simple game where you keep moving your character upwards by jumping on the available platforms. If you miss a platform and fall to your doom, it’s game over. You earn a point for every platform you cross. There’s no limit to the game, ending only when you fall and die (or get bored and quit).Included ConceptsBelow are all the Pygame game programming concepts included in this game. Don’t worry, all of them will be explained alongside the source code. As mentioned earlier, these will be split across several articles due to size limitations.Collision DetectionPlayer movement (realistic sideways movement)Jump mechanicsGravity and FrictionRandom Level GenerationWarpable screen movementScrolling the screen (creating an infinite height)Creating a Score counter“Game Over” MechanicRandom Platform movementPart 1 – Setting the FoundationIn this article we’ll set the foundation for our game. Creating our player sprite and setting up some movement controls.InitializationGitHub - hghpublic/pygame-pygame: pygame (the library) is a
And Constantsimport pygamefrom pygame.locals import *pygame.init()vec = pygame.math.Vector2 # 2 for two dimensionalHEIGHT = 450WIDTH = 400ACC = 0.5FRIC = -0.12FPS = 60FramePerSec = pygame.time.Clock()displaysurface = pygame.display.set_mode((WIDTH, HEIGHT))pygame.display.set_caption("Game")The above code is all pre-game related. You can see us importing the pygame module(s), calling pygame.init() to initialize pygame, setting up several constants such as screen height and width etc. We also set up a clock in pygame, which we’ll use later to control the Frames displayed per second.Next we’ve set up the display screen using the WIDTH and HEIGHT variables and given the display window the name “Game”.You’ll have noticed the constants ACC and FRIC and the variable called vec. These, we’ll be using later on in the article to create realistic movement and implement gravity.Above is an image of our current progress. A 450 by 500 pixel display screen. We have no objects made, so it’s a blank screen with the default black color.Player and Platform ClassesIn this game, we’re going to have two different types of entities. The player who we will be controlling and the platforms on which we’ll be jumping. We’re going to create two different classes for each one of these entities.If you haven’t been using classes until now, this is a good time to start. This approach allow us to easily duplicate and access the objects we’re going to be creating. You’ll realize this once we begin creating many platforms. For now we’re just making one.class Player(pygame.sprite.Sprite): def __init__(self): super().__init__() self.surf = pygame.Surface((30, 30)) self.surf.fill((128,255,40)) self.rect = self.surf.get_rect(center = (10, 420))class platform(pygame.sprite.Sprite): def __init__(self): super().__init__() self.surf = pygame.Surface((WIDTH, 20)) self.surf.fill((255,0,0)) self.rect = self.surf.get_rect(center = (WIDTH/2, HEIGHT - 10))PT1 = platform()P1 = Player()Most of this should only require basic Pygame knowledge. We create surface objects for each class with a fixed size. We give each ofGitHub - pygame-community/pygame-ce: pygame - Community
Art_Gallery_problemThe Art Gallery Problem (AGP) is one of the classic problems in Computational Geometry.Many variants of these problems have already been studied.In this paper, we propose an algorithm to solve the art gallery problem in which guards are placed on the vertices of the polygon P i.e gallery.Problem StatementGuarding an art gallery with the minimum number of guards who can keep a check on the whole gallery.We have considered the layout of the art gallery be a simple polygon in which guards are to be placed on the vertices of the polygon .Let a set S of points is said to guard a polygon if, for every point p in the polygon, there is some q ∈ S such that the line joining p and q does not leave the polygon.IMPLEMENTATIONFirst we built a polygon and used a graphical user interface to show instructions on how we can use the tool.In the design part we also used prev and next buttons where users can navigate and visualize the implementation.We have used the following algorithms in this tool:• Ear Clipping Algorithm for Triangulation• M-coloring using backtracking (3-coloring)• Polygon VisibilityRun on WindowsDownload the Art Gallery setup.exe file from the dist folder and run it to install the Art Gallery Tool. Run the Art Gallery Tool by executing Art Gallery Pedagogical Tool.exe from desktop shortcut or the location chosen to install the program.Run on Mac OS, LinuxRequirementsPython Libraries (use pip to download and install these libraries)Pygame (pip3 install pygame or pip install pygame)EasyGui. pygame._sdl2.controller: pygame module to work with controllers pygame._sdl2.touch pygame module to work with touch input pygame._sdl2.video Experimental pygame module for porting Pygame Download Tutorial – How to in 3 Steps. Pygame Transform Tutorial – Complete Guide. Categories Pygame. Pygame Clock Tutorial – Complete Guide. PygameGUIs with pygame - pygame wiki
· 21 min read · Updated may 2023 · Game Development Kickstart your coding journey with our Python Code Assistant. An AI-powered assistant that's always ready to help. Don't miss out!Checkers is a classic two-player board game that has been enjoyed by people of all ages for generations. It is a strategy game that requires players to move their pieces across the board, capturing their opponent's pieces and ultimately trying to reach the other end of the board with one of their pieces to become a king.In this article, we will be making a Checkers game in Python. Our goal is to provide an overview of the game's codebase, breaking it down into several classes that work together to provide the game's functionality. We will cover the installation and setup process, the main class, the game class, the board class, the tile class, the piece class, the pawn class, and the king class. We also have a tutorial on making a chess game, make sure to check it out if you're interested!Our focus will be on explaining the code in a way that is easy to understand for new programmers. So, without further ado, let's get started!Table of Contents:Setup and InstallationThe Main classThe Game classThe Board classThe Tile classThe Piece classThe Pawn classThe King classSetup and InstallationBefore we can begin working on our game, we need to make sure we have all the necessary tools installed on our computer. The first thing we need to do is to make sure we have Python installed. You can download Python from the official website.Also, we need to install the Pygame library. Pygame is a set of Python modules that allow us to create games and multimedia applications. To install Pygame, open up the command prompt/terminal and type the following command:$ pip install pygameWe can now create the directory for our Checkers game. Open up your file explorer and navigate to the directory where you want to create your game, and create the "Checkers" folder.Inside the Checkers directory, we need to create several Python files. Namely "Main.py", "Game.py", "Board.py", "Tile.py", "Piece.py", "Pawn.py", and "King.py".Finally, we need to create a folder named "images" inside the Checkers directory. This folder will contain the images for our game pieces. Inside the folder, place the following image files: black-pawn.png, black-king.png, red-pawn.png, and red-king.png. You can access the pictures here.The structure of our game should look like this:The Main classThe Main class is the starting point of our game. It sets up the game window, initializes the game objects, and runs the game loop.First, we import the necessary modules and classes from the other files in our Checkers game. Then, we initialize Pygame with the pygame.init() function:# /*Comments
One error that you might encounter when working with Python is:ModuleNotFoundError: No module named 'pygame'This error occurs when Python can’t find the pygame module in your current Python environment.This tutorial shows examples that cause this error and how to fix it.How to reproduce the errorSuppose you want to use the pygame module to develop a video game using Python.You import the pygame module in your code as follows:import pygamepygame.init()But you get the following error when running the code:Traceback (most recent call last): File "main.py", line 1, in import pygameModuleNotFoundError: No module named 'pygame'This error occurs because the pygame module is not a built-in Python module, so you need to install it before using it.To see if you have the pygame module installed, you can run the pip show pygame command from the terminal as follows:$ pip3 show pygame WARNING: Package(s) not found: pygameIf you get the warning as shown above, then you need to install the pygame module.How to fix this errorTo resolve this error, you need to install the pygame library using pip as shown below:pip install pygame# For pip3:pip3 install pygameOnce the module is installed, you should be able to run the code that imports pygame without receiving the error.Install commands for other environmentsThe install command might differ depending on what environment you used to run the Python code.Here’s a list of common install commands in popular Python environments to install the pygame module:# if you don't have pip in your PATH:python -m pip install pygamepython3 -m pip install pygame# Windowspy -m pip install pygame# apt-get mirror for Ubuntu/Debian/Mintsudo apt-get install python3-pygame# yum mirror for CentOS/Fedora/Red hatsudo yum install python3-pygameOnce the module is installed, you should be able to run the code without receiving this error.Other common causes for this errorIf you still see the error even after installing the module, it means that the pygame module can’t be found in your Python environment.There are several reasons why this error can happen:You may have multiple versions of Python installed on your system, and you are using a different version of Python than the one where pygame is installed.You might have pygame installed in a virtual environment, and you are not activating the virtual environment before running your code.Your IDE uses a different version of Python from the one that has pygameLet’s see how to fix these errors in practice.1. You have multiple versions of PythonIf you have multiple versions of Python installed on your system, you need to make sure that you are using the specific version where the pygame module is available.You can test this by running the which -a python or which -a python3 command from the terminal:$ which -a python3/opt/homebrew/bin/python3/usr/bin/python3In the example above, there are two versions of Python installed on /opt/homebrew/bin/python3 and /usr/bin/python3.Suppose you run the following steps in your project:Install pygame with pip using /usr/bin/ Python versionInstall Python using Homebrew, you have Python in /opt/homebrew/Then you run import pygame in your codeThe steps above will cause the error because pygame is installed in
2025-04-19/usr/bin/, and your code is probably executed using Python from /opt/homebrew/ path.To solve this error, you need to run the pip install pygame command again so that pygame is installed and accessible by the active Python version.2. Python virtual environment is activeAnother scenario that could cause this error is you may have pygame installed in a virtual environment.Python venv package allows you to create a virtual environment where you can install different versions of packages required by your project.If you are installing pygame inside a virtual environment, then the module won’t be accessible outside of that environment.You can see if a virtual environment is active or not by looking at your prompt in the terminal.When a virtual environment is active, the name of that environment will be shown inside parentheses as shown below:In the picture above, the name of the virtual environment (demoenv) appears, indicating that the virtual environment is currently active.If you run pip install while the virtual environment is active, then the package is installed only for that environmentLikewise, any package installed outside of that virtual environment won’t be accessible from the virtual environment. The solution is to run the pip install command on the environment you want to use.If you want to install pygame globally, then turn off the virtual environment by running the deactivate command before running the pip install command.3. IDE using a different Python versionFinally, the IDE from where you run your Python code may use a different Python version when you have multiple versions installed.For example, you can check the Python interpreter used in VSCode by opening the command palette (CTRL + Shift + P for Windows and ⌘ + Shift + P for Mac) then run the Python: Select Interpreter command.You should see all available Python versions listed as follows:You need to use the same version where you installed pygame so that the module can be found when you run the code from VSCode.Once done, you should be able to import pygame into your code.ConclusionIn summary, the ModuleNotFoundError: No module named 'pygame' error occurs when the pygame library is not available in your Python environment. To fix this error, you need to install pygame using pip.If you already have the module installed, make sure you are using the correct version of Python, check if the virtual environment is active if you have one, and check for the Python version used by your IDE.By following these steps, you should be able to import the pygame module in your code successfully.I hope this tutorial is helpful. Until next time! 👋
2025-04-05Possible_moves def valid_moves(self): tile_moves = [] moves = self._possible_moves() for move in moves: tile_pos = (self.x + move[0], self.y + move[-1]) if tile_pos[0] 7 or tile_pos[-1] 7: pass else: tile = self.board.get_tile_from_pos(tile_pos) if tile.occupying_piece == None: tile_moves.append(tile) return tile_moves def valid_jumps(self): tile_jumps = [] moves = self._possible_moves() for move in moves: tile_pos = (self.x + move[0], self.y + move[-1]) if tile_pos[0] 7 or tile_pos[-1] 7: pass else: tile = self.board.get_tile_from_pos(tile_pos) if self.board.turn == self.color: if tile.occupying_piece != None and tile.occupying_piece.color != self.color: next_pos = (tile_pos[0] + move[0], tile_pos[-1] + move[-1]) next_tile = self.board.get_tile_from_pos(next_pos) if next_pos[0] 7 or next_pos[-1] 7: pass else: if next_tile.occupying_piece == None: tile_jumps.append((next_tile, tile)) return tile_jumpsAnd now the game is done! You can try the game by running the Main.py on your terminal:$ python Main.pyHere are some of the game snapshots:Starting the game:Pawn's move:Pawn's Jump:Pawn Promotion:King's moves:King's Jump:ConclusionIn this tutorial, we've explored how to implement a checkers game in Python using the Pygame library. We've covered how to create the game board, pieces, and their movements, as well as the basic rules of the game. Playing checkers is an enjoyable way to pass the time and test your strategy and critical thinking skills. We hope this article has been helpful in understanding the basics of checkers programming in Python. See you on the next one!We also have a chess game tutorial, if you want to build one!Get the complete code here.Here is a list of other pygame tutorials:How to Make a Chess Game with Pygame in PythonHow to Build a Tic Tac Toe Game in PythonHow to Make a Tetris Game using PyGame in PythonHow to Create a Hangman Game using PyGame in PythonHow to Make a Drawing Program in PythonHow to Make a Planet Simulator with PyGame in PythonHappy coding ♥Want to code smarter? Our Python Code Assistant is waiting to help you. Try it now! View Full Code Analyze My CodeRead Also Comment panel
2025-04-19Of the game loop.Below is a short video, show casing what we’ve accomplished so far.If you have any trouble with some of the code above, I recommend you try running it piece by piece and experimenting with it on your own. Leave out certain lines to discover their effect on the game. Game development in Pygame is a skill learnt best when you’re the one tinkering with the Platformer (or any game) code yourself.Click on the button below to head over to the next Part in this series of Game Development with Pygame Platformer. The complete code for this article is also available in Part 2.Related Articles:Pygame – The full tutorialPygame projects with source codeAudio and Sound – Pygame MixerPygame RPG Tutorial SeriesInterested in taking things to the next level? Check out this article on Game Development Books to become a real Game Developer!This marks the end of the Pygame Platformer Game Development article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article material can be asked in the comments section below.
2025-04-06This article covers the game development of a Platformer game in Pygame.Welcome to the Pygame Platformer Game Development! In this section, we’ll be building a 2D Platformer game using the Python game library, Pygame. Fair warning to all our readers, this article is primarily targeted towards people already somewhat familiar with Pygame.We will only be skimming over basic pygame concepts, reserving most of our time for the more advanced concepts. If you’re quick and intuitive you’ll probably be able to follow along, but I still recommend you read our Pygame Tutorial (aimed towards absolute beginners) first.This article will cover some advanced concepts (listed below). Due to the sheer size of the code (300+ lines) and the explanation required, we’ll be splitting the game across several articles, each tackling a certain number of problems and features.About the GameA sneak peek at the final version game we’ll be buildingChances are you’ve played one of these platformer games before. It’s a simple game where you keep moving your character upwards by jumping on the available platforms. If you miss a platform and fall to your doom, it’s game over. You earn a point for every platform you cross. There’s no limit to the game, ending only when you fall and die (or get bored and quit).Included ConceptsBelow are all the Pygame game programming concepts included in this game. Don’t worry, all of them will be explained alongside the source code. As mentioned earlier, these will be split across several articles due to size limitations.Collision DetectionPlayer movement (realistic sideways movement)Jump mechanicsGravity and FrictionRandom Level GenerationWarpable screen movementScrolling the screen (creating an infinite height)Creating a Score counter“Game Over” MechanicRandom Platform movementPart 1 – Setting the FoundationIn this article we’ll set the foundation for our game. Creating our player sprite and setting up some movement controls.Initialization
2025-04-11