Convert Figma logo to code with AI

pygame logopygame

🐍🎮 pygame (the library) is a Free and Open Source python programming language library for making multimedia applications like games built on top of the excellent SDL library. C, Python, Native, OpenGL.

7,683
3,440
7,683
480

Top Related Projects

10,902

Simple Directmedia Layer

24,437

A simple and easy-to-use library to enjoy videogames programming

17,941

Open source UI framework written in Python, running on Windows, Linux, macOS, Android and iOS

5,864

LÖVE is an awesome 2D game framework for Lua.

10,342

Simple and Fast Multimedia Library

93,104

Godot Engine – Multi-platform 2D and 3D game engine

Quick Overview

Pygame is a popular Python library for creating 2D games and multimedia applications. It provides a set of modules built on top of the SDL library, offering easy-to-use tools for graphics, sound, and input handling. Pygame is suitable for both beginners and experienced developers looking to create games or interactive applications in Python.

Pros

  • Easy to learn and use, especially for those already familiar with Python
  • Cross-platform compatibility (Windows, macOS, Linux)
  • Active community and extensive documentation
  • Suitable for both simple and complex 2D game development

Cons

  • Limited to 2D graphics (no built-in 3D support)
  • Performance may be slower compared to lower-level game engines
  • Less suitable for large-scale commercial game development
  • Some features may be outdated compared to more modern game development frameworks

Code Examples

  1. Creating a window and drawing a rectangle:
import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.draw.rect(screen, (255, 0, 0), (100, 100, 200, 100))
pygame.display.flip()
  1. Handling user input:
import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                print("Space key pressed!")

pygame.quit()
  1. Playing a sound:
import pygame

pygame.init()
pygame.mixer.init()
sound = pygame.mixer.Sound("example.wav")
sound.play()
pygame.time.wait(2000)  # Wait for 2 seconds

Getting Started

To get started with Pygame, follow these steps:

  1. Install Pygame using pip:

    pip install pygame
    
  2. Create a new Python file and import Pygame:

    import pygame
    
    pygame.init()
    screen = pygame.display.set_mode((800, 600))
    clock = pygame.time.Clock()
    
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        
        screen.fill((255, 255, 255))  # Fill screen with white
        pygame.display.flip()
        clock.tick(60)  # Limit to 60 FPS
    
    pygame.quit()
    

This basic template sets up a Pygame window and a game loop, providing a starting point for your game development.

Competitor Comparisons

10,902

Simple Directmedia Layer

Pros of SDL

  • Lower-level API providing more control and flexibility
  • Cross-platform support for multiple programming languages
  • Better performance for complex multimedia applications

Cons of SDL

  • Steeper learning curve due to lower-level nature
  • Requires more code to achieve basic functionality
  • Less Python-specific documentation and community support

Code Comparison

SDL (C):

SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow("SDL Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);

Pygame (Python):

import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Pygame Window")
screen.fill((255, 255, 255))
pygame.display.flip()

SDL provides a more low-level approach, offering greater control but requiring more code. Pygame, built on top of SDL, simplifies game development in Python with higher-level abstractions. SDL is suitable for cross-platform, performance-critical applications in various languages, while Pygame is ideal for rapid game prototyping and development in Python.

24,437

A simple and easy-to-use library to enjoy videogames programming

Pros of raylib

  • Cross-platform support for desktop, web, and mobile
  • Better performance and hardware acceleration
  • More comprehensive feature set for 3D graphics

Cons of raylib

  • Steeper learning curve, especially for beginners
  • Less Python-friendly (primarily C-based)
  • Smaller community and fewer learning resources

Code Comparison

raylib (C):

#include "raylib.h"

int main(void) {
    InitWindow(800, 450, "raylib example");
    while (!WindowShouldClose()) {
        BeginDrawing();
        ClearBackground(RAYWHITE);
        DrawText("Hello, raylib!", 190, 200, 20, LIGHTGRAY);
        EndDrawing();
    }
    CloseWindow();
    return 0;
}

Pygame (Python):

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 450))
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    screen.fill((255, 255, 255))
    font = pygame.font.Font(None, 36)
    text = font.render("Hello, Pygame!", True, (200, 200, 200))
    screen.blit(text, (190, 200))
    pygame.display.flip()
pygame.quit()
17,941

Open source UI framework written in Python, running on Windows, Linux, macOS, Android and iOS

Pros of Kivy

  • Cross-platform support for desktop, mobile, and web applications
  • Built-in UI elements and touch support
  • More modern and actively maintained

Cons of Kivy

  • Steeper learning curve for beginners
  • Larger file size and resource usage
  • Less suitable for simple 2D games

Code Comparison

Kivy:

from kivy.app import App
from kivy.uix.button import Button

class MyApp(App):
    def build(self):
        return Button(text='Hello World')

MyApp().run()

Pygame:

import pygame

pygame.init()
screen = pygame.display.set_mode((300, 200))
pygame.display.set_caption('Hello World')

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

pygame.quit()

Kivy offers a more declarative approach with built-in UI elements, while Pygame provides lower-level control over graphics and events. Kivy is better suited for complex, multi-platform applications with rich UIs, whereas Pygame excels in simple 2D game development and educational projects.

5,864

LÖVE is an awesome 2D game framework for Lua.

Pros of LÖVE

  • Easier to distribute games across multiple platforms
  • More performant for complex 2D games
  • Built-in physics engine and advanced graphics capabilities

Cons of LÖVE

  • Steeper learning curve for beginners
  • Smaller community and fewer learning resources
  • Less integration with Python ecosystem

Code Comparison

Pygame:

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

LÖVE:

function love.load()
    -- Initialization code
end

function love.update(dt)
    -- Game logic
end

function love.draw()
    -- Rendering code
end

Summary

Pygame is a Python library for game development, while LÖVE is a Lua-based framework. Pygame is often easier for Python developers to pick up, but LÖVE offers better performance and cross-platform capabilities. Pygame has a larger community and more resources, making it more beginner-friendly. LÖVE's structure encourages better code organization through its callback system, while Pygame requires more manual management of the game loop.

10,342

Simple and Fast Multimedia Library

Pros of SFML

  • Better performance and hardware acceleration
  • More comprehensive multimedia support (audio, networking, etc.)
  • Object-oriented design with modern C++ features

Cons of SFML

  • Steeper learning curve for beginners
  • Less extensive documentation and community resources
  • Requires C++ knowledge, which may be challenging for Python developers

Code Comparison

SFML (C++):

#include <SFML/Graphics.hpp>

int main() {
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML Window");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

    while (window.isOpen()) {
        // Event handling and drawing logic
    }
    return 0;
}

Pygame (Python):

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
running = True
while running:
    # Event handling and drawing logic
pygame.quit()

Both SFML and Pygame are popular libraries for game development and multimedia applications. SFML offers better performance and more features but requires C++ knowledge. Pygame, built on top of SDL, provides a simpler Python interface, making it more accessible for beginners and rapid prototyping. The choice between the two depends on the project requirements, performance needs, and the developer's programming language preference.

93,104

Godot Engine – Multi-platform 2D and 3D game engine

Pros of Godot

  • Full-featured game engine with built-in editor and visual scripting
  • Supports 2D and 3D game development out of the box
  • Cross-platform deployment for multiple platforms, including web and mobile

Cons of Godot

  • Steeper learning curve due to more complex architecture
  • Larger project size and resource requirements
  • Less suitable for simple 2D games or educational purposes

Code Comparison

Pygame:

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

Godot (GDScript):

extends Node2D

func _ready():
    pass

func _process(delta):
    pass

Pygame is a Python library for creating 2D games, while Godot is a complete game engine with its own scripting language (GDScript). Pygame offers simplicity and is great for learning game development basics, while Godot provides a more comprehensive set of tools for creating complex games across multiple platforms.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

.. image:: https://raw.githubusercontent.com/pygame/pygame/main/docs/reST/_static/pygame_logo.svg :alt: pygame :target: https://www.pygame.org/

|AppVeyorBuild| |PyPiVersion| |PyPiLicense| |Python3| |GithubCommits| |BlackFormatBadge|

Pygame_ is a free and open-source cross-platform library for the development of multimedia applications like video games using Python. It uses the Simple DirectMedia Layer library_ and several other popular libraries to abstract the most common functions, making writing these programs a more intuitive task.

We need your help_ to make pygame the best it can be! New contributors are welcome.

Installation

Before installing pygame, you must check that Python is installed on your machine. To find out, open a command prompt (if you have Windows) or a terminal (if you have MacOS or Linux) and type this: ::

python --version

If a message such as "Python 3.8.10" appears, it means that Python is correctly installed. If an error message appears, it means that it is not installed yet. You must then go to the official website <https://www.python.org/downloads/>_ to download it.

Once Python is installed, you have to perform a final check: you have to see if pip is installed. Generally, pip is pre-installed with Python but we are never sure. Same as for Python, type the following command: ::

pip --version

If a message such as "pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)" appears, you are ready to install pygame! To install it, enter this command: ::

pip install pygame

Once pygame is installed, quickly test your library by entering the following command, which opens one of the many example games that comes pre-installed: ::

python3 -m pygame.examples.aliens

If this doesn’t work, the Getting Started <https://www.pygame.org/wiki/GettingStarted/>_ section of the official website has more information for platform specific issues, such as adding python to your machine’s PATH settings

Help

If you are just getting started with pygame, you should be able to get started fairly quickly. Pygame comes with many tutorials and introductions. There is also full reference documentation for the entire library. Browse the documentation on the docs page_. You can also browse the documentation locally by running python -m pygame.docs in your terminal. If the docs aren't found locally, it'll launch the online website instead.

The online documentation stays up to date with the development version of pygame on GitHub. This may be a bit newer than the version of pygame you are using. To upgrade to the latest full release, run pip install pygame --upgrade in your terminal.

Best of all, the examples directory has many playable small programs which can get you started playing with the code right away.

Features

Pygame is a powerful library for game development, offering a wide range of features to simplify your coding journey. Let's delve into what pygame has to offer:

Graphics - With pygame, creating dynamic and engaging graphics has never been easier. The library provides simple yet effective tools for 2D graphics and animation, including support for images, rectangles, and polygon shapes. Whether you're a seasoned game developer or just starting out, pygame has you covered.

Sound - Pygame also includes support for playing and manipulating sound and music, making it easy to add sound effects and background music to your games. With support for WAV, MP3, and OGG file formats, you have plenty of options to choose from.

Input - Pygame provides intuitive functions for handling keyboard, mouse, and joystick input, allowing you to quickly and easily implement player controls in your games. No more struggling with complex input code, pygame makes it simple.

Game Development - Lastly, pygame provides a comprehensive suite of tools and features specifically designed for game development. From collision detection to sprite management, pygame has everything you need to create exciting and engaging games. Whether you're building a platformer, puzzle game, or anything in between, pygame has you covered.

Building From Source

If you want to use features that are currently in development, or you want to contribute to pygame, you will need to build pygame locally from its source code, rather than pip installing it.

Installing from source is fairly automated. The most work will involve compiling and installing all the pygame dependencies. Once that is done, run the setup.py script which will attempt to auto-configure, build, and install pygame.

Much more information about installing and compiling is available on the Compilation wiki page_.

Contribute

  • Documentation Contributions <https://github.com/pygame/pygame/tree/main/docs>_ - Guidelines for contributing to the main documentations
  • Writing your first unit test <http://renesd.blogspot.com/2019/11/draft-2-of-lets-write-unit-test.html>_ - Step by step guide on how to write your first unit test in Python for Pygame.
  • How to Hack Pygame <https://www.pygame.org/wiki/Hacking>_ - Information on hacking, developing, and modifying Pygame
  • Issue Tracker for beginners <https://github.com/pygame/pygame/labels/good%20first%20issue>_ - A way for beginners to contribute to the project
  • Bugs & Patches <https://www.pygame.org/wiki/patchesandbugs>_ - Report bugs
  • Communication tools <https://www.pygame.org/wiki/info>_ - More information and ways to get in touch with the Pygame team

Credits

Thanks to everyone who has helped contribute to this library. Special thanks are also in order.

  • Marcus Von Appen: many changes, and fixes, 1.7.1+ freebsd maintainer
  • Lenard Lindstrom: the 1.8+ windows maintainer, many changes, and fixes
  • Brian Fisher for svn auto builder, bug tracker and many contributions
  • Rene Dudfield: many changes, and fixes, 1.7+ release manager/maintainer
  • Phil Hassey for his work on the pygame.org website
  • DR0ID for his work on the sprite module
  • Richard Goedeken for his smoothscale function
  • Ulf EkstrÜm for his pixel perfect collision detection code
  • Pete Shinners: original author
  • David Clark for filling the right-hand-man position
  • Ed Boraas and Francis Irving: Debian packages
  • Maxim Sobolev: FreeBSD packaging
  • Bob Ippolito: MacOS and OS X porting (much work!)
  • Jan Ekhol, Ray Kelm, and Peter Nicolai: putting up with early design ideas
  • Nat Pryce for starting our unit tests
  • Dan Richter for documentation work
  • TheCorruptor for his incredible logos and graphics
  • Nicholas Dudfield: many test improvements
  • Alex Folkner for pygame-ctypes

Thanks to those sending in patches and fixes: Niki Spahiev, Gordon Tyler, Nathaniel Pryce, Dave Wallace, John Popplewell, Michael Urman, Andrew Straw, Michael Hudson, Ole Martin Bjoerndalen, Herve Cauwelier, James Mazer, Lalo Martins, Timothy Stranex, Chad Lester, Matthias Spiller, Bo Jangeborg, Dmitry Borisov, Campbell Barton, Diego Essaya, Eyal Lotem, Regis Desgroppes, Emmanuel Hainry, Randy Kaelber Matthew L Daniel, Nirav Patel, Forrest Voight, Charlie Nolan, Frankie Robertson, John Krukoff, Lorenz Quack, Nick Irvine, Michael George, Saul Spatz, Thomas Ibbotson, Tom Rothamel, Evan Kroske, Cambell Barton.

And our bug hunters above and beyond: Angus, Guillaume Proux, Frank Raiser, Austin Henry, Kaweh Kazemi, Arturo Aldama, Mike Mulcheck, Michael Benfield, David Lau

There's many more folks out there who've submitted helpful ideas, kept this project going, and basically made our life easier. Thanks!

Many thank you's for people making documentation comments, and adding to the pygame.org wiki.

Also many thanks for people creating games and putting them on the pygame.org website for others to learn from and enjoy.

Lots of thanks to James Paige for hosting the pygame bugzilla.

Also a big thanks to Roger Dingledine and the crew at SEUL.ORG for our excellent hosting.

Dependencies

Pygame is obviously strongly dependent on SDL and Python. It also links to and embeds several other smaller libraries. The font module relies on SDL_ttf, which is dependent on freetype. The mixer (and mixer.music) modules depend on SDL_mixer. The image module depends on SDL_image, which also can use libjpeg and libpng. The transform module has an embedded version of SDL_rotozoom for its own rotozoom function. The surfarray module requires the Python NumPy package for its multidimensional numeric arrays. Dependency versions:

+----------+------------------------+ | CPython | >= 3.6 (Or use PyPy3) | +----------+------------------------+ | SDL | >= 2.0.8 | +----------+------------------------+ | SDL_mixer| >= 2.0.0 | +----------+------------------------+ | SDL_image| >= 2.0.2 | +----------+------------------------+ | SDL_ttf | >= 2.0.11 | +----------+------------------------+ | SDL_gfx | (Optional, vendored in)| +----------+------------------------+ | NumPy | >= 1.6.2 (Optional) | +----------+------------------------+

License

This library is distributed under GNU LGPL version 2.1_, which can be found in the file docs/LGPL.txt. We reserve the right to place future versions of this library under a different license.

This basically means you can use pygame in any project you want, but if you make any changes or additions to pygame itself, those must be released with a compatible license (preferably submitted back to the pygame project). Closed source and commercial games are fine.

The programs in the examples subdirectory are in the public domain.

See docs/licenses for licenses of dependencies.

.. |AppVeyorBuild| image:: https://ci.appveyor.com/api/projects/status/x4074ybuobsh4myx?svg=true :target: https://ci.appveyor.com/project/pygame/pygame

.. |PyPiVersion| image:: https://img.shields.io/pypi/v/pygame.svg?v=1 :target: https://pypi.python.org/pypi/pygame

.. |PyPiLicense| image:: https://img.shields.io/pypi/l/pygame.svg?v=1 :target: https://pypi.python.org/pypi/pygame

.. |Python3| image:: https://img.shields.io/badge/python-3-blue.svg?v=1

.. |GithubCommits| image:: https://img.shields.io/github/commits-since/pygame/pygame/2.1.2.svg :target: https://github.com/pygame/pygame/compare/2.1.2...main

.. |BlackFormatBadge| image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/psf/black

.. _pygame: https://www.pygame.org .. _Simple DirectMedia Layer library: https://www.libsdl.org .. _We need your help: https://www.pygame.org/contribute.html .. _Compilation wiki page: https://www.pygame.org/wiki/Compilation .. _docs page: https://www.pygame.org/docs/ .. _GNU LGPL version 2.1: https://www.gnu.org/copyleft/lesser.html