Pygame how to install
Pygame how to install
How to install Pygame using PIP or an IDE
We will see in this tutorial how to install the pygame module on Windows or MAC using pip or the PyCharm editor.
Introduction
When you’re new to Python programming, the best way to improve your skills is to create mini-games. This allows you to have fun while learning the basics of programming. To develop a game in Python, there are several modules that make it easier to work with graphics (such as rectangles, circles, images, etc…) and sounds. Pygame is one of them.
Pygame is a Python wrapper for the SDL (Simple DirectMedia Layer) library. SDL provides cross-platform access to the underlying multimedia hardware components of your system, such as sound, video, mouse, keyboard and joystick. You can therefore program games and Python programs with Pygame that are supported on different platforms.
By default, Pygame is not installed on the Python programming environment. We will therefore see in this guide the best instructions for installing it on your system.
As an Amazon Associate I earn from qualifying purchases. If you purchase a product by using a link on this page, I’ll earn a small commission at no extra cost to you
How to install Pygame for Windows
Install Python
To run the Pygame module, we must have a version of Python on our machine. If you haven’t already done so, it is available here :
Download Latest Version of Python
Click on the version of Python you are interested in and press download. You can install the latest stable version of Python.
Once the download is complete, press the run button. Check the box ”Add Python 3.5 to PATH”.
Make sure the checkboxes for “Optional features” are checked. For the rest, you can leave them as they are. To finalize the installation, press the install button for your computer to complete the installation.
Install Module Pygame
You can get a version of Pygame via this link :
pygame‑1.9.6‑cp39‑cp39‑win32.whl
You can choose between a 32bits or 64bits version (in this example, we will start with the win32 version).
To install the previously downloaded Pygame module, we need to access the Windows command line.
To access it, right-click on the started menu and click on Execute. Then type on the text box “cmd“.
Then go to the directory where you installed the Pygame module (by default in the Downloads folder).
Once you are in the right folder, type the following command prompt:
To check that the installation has worked, type the following command prompt:
If you do not see any error messages, the installation went well.
How to install Pygame for OS X
The first step to do is to access the command line. To do so, click on the Spotlight icon and type “terminal” to find it.
We will install XCode (which is an Apple tool for creating Mac and iOS applications. Once the installation is complete, type the following command prompt:
Install Homebrew
To install it, copy and paste this on the command prompt:
You will also need to install Homebrew Cask :
Install pygame and these Requirements
To install pygame, we must first install all the pygame dependencies. To do this, please run the following commands one at a time:
As you can see, we have installed python 3 and the pygame module. To check that the installation has been successful, type the following commands:
If you don’t get any error messages, it means that the installation was successful.
How to install Pygame using PyCharm IDE
PyCharm is an integrated development environment (IDE) used in computer programming, specifically for the Python language. PyCharm is cross-platform, with Windows, macOS and Linux versions.
To start opening Pycharm and create a new python project. Then create a python file by right-clicking on the project then New then Python file. Name your python file as you wish.
In your python file, type the following line :
You will see that the pygame is underlined in red. To install pygame, move the mouse over the red underlined area and click on “install package pygame“.
Conclusion
In this tutorial, we have seen how to install pygame on Windows, OS X and using an IDE like PyCharm. Now it’s up to you to create your first 2D mini-game!
Here is an example of what you can do with Pygame :
Don’t hesitate to tell me in the comments if you have problems with the pygame installation. And also, I would be happy to see your future projects on pygame!
By ayed_amira
I’m a data scientist. Passionate about new technologies and programming I created this website mainly for people who want to learn more about data science and programming 🙂
Установка pygame и создание шаблона для разработки игр в Python 3
Библиотека pygame – это модуль Python с открытым исходным кодом для разработки игр и мультимедийных приложений. Основанный на портируемой библиотеке SDL, модуль pygame может работать на многих платформах и операционных системах.
С помощью pygame можно контролировать логику и графику игр, не беспокоясь о сложностях бэкэнда, связанных с работой видео и аудио.
Этот мануал поможет установить модуль pygame в среду разработки Python и создать шаблон для разработки игр в Python 3.
Требования
Для работы вам понадобится локальная или удаленная среда разработки Python 3.
Кроме того, нужно ознакомиться со следующими руководствами:
Установка pygame
Разверните среду программирования Python 3:
Теперь установите pygame:
pip install pygame
Collecting pygame
Using cached pygame-1.9.3-cp35-cp35m-manylinux1_x86_64.whl
Installing collected packages: pygame
Successfully installed pygame-1.9.3
Если вы установили pygame в систему с доступным видео и аудио, вы можете проверить установку с помощью команды, которая запустит макет игры и продемонстрирует, что pygame может делать с графикой и звуком:
Если вы не хотите запускать макет или в установке нет аудио/видео, можно открыть интерактивную консоль Python и попробовать импортировать модуль pygame. Чтобы запустить консоль, введите:
Теперь можно импортировать модуль:
Если вы не получили ошибок после того как нажали Enter, значит, модуль pygame был успешно установлен. Вы можете выйти из интерактивной консоли Python с помощью команды quit().
Если во время импорта произошла ошибка, обратитесь к рекомендациям на сайте pygame.
Примечание: На последующих этапах для отображения графического интерфейса пользователя и проверки кода используется монитор.
Импортирование pygame
Создайте файл our_game.py.
Начиная работу над проектом pygame, нужно сначала импортировать модуль. Добавьте в начало файла строку:
Также можно использовать еще один оператор import, чтобы добавить константы и функции pygame в глобальное пространство имен файла:
import pygame
from pygame.locals import *
Модуль pygame импортирован в файл проекта. Теперь можно создать шаблон игры.
Инициализация pygame
Затем нужно инициализировать pygame с помощью функции init().
import pygame
from pygame.locals import *
pygame.init()
Функция init() автоматически запустит все модули pygame, которые нужно инициализировать.
Также можно инициализировать каждый из модулей pygame по отдельности:
Функция init() может возвращать кортежи. Кортеж будет сообщать о состоянии инициализации. Это можно сделать как в общем вызове init(), так и при инициализации определенных модулей (это позволит понять, доступны ли эти модули).
i = pygame.init()
print(i)
f = pygame.font.init()
print(f)
Запустив этот код, вы получите вывод:
В данном случае переменная i вернула кортеж (6, 0): было выполнено 6 успешных инициализаций pygame и получено 0 ошибок. Переменная f вернула None, что значит, что модуль недоступен в этой среде.
Настройка отображения
Затем нужно настроить отображение игры. Используйте pygame.display.set_mode() для инициализации окна или экрана отображения и передайте функции переменную. В функции нужно передать аргумент разрешения экрана; это пара чисел, которые выражают ширину и высоту в кортеже. Добавьте функцию в программу:
import pygame
from pygame.locals import *
pygame.init()
game_display = pygame.display.set_mode((800, 600))
В качестве аргумента функции set_mode () был передан кортеж, который определяет высоту (600 пикселей) и ширину (800 пикселей). Обратите внимание: кортеж содержится в круглых скобках функции, поэтому в приведенной выше функции указаны двойные скобки.
Обычно для определения разрешения экрана игры используются целые числа, которые можно присвоить переменным, чтобы не вводить их вручную. Это упростит разработку программы.
Ширину экрана игры можно присвоить переменной display_width, а высоту – переменной display_height. Переменные можно передать функции set_mode().
import pygame
from pygame.locals import *
pygame.init()
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width, display_height))
Обновление экрана
Затем нам нужно использовать одну из двух доступных функций для обновления отображения поверхности игры.
По сути анимация – это просто смена кадров во времени. Хорошим примером тут будет кинеограф – сшитая в блокнот серия картинок, при быстром перелистывании которой получается анимированное изображение.
Для обновления поверхности игры можно использовать функцию flip(). Вызовите ее:
Эта функция обновляет всю поверхность отображения.
Чаще вместо flip() используется функция update(), которая обновляет только часть изображения, что экономит память.
Добавьте update() в конец файла our_game.py:
import pygame
from pygame.locals import *
pygame.init()
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.update()
Программа будет работать без ошибок, но экран игры просто откроется и сразу закроется.
Создание цикла игры
Теперь можно начать работу над основным циклом игры.
Создайте цикл while, который будет запускать игру. Цикл будет вызывать логическое значение True, потому он будет работать непрерывно, пока его не остановит пользователь.
В главном цикле игры нужно построить цикл for для итерации очереди пользовательских событий, которые будут вызваны функцией pygame.event.get().
На данный момент в цикле for ничего нет, но в него можно добавить оператор print() и убедиться, что программа работает правильно. Передать события для итерации можно как print(event).
Добавьте в файл циклы и print().
import pygame
from pygame.locals import *
pygame.init()
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.update()
while True:
for event in pygame.event.get():
print(event)
Теперь убедитесь, что код работает:
После запуска файла на экране появится окно 800×600. Чтобы проверить события, вы можете навести курсор мыши на окно, щелкнуть по окну и нажать клавиши на клавиатуре. Эти события будут распечатываться в окне консоли.
Вывод выглядит примерно так:
Этот вывод отображает пользовательские события. Такие события будут контролировать игру, поскольку они генерируются пользователем. Всякий раз, когда вы запускаете функцию pygame.event.get (), код будет принимать эти события.
Остановите программу (CTRL + C).
На данном этапе print() можно удалить или закомментировать.
Выход из игры
Чтобы выйти из программы pygame, можно сначала объявить соответствующие модули неинициализированными, а затем просто выйти из Python с помощью функции quit().
Поскольку пользователи контролируют работу и события в игре, pygame.QUIT отправляется в очередь событий, когда пользователь завершает работу программы, нажав на «X» в верхнем углу игрового окна.
Добавьте в цикл for выражение if.
import pygame
from pygame.locals import *
pygame.init()
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
quit()
Новый код говорит программе, что если пользователь нажал Х, программа должна прекратить работу с помощью функций pygame.quit() и quit().
Поскольку ранее мы импортировали pygame.locals, теперь можно использовать event.type и QUIT без «pygame.» в начале.
Также запрос на выход из программы могут вызывать другие пользовательские события, например, событие KEYDOWN и несколько ключей.
Событие KEYDOWN значит, что пользователь нажал клавишу на клавиатуре. К примеру, это может быть клавиша Q или ESC. Добавьте код в цикл for.
import pygame
from pygame.locals import *
pygame.init()
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == QUIT or (
event.type == KEYDOWN and (
event.key == K_ESCAPE or
event.key == K_q
)):
pygame.quit()
quit()
Логические операторы сообщат программе, что она должна прекратить работу, если пользователь нажимает «X» в верхнем углу игрового окна или клавиши Q или ESC.
На этом этапе можно протестировать функциональность игры и затем выйти из нее, либо с помощью значка Х, либо нажав Q или ESC.
Улучшение кода
Теперь у вас есть полностью рабочая программа, однако код еще можно усовершенствовать.
К примеру, код цикла while можно поместить в определение функции.
def event_handler():
for event in pygame.event.get():
if event.type == QUIT or (
event.type == KEYDOWN and (
event.key == K_ESCAPE or
event.key == K_q
)):
pygame.quit()
quit()
Это сократит цикл while, что особенно важно для удобочитаемости кода.
Также можно добавить заголовок окна (в настоящее время здесь указано pygame window). Для этого используйте:
Функцию pygame.display.update() можно переместить в основной цикл игры.
В итоге код программы выглядит так:
import pygame
from pygame.locals import *
pygame.init()
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption(‘Our Game’)
def event_handler():
for event in pygame.event.get():
if event.type == QUIT or (
event.type == KEYDOWN and (
event.key == K_ESCAPE or
event.key == K_q
)):
pygame.quit()
quit()
while True:
event_handler()
pygame.display.update()
Этот код еще можно улучшить, например, добавить оператор break.
Теперь вы можете приступать к изучению анимации, спрайтовой графики и управления кадрами. Больше информации о pygame можно найти в документации pygame.
How to install Pygame on Windows 10 and get started
In this article, you will learn how to install Pygame on Windows 10 and get started with the basic concepts.
Pygame is a set of Python modules used to create fully-featured multimedia programs and video games. It is very simple and easy to use. It is free, platform independent and run on almost every operating system. So we can easily create freeware, shareware, and commercial games with it.
Install Pygame in Windows
Pygame needs Python. We hope you have already installed it, and if you do not, please follow our this tutorial on Python Installation. Here is the command to install Pygame with pip tool.
Getting Started Pygame
For using the Pygame, we must import this at the top of the script. This includes all the functions that pygame and sys modules have.
Where we call the function of pygame, we will have to write modulename.functionname() format. Instead, we can directly use the functionname() by adding the following import statement.
The pygame.locals contains several constant variables that are easy to identify. Next, the pygame needs to be initialized using the following statement.
Set the window
The pygame.display.set_mode() function returns the pygame.Surface object for the window. The set_mode() function accepts two arguments width and height of the window.
Set the window caption
To set the caption on the top of the window, call pygame.display.set_caption() function.
Pygame Event Object
When we do any action on the window, it is recorded as an event, like- moving the mouse or pressing a key on the keyboard. Pygame provides ‘pygame.event.Event‘ object to record these events and ‘pygame.event.get()‘ to get a list of event objects. We can use the for loop to iterate over these events.
Quit Pygame Event
The event object has a member variable ‘type‘, which tells us the type of the object. If the event object type equals ‘QUIT‘, then the ‘pygame.quit()‘ and the ‘sys.exit()‘ functions are called.
Updating the screen
Basic Pygame Code Pattern
Here, we have merged the above explained code and this is the basic pygame code patterns.
Basic Pygame code to draw rectangle
Here is the basic code to draw rectangle and set color in pygame.
Install Pygame in Linux
In this article, we will discuss how to install PyGame in the Linux system. We are using Ubuntu 20 LTS you can use any other one.
To successfully install PyGame in your Linux system, follow the below procedure:
Because the PyGame is only supported python 3.7.7 or higher version so make sure you are using the latest version of python. Type the below command to the check the version of the article.
Note: If Python is not installed refer to install python in the Linux system.
The pip is a python package installer, if you want to use any external package in your python file you first install it in your local system, so the pip tool is used. If you are already using the new pip version so follow the below steps if not, so refer to the article on how to install pip in the Linux system.
Open the terminal and make sure you are the root user.
Type your password and doing the below process as a root user and update Linux packages using the below command.
After doing the step you are ready to install PyGame in your Linux system.
Installing Pygame
Type the below command in your terminal and hit the enter key.
sudo apt-get install python3-pygame
This process will take time finally you successfully installed your PyGame module in your Linux system.
Type below command and open your python interpreter and import PyGame.
Displaying the PyGame version indicates that the library is properly installed.
Chapter 1 – Installing Python and Pygame
What You Should Know Before You Begin
You don’t need to know how to use the Pygame library before reading this book. The next chapter is a brief tutorial on all of Pygame’s major features and functions.
Just in case you haven’t read the first book and already installed Python and Pygame on your computer, the installation instructions are in this chapter. If you already have installed both of these then you can skip this chapter.
Downloading and Installing Python
Before we can begin programming you’ll need to install software called the Python interpreter on your computer. (You may need to ask an adult for help here.) The interpreter is a program that understands the instructions that you’ll write (or rather, type out) in the Python language. Without the interpreter, your computer won’t be able to run your Python programs. We’ll just refer to “the Python interpreter” as “Python” from now on.
Windows Instructions
Double-click on the python-3.2.msi file that you’ve just downloaded to start the Python installer. (If it doesn’t start, try right-clicking the file and choosing Install.) Once the installer starts up, just keep clicking the Next button and just accept the choices in the installer as you go (no need to make any changes). When the install is finished, click Finish.
Mac OS X Instructions
Mac OS X 10.5 comes with Python 2.5.1 pre-installed by Apple. Currently, Pygame only supports Python 2 and not Python 3. However, the programs in this book work with both Python 2 and 3.
Ubuntu and Linux Instructions
Pygame for Linux also only supports Python 2, not Python 3. If your operating system is Ubuntu, you can install Python by opening a terminal window (from the desktop click on Applications > Accessories > Terminal) and entering “ sudo apt-get install python2.7 ” then pressing Enter. You will need to enter the root password to install Python, so ask the person who owns the computer to type in this password if you do not know it.
You also need to install the IDLE software. From the terminal, type in “ sudo apt-get install idle ”. The root password is also needed to install IDLE (ask the owner of your computer to type in this password for you).
Starting Python
We will be using the IDLE software to type in our programs and run them. IDLE stands for Interactive DeveLopment Environment. The development environment is software that makes it easy to write Python programs, just like word processor software makes it easy to write books.
If your operating system is Windows XP, you should be able to run Python by clicking the Start button, then selecting Programs, Python 3.1, IDLE (Python GUI). For Windows Vista or Windows 7, just click the Windows button in the lower left corner, type “IDLE” and select “IDLE (Python GUI)”.
If your operating system is Max OS X, start IDLE by opening the Finder window and click on Applications, then click Python 3.2, then click the IDLE icon.
If your operating system is Ubuntu or Linux, start IDLE by opening a terminal window and then type “ idle3 ” and press Enter. You may also be able to click on Applications at the top of the screen, and then select Programming, then IDLE 3.
Installing Pygame
Pygame does not come with Python. Like Python, Pygame is available for free. You will have to download and install Pygame, which is as easy as downloading and installing the Python interpreter. In a web browser, go to the URL http://pygame.org and click on the “Downloads” link on the left side of the web site. This book assumes you have the Windows operating system, but Pygame works the same for every operating system. You need to download the Pygame installer for your operating system and the version of Python you have installed.
For Linux, open a terminal and run “ sudo apt-get install python-pygame ”.
On Windows, double click on the downloaded file to install Pygame. To check that Pygame is install correctly, type the following into the interactive shell:
If nothing appears after you hit the Enter key, then you know Pygame has successfully been installed. If the error ImportError: No module named pygame appears, then try to install Pygame again (and make sure you typed import pygame correctly).
This chapter has five small programs that demonstrate how to use the different features that Pygame provides. In the last chapter, you will use these features for a complete game written in Python with Pygame.
How to Use This Book
“Making Games with Python & Pygame” is different from other programming books because it focuses on the complete source code for several game programs. Instead of teaching you programming concepts and leaving it up to you to figure out how to make programs with those concepts, this book shows you some programs and then explains how they are put together.
In general, you should read these chapters in order. There are many concepts that are used over and over in these games, and they are only explained in detail in the first game they appear in. But if there is a game you think is interesting, go ahead and jump to that chapter. You can always read the previous chapters later if you got ahead of yourself.
The Featured Programs
Each chapter focuses on a single game program and explain how different parts of the code work. It is very helpful to copy these programs by typing in the code line by line from this book.
However, you can also download the source code file from this book’s website. In a web browser, go to the URL http://invpy.com/source and follow the instructions to download the source code file. But typing in the code yourself really helps you learn the code better.
Downloading Graphics and Sound Files
Line Numbers and Spaces
When entering the source code yourself, do not type the line numbers that appear at the beginning of each line. For example, if you see this in the book:
1. number = random.randint(1, 20)
3. print(‘Hello world!’)
You do not need to type the “1.” on the left side, or the space that immediately follows it. Just type it like this:
number = random.randint(1, 20)
Those numbers are only used so that this book can refer to specific lines in the code. They are not a part of the actual program.
Aside from the line numbers, be sure to enter the code exactly as it appears. Notice that some of the lines don’t begin at the leftmost edge of the page, but are indented by four or eight or more spaces. Be sure to put in the correct number of spaces at the start of each line. (Since each character in IDLE is the same width, you can count the number of spaces by counting the number of characters above or below the line you’re looking at.)
For example in the code below, you can see that the second line is indented by four spaces because the four characters (“whil”) on the line above are over the indented space. The third line is indented by another four spaces (the four characters, “if n” are above the third line’s indented space):
while spam 1. print(‘This is the first line! xxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxx’)
2. print(‘This is the second line, not the third line.’)
Checking Your Code Online
Some of the programs in this book are a little long. Although it is very helpful to learn Python by typing out the source code for these programs, you may accidentally make typos that cause your programs to crash. It may not be obvious where the typo is.
You can copy and paste the text of your source code to the online diff tool on the book’s website. The diff tool will show any differences between the source code in the book and the source code you’ve typed. This is an easy way of finding any typos in your program.
More Info Links on http://invpy.com
Even though this book is not dangerously heavy, please do not let it fall on you anyway.