Как сделать онлайн игру на python

от admin

Создание игр на Python 3 и Pygame: Часть 1

Многие разработчики приходят в разработку ПО, потому что хотят создавать игры. Не все могут стать профессиональными разработчиками игр, но любой может создавать собственные игры из интереса (а может быть, и с выгодой). В этом туториале, состоящем из пяти частей, я расскажу вам, как создавать двухмерные однопользовательские игры с помощью Python 3 и замечательного фреймворка PyGame.

Мы создадим версию классической игры Breakout. Освоив этот туториал, вы будете чётко понимать, что необходимо для создания игры, познакомитесь с возможностями Pygame и напишете собственный пример игры.

Мы реализуем следующие функции и возможности:

  • простые стандартные GameObject и TextObject
  • простой стандартный Game object
  • простая стандартная кнопка
  • файл конфигурации
  • обработка событий клавиатуры и мыши
  • кирпичи, ракетка и мяч
  • управление движением ракетки
  • обработка коллизий мяча с объектами игры
  • фоновое изображение
  • звуковые эффекты
  • расширяемая система спецэффектов

Краткое введение в программирование игр

Главное в играх — перемещение пикселей на экране и издаваемый шум. Почти во всех видеоиграх есть эти элементы. В этой статье мы не будем рассматривать клиент-серверные и многопользовательские игры, для которых требуется много сетевого программирования.

Основной цикл

Основной цикл (main loop) игры выполняется и обновляет экран через фиксированные интервалы времени. Они называются частотой кадров и определяют плавность перемещения. Обычно игры обновляют экран 30-60 раз в секунду. Если частота будет меньше, то покажется, что объекты на экране дёргаются.

Внутри основного цикла есть три основных операции: обработка событий, обновление состояния игры и отрисовка текущего состояния на экране.

Обработка событий

События в игре состоят из всего, что происходит за пределами управления кода игры, но относится к выполнению игры. Например, если в Breakout игрок нажимает клавишу «стрелка влево», то игре нужно переместить ракетку влево. Стандартными событиями являются нажатия (и отжатия) клавиш, движение мыши, нажатия кнопок мыши (особенно в меню) и события таймера (например, действие спецэффекта может длиться 10 секунд).

Обновление состояния

Сердце любой игры — это её состояние: всё то, что она отслеживает и отрисовывает на экране. В случае Breakout к состоянию относятся положение всех кирпичей, позиция и скорость мяча, положение ракетки, а также жизни и очки.

Существует также вспомогательное состояние, позволяющее управлять игрой:

  • Отображается ли сейчас меню?
  • Закончена ли игра?
  • Победил ли игрок?

Отрисовка

Игре нужно отображать своё состояние на экране, в том числе отрисовывать геометрические фигуры, изображения и текст.

Игровая физика

В большинстве игр симулируется физическое окружение. В Breakout мяч отскакивает от объектов и имеет очень приблизительную систему физики твёрдого тела (если это можно так назвать).

В более сложных играх могут использоваться более изощрённые и реалистичные физические системы (особенно в 3D-играх). Стоит также отметить, что в некоторых играх, например, в карточных, физики почти нет, и это совершенно нормально.

ИИ (искусственный интеллект)

Во многих играх мы сражаемся с компьютерными противниками, или в них есть враги, пытающиеся нас убить. Часто они ведут себя в игровом мире так, как будто обладают разумом.

Например, враги преследуют игрока и знают о его местоположении. В Breakout нет никакого ИИ. Игрок сражается с холодными и твёрдыми кирпичами. Однако ИИ в играх часто очень прост и всего лишь следует простым (или сложным) правилам, обеспечивающим псевдоразумные результаты.

Воспроизведение звука

Воспроизведение звука — ещё один важный аспект игр. В общем случае существует два типа звука: фоновая музыка и звуковые эффекты. В Breakout я реализую только звуковые эффекты, которые воспроизводятся при различных событиях.

Фоновая музыка — это просто музыка, постоянно играющая на фоне. В некоторых играх она не используется, а в некоторых меняется на каждом уровне.

Жизни, очки и уровни

В большинстве игр игрок имеет определённое количество жизней, и когда они заканчиваются, игра завершается. Также в играх часто присутствуют очки, позволяющие понять, насколько хорошо мы играем, и дающие мотивацию к самосовершенствованию или просто хвастаться друзьям своими рекордами. Во многих играх есть уровни, которые или совершенно отличаются, или постепенно увеличивают сложность.

Знакомство с Pygame

Прежде чем приступить к реализации игры, давайте немного узнаем о Pygame, который возьмёт на себя большую часть работы.

Что такое Pygame?

Pygame — это фреймворк языка Python для программирования игр. Он создан поверх SDL и обладает всем необходимым:

  • зрелостью
  • хорошим сообществом
  • открытым исходным кодом
  • кроссплатформенностью
  • качественной документацией
  • множеством примеров игр
  • простотой изучения

Установка Pygame

Введите pip install pygame , чтобы установить фреймворк. Если вам нужно что-то ещё, то следуйте инструкциям из раздела Getting Started в Wiki проекта. Если у вас, как и у меня, macOS Sierra, то могут возникнуть проблемы. Мне удалось установить Pygame без сложностей, и код работает отлично, но окно игры никогда не появляется.

Это станет серьёзным препятствием при запуске игры. В конце концов мне пришлось запускать её в Windows внутри VirtualBox VM. Надеюсь, ко времени прочтения этой статьи проблема будет решена.

Архитектура игры

Играм нужно управлять кучей информации и выполнять почти одинаковые операции со множеством объектов. Breakout — это небольшая игра, однако попытка управлять всем в одном файле может оказаться слишком утомительной. Поэтому я решил создать файловую структуру и архитектуру, которая подойдёт и для гораздо более крупных игр.

Структура папок и файлов

Pipfile и Pipfile.lock — это современный способ управления зависимостями в Python. Папка images содержит изображения, используемые игрой (в нашей версии будет только фоновое изображение), а в папке sound_effects directory лежат короткие звуковые клипы, используемые (как можно догадаться) в качестве звуковых эффектов.

Файлы ball.py, paddle.py и brick.py содержат код, относящийся к каждому из этих объектов Breakout. Подробнее я рассмотрю их в следующих частях туториала. Файл text_object.py содержит код отображения текста на экране, а в файле background.py содержится игровая логика Breakout.

Однако существует несколько модулей, создающих произвольный «скелет» общего назначения. Определённые в них классы можно будет использовать в других играх на основе Pygame.

Класс GameObject

GameObject представляет собой визуальный объект, знающий о том, как себя рендерить, сохранять свои границы и перемещаться. В Pygame есть и класс Sprite, исполняющий похожую роль, но в этом туториале я хочу показать вам, как всё работает на низком уровне, а не полагаться слишком активно на готовую магию. Вот как выглядит класс GameObject:

GameObject предназначен для того, чтобы быть базовым классом для других объектов. Он непосредственно раскрывает множество свойств его прямоугольника self.bounds, а в своём методе update() он перемещает объект в соответствии с его текущей скоростью. Он ничего не делает в своём методе draw() , который должен быть переопределён подклассами.

Класс Game

Класс Game — это ядро игры. Он выполняется в основном цикле. В нём есть множество полезных возможностей. Давайте разберём его метод за методом.

Метод __init__() инициализирует сам Pygame, систему шрифтов и звуковой микшер. Три разных вызова нужны, так как не во всякой игре на Pygame используются все компоненты, поэтому можно контролировать подсистемы, которые мы используем, и инициализировать только нужные с соответствующими параметрами. Метод создаёт фоновое изображение, основную поверхность (на которой всё отрисовывается) и игровой таймер с правильной частотой кадров.

Элемент self.objects хранит все игровые объекты, которые должны рендериться и обновляться. Различные обработчики управляют списками функций-обработчиков, которые должны выполняться при определённых событиях.

Методы update() и draw() очень просты. Они обходят все управляемые игровые объекты и вызывают соответствующие им методы. Если два объекта накладываются друг на друга на экране, то порядок списка объектов определяет, какой из них будет рендериться первым, а остальные будут частично или полностью его перекрывать.

Метод handle_events() слушает события, генерируемые Pygame, такие как события клавиш и мыши. Для каждого события он вызывает все функции-обработчики, которые должны обрабатывать события соответствующих типов.

Наконец, метод run() выполняет основной цикл. Он выполняется до тех пор, пока элемент game_over не принимает значение True. В каждой итерации он рендерит фоновое изображение и вызывает по порядку методы handle_events() , update() и draw() .

Затем он обновляет экран, то есть записывает на физический дисплей всё содержимое, которое было отрендерено на текущей итерации. И последнее, но не менее важное — он вызывает метод clock.tick() для управления тем, когда будет вызвана следующая итерация.

Заключение

В этой части мы изучили основы программирования игр и все компоненты, участвующие в создании игр. Также мы рассмотрели сам Pygame и узнали, как его установить. Наконец, мы погрузились в архитектуру игры и изучили структуру папок, классы GameObject и Game.

Во второй части мы рассмотрим класс TextObject , используемый для рендеринга текста на экране. Мы создадим основное окно, в том числе и фоновое изображение, а затем узнаем, как отрисовывать объекты (мяч и ракетку).

Name already in use

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Игра в стиле RPG созданная на pygame

  • Познакомиться с инструментами Python для создания игровых процессов
  • Разобраться с работой TCP/UDP – серверов
  • Написать многопользовательскую сетевую игру

pygame — библиотека Python, предназначенный для написания компьютерных игр и мультимедиа-приложений.

pygame

pyganim — для добавления анимаций в игру

pyganim

peewee — orm для взаимодействия с БД

peewee

sql — СУБД для хранения информации об игроке

sql

Как это выглядит

menu

персонаж повторное имя нельзя рандомный персонаж
person1 person2 person3

options

таверна город внешний мир с драконами
world1 world2 world3

battle

P.S. чтобы встретить драконов, необходимо немного потусоваться на зеленой лужайке внешнего мира 🙂

Чтобы запустить игру, запустите server_TCP.py + server_UDP.py, а затем уже Runner.py и выбирайте offline режим.

Если вы хотите запустить игру в сети, то запустите cервера server_TCP.py и server_UDP.py на своем хосте. Измените поле HOST в others.py на адрес вашего хоста. Также поменяйте порты в коде, на которых теперь крутятся эти два сервера. Затем уже запускайте Runner.py

About

Многопользовательская сетевая игра, написанная на python с использованием pygame

Multiplayer Game Programming for Teens with Python: Part 1

Have you ever wondered how a multiplayer game works? This tutorial will teach teens and adults about multiplayer game programming in python with PyGame. By .

Sign up/Sign in

With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!

Already a member of Kodeco? Sign in

Sign up/Sign in

With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!

Already a member of Kodeco? Sign in

Share this

Twitter
Facebook
Email

Contents

Multiplayer Game Programming for Teens with Python: Part 1

  • Getting Started
  • The Rules of the Game
  • Object-Oriented Programming: A Quick Introduction
  • Setting Up a Basic Object-Oriented Game
  • Drawing the Board and Lines on the Screen
  • Adding Other Types of Lines
  • Finishing Touches
  • Where to Go from Here?

This is a post by Tutorial Team Member Julian Meyer, a 13-year-old python developer. You can find him on Google+ and Twitter.

I’m sure that once in a while, you and your friends go online to play a multiplayer game. Have you ever wondered about the inside of that game and how everything works?

In this tutorial, you will learn about multiplayer game programming by creating a sample game. Along the way you will also learn about object-oriented programming.

For this tutorial, you will be using Python and the PyGame modules. If you are new to Python or PyGame, you should first look at this earlier tutorial on beginning game programming, which explains some of the basics of PyGame.

Getting Started

The first step is to make sure that you have PyGame installed. You can download a Mac installer for PyGame here. Make sure you download the Lion installer if you have Mac OSX 10.7 or up. Otherwise, download the Snow Leopard installer.

You can also download and install PyGame in these ways:

  • With MacPorts using: sudo port install python2.7 py27-game
  • With Fink using: sudo fink install python27 pygame-py27
  • With Homebrew and pip using the command found here.

If you are running Windows, then you can find your installer here.

Note: If you had trouble in the last tutorial, make sure you have the 32-bit version of Python on your system. If you have a 64-bit system, then you need to run python2.7-32 to run Python.

Lastly, download the resources for this project, which include some images and sounds that you’ll need for this game.

The Rules of the Game

The game you’re going to make in this tutorial is called “Boxes”. You may be familiar with playing this game on paper with some friends while you were in school!

In case you’re not familiar with the game, here are the rules:

  1. The board consists of a 7×7 grid of points (which makes a 6×6 grid of cubes if you were to connect the dots).

Boxes1

  1. On each player’s turn, the player fills in the horizontal or vertical line segment connecting two neighboring points.

Boxes2

  1. If filling in a line segment completes a box on the grid, the player becomes the owner of that square and gets a point. The player also gets to place another line segment on the same turn.

Boxes3

  1. The player with the most squares/points at the end of the game wins!

Although these rules are very simple, it’s a fun game to play, especially if you’re bored. But wouldn’t it be great if you could play this online?

Object-Oriented Programming: A Quick Introduction

Before we begin, let’s discuss something called Object-Oriented Programming which you’re going to use in this tutorial.

Object-oriented programming, also known as OOP, is a type of programming based on objects. Object are bundles of data and associated logic. For example, you might have a “dog” object that consists of some data (the dog’s name or favorite treat) and associated logic (for example, instructions on how to bark).

Objects are made from templates called classes that define what kinds of data the object can hold and what kinds of things the object can do. These are known as the object’s properties and methods, respectively.

Methods are functions that represent something you can ask the object to do. For example, the statement car.drive() can be interpreted as telling the object in the “car” variable to “drive”. Properties are variables that belong to an object. Continuing the example, your car object might have a property called gas , and the statement car.gas = 100 would set the car’s gas to 100.

These two statements manipulate a car object that already exists. Recall that the car’s class is the template that defines how to make a car object and what a car is by defining its properties and methods. Within the definitions of those methods, you will find the code that manipulates the car from the inside. For instance, instead of car.gas = 100 , you might find self.gas=100 , which is a car object telling itself – self , get it? – to set its own gas to 100.

OOP is a large topic but the basics above are all you need to get started. Your code will describe the Boxes game as the interaction of various objects. Those objects all have properties and methods, which you will define in the object’s class. And when you write a piece of code, you should remember whether you’re writing the class code that defines what an object can do from the “inside” of the object, or code that manipulates an object from the “outside” of that object.

Setting Up a Basic Object-Oriented Game

There are a couple of ways to use an object-oriented framework for your game. Your Boxes game will take a simple approach in which there is one class for the client and one for the server. For now, let’s just create the main client class that will run when the user starts the game.

At the start of making every game, I like to make a folder for the game. When you unzipped the resources for this project, it should have created a folder or you called boxes. This is where you will put your source code for the game – right here alongside all the images.

Create a file in this directory called boxes.py using your favorite text editor (if you don’t have one, you can use TextEdit on the Mac, or Notepad in Windows). Then add this import of the file:

This imports the PyGame module for you to use. Before you go any further, you should test that at least this much is working. To do this, open Terminal and switch to your boxes directory using the cd command. Then enter python boxes.py. For example, here’s what it looks like on my machine:

If you get no errors after running this, that means you have PyGame installed correctly, and you are good to go.

Note: If running the code above gives you an ImportError saying there is “No module named pygame”, then you have not installed PyGame or else you have installed PyGame into a copy of Python different from the one you are running. For instance, if you used MacPorts to install Python 2.7 and PyGame with port install python2.7 py27-game , then make sure to run the same Python by calling python2.7 from the Terminal.

If running the code above gives you this specific error:

That means you need to run Python in 32-bit mode, like this:

Next add the class definition, as well as one thing every class should have:

The first line of this code tells the compiler that you are creating a new class called BoxesGame. The second line defines a method called __init__ . The surrounding double underscores are a hint that this is a special method name. In fact, this name identifies the method as the class’s __init__ method, the method that you run whenever you want to create or instantiate an object of the class.

Now you’ll fill in the body of the init function to do some PyGame initialization. Add this to the code you wrote above, in place of the comment beginning with #put something here. :

Make sure you indent it correctly, so that everything lines up to the left margin of where the “#put something here…” comment was. You can read more about the matter here: Python Indentation.

Let’s look at the code you just added, one chunk at a time:

  1. First you initialize PyGame and two variables that you’ll use to set up the screen, width and height .
  2. Then you initialize the screen using those two variables. You also set the title of the screen.
  3. Finally, you initialize the PyGame clock, which you’ll need for tracking time in the game.

Next let’s add the update() loop, which runs every periodically to update the game, draw the graphics and receive user input. Do this by simply adding the following after the __init__ method (the left margin should be equal to the left margin of __init__):

This is a basic update loop that clears the screen and checks to see if the user wants to quit the game. You’ll be adding more to this later.

Running the Python file now won’t do anything yet, as all you’ve done is defined the class BoxesGame. You still need to create an object of this class and start the game!

Now that you have the update loop ready, let’s add the code that will run the main game class. After that, you’ll set up some of the basic graphics in the game, such as drawing the board.

Add this code to the end of the file to start the game (the left margin should be equal to the left margin of the file):

This is the nice thing about object-oriented programming: The code that actually makes things happen is only three lines long!

At this point, the entire file should look like this:

That’s it. Now wasn’t that easy? This is a good time to run the game:

Screen Shot 2013-06-13 at 6.16.08 AM

As you can see, running the game results in a very impressive black screen! Yay!

You may not understand this now, but game writing is a strategic process. Think of it as being an architect. You have just built a strong base for your building. Large buildings must have very good bases and so you must think your plan through before you start.

Let’s add another method. If you don’t remember what this means, reread the section of the tutorial called, “Object Oriented Programming: A Quick Introduction.”

Drawing the Board and Lines on the Screen

In PyGame, the upper left of the window is coordinate (0, 0). So let’s define a coordinate system for the points in the Boxes grid that is similar, with (0,0) representing the upper left point and (6,6) representing the bottom right point:

Boxes4

Somehow, you need a way to represent the potential line segments in the game. Well, there are two different types of line segments: horizontal and vertical lines. Let’s imagine you make a list of all the potential horizontal and vertical line combinations. It would look something like this:

Boxes5

In programming terms, a list is also known as an array. And when you have a list of lists, like the horizontal and vertical line combinations here, that’s called a 2D array.

For example, to represent the horizontal line from (0, 0) to (1, 1), that would be row 0, column 0 in the “horizontal lines” list.

Note that the horizontal lines list has 6 rows and 7 columns, and the vertical lines list has 7 rows and 6 columns.

Add these two lines to __init__ to define these two arrays:

A quick way to create an array is to do this: [valuePerItem for x in y] . In this case, you fill an array with an array filled with False s. False stands for an empty space.

Now that you have the board representation, let’s get to the code of drawing the board.

First of all, create a new method called initGraphics() . This method will be something you call from __init__ but, to keep your code organized, you’re creating a separate method just for the purpose of loading the graphics. Add this right before the __init__ function:

As you can see, you have three main sprites: an normal (empty) line, a done (occupied) line and a hover line. You rotate each of these lines by 90 degrees to draw the horizontal versions of them. These files came with the resources you downloaded earlier and should be in the same directory as your Python file.

You have a method to load all of the graphics, but you have yet to call it. Try to guess where to add what!

Once you have an answer, click the Show button below to see if you’re right.

[spoiler title=”Solution”]Add this at the end of __init__:

Next you should add the code that actually draws the board. To loop through every x and y in a grid, you must add a for loop inside of a for loop. (For all of you Inception fans, a for-loop-ception.) You need a loop that loops through the x- and y-values. Add this right after the __init__ method:

This code simply loops through the grid and checks whether or not that part on the grid has been clicked. The code does this for both the horizontal and vertical lines. self.boardv[x][y] and self.boardh[x][y] returns either true or false, depending on whether the appropriate line segment has been filled in yes.

Running the program now still won’t do anything. All you’ve done is defined what the game should do if it ever gets that method call.

Now let’s add the method call to the update function. Add this after you clear the screen with screen.fill(0) :

And of course, as a good programmer, you remember to add a comment to explain the code.

Run your code now. When you do, you should see the grid drawn on the screen:

Screen Shot 2013-06-13 at 6.28.57 AM

Every time I write map drawing code, I like to test it out, both because it’s fun and because it’s a good way to find bugs. Add this after you initialize the boards by defining self.boardh and self.boardv :

Run the code and as you can see, one horizontal line is lit up – the line from (5, 3) to (5, 4):

Boxes6

Pretty cool, huh? Delete the line of test code you just added.

Good job. You’ve finished drawing your map, which is one of the most difficult things to do in game programming.

Adding Other Types of Lines

Next you need to find the line to which the mouse is closest so that you can draw a hover line at that spot.

First, at the top of the file, add this line to import the math library, which you’ll need soon:

Then, before pygame.display.flip() , add this big chunk of code:

Wow! That’s a lot of code. Let’s go over the sections one-by-one:

  1. First you get the mouse position with PyGame’s built-in function.
  2. Next you get the position of the mouse on the grid, using the fact that each square is 64×64 pixels.
  3. You check if the mouse is closer to the top and bottom or the left and right, in order to determine whether the user is hovering over a horizontal or vertical line.
  4. You get the new position on the grid based on the is_horizontal variable.
  5. You initialize the variable board as either boardh or boardv , whichever is correct.
  6. Finally, you try drawing the hover line to the screen, taking into consideration whether it is horizontal or vertical and on the top, bottom, left or right. You also check if the line is out of bounds. If it is, or if the line has already been drawn, you don’t draw the hover line.

Run the program and you get. drum roll, please. a map where a line lights up as your mouse moves over it!

If you’re like me, you probably have your mouse whizzing across the board by now. Take some time to enjoy your results.

OK, now you have a grid that lights up when the player’s mouse moves over a line. But this isn’t a game where you just have to move your mouse around a bunch. You need to add the click-to-lay-down-line functionality.

To do this, you’re going to use PyGame’s built-in mouse function, which is simply pygame.mouse.get_pressed()[0] . The function returns either 1 or 0, depending on whether the mouse button is currently pressed down.

Before I tell you how to implement this in your game, try figuring it out yourself. Remember how you used if statements before and how to create a piece on the board.

[spoiler title=»Solution»]Add this directly after the last block of code defining hover behavior:

Run the program now and voilà! If you click, you place a line just where you were hovering. As you can see, the code you added checks if the mouse is pressed and if the line should be horizontal or vertical, and places the line accordingly.

Boxes7

One problem, though, is that if you click at the bottom of the screen (below where the boxes are drawn), the game crashes. Let’s see why this is. When something crashes, usually it gives you an error report in the Terminal. In this case, the report looks like this:

This error is saying that the array boardh that you tried to access doesn’t go as far as where you clicked. Remember that variable called isoutofbounds ? That will come in handy here. Simply change this:

Now if you try clicking outside of the board, the game doesn’t crash. Good job – you have just demonstrated the word debugging!

Before you begin implementing the game logic on the server side, let’s first add some finishing touches to the client side.

Finishing Touches

One thing that really bugs me are the spaces at the junctions of the lines. Fortunately, you can fix this quite easily using a 7×7 grid of square dots to fill in those spaces. Of course, you do need the image file, so let’s load that right now and at the same time add all of the other images you will be using in this section.

Add this to the end of initGraphics() :

Now that you image is loaded, let’s draw each of the 49 dots onto the screen. Add this to the end of drawBoard() :

All right, enough code! It’s time for a test run. Run the game, and you should get a better-looking grid.

Screen Shot 2013-06-16 at 7.29.20 AM

Next, let’s put a head-up display or HUD at the bottom of the screen. First, you need to create the drawHUD() method. Add this code after drawBoard() :

This code also draws the background of the score panel.

Let me go over the way PyGame handles fonts. There are three steps:

  1. First you define a font with a set size.
  2. Next you call font.render(«your text here») to create a surface for those letters in that font.
  3. Then you draw the surface just as you would an image.

Now that you know that, you can use this information to draw the next part of the HUD: the «Your Turn» indicator. Add this code at the bottom of drawHUD() :

Also add this after the call to pygame.init() :

This code creates the font, renders it in white and then draws it onto the screen. Before you try running the game, add this after the call to self.drawBoard() :

Run the program and you should get some text that says «Your Turn» at the bottom of the screen. If you look closely, you can also see the nicely textured background.

Screen Shot 2013-06-16 at 7.10.03 PM

This is great, but you still need to add the indicator after the «Your Turn» text to let the player know it’s their round.

Before you do, though, you want the game to know whose turn it is. Make sure it knows by adding this to the end of __init__ :

Now for that indicator. Add this to the end of drawHUD() :

Run the game and you will see the green score indicator. You can check that off of your list of things to do.

Next let’s add the text for each player’s score. Initialize the variables for the two scores by tacking this onto the end of __init__ :

Here you also add another variable that you will use later in this step.

Remember how to add text? You’re going to do the same type of thing you did before, but with differently sized fonts. Add this to the end of drawHUD() :

Run the game to check out your work.

Boxes8

You are now officially done with the HUD. There are just a couple more things to do on the client side, so bear with me.

Next, let’s add a very simple owner grid that contains values representing a player. These values will let you keep track of who owns which squares. You need this to color the squares properly, and to keep track of the score. Remember, the person who controls the most squares wins!

First initialize another array by adding this at the end of __init__ :

Now draw the owner grid onto the screen using the same kind of 2d-array loop that you used to loop through the lines arrays. Add this to the bottom of the class:

This method checks if it needs to draw in a given square and if it does, it draws the correct color (each player will have his or her own color).

Right now this code won’t work because you need the server to tell the client which color to draw, which you will do in the next part of the tutorial. For now, you just won’t call this method.

You have one more thing to add to the user interface: winning and losing screens. Define this last method and add it to the bottom of the class:

Screen Shot 2013-06-16 at 8.33.37 PM

Of course, there is no way yet to trigger these screens in the game. That, too, you’ll take care of in the next part of the tutorial, when you implement the server side of the game.

Remember that by adding all of these game elements now, you are making sure that the server will be able to manipulate the client however it wants. From here on out, you won’t need to make many changes to the client other than a little glue between the client and the server.

But just to make sure it works, try calling the finished() method in the last part of __init__ . You should get a game over screen that looks like the image to the right.

ragecomic

Where to Go from Here?

Here is the source code from the tutorial so far.

Congratulations! You have finished the client side of a very organized and good-looking game. This, of course, is not the end since you haven’t implemented any game logic, but excellent job on the client side!

Now you should go look at Part 2 of this tutorial, which is all about the server-side — and you’ll finally start making this game truly multiplayer!

Sign up/Sign in

With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!

Already a member of Kodeco? Sign in

Sign up/Sign in

With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!

Already a member of Kodeco? Sign in

Sign up/Sign in

With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!

Introduction to Game Development in Python (part 1)

Game development is a rewarding experience and also an exciting teaching tool. But what can you learn by coding the most boring game? This post serves as an introduction to Pygame by helping you write a simple program.

Pygame is an excellent tool for developers. It isn’t set up to be compatible with mobile devices. Also, due to Python’s nature, it isn’t great for commercial products in general; yet, its strengths include its ease of use and accessibility. The flow of the Pygame workflow is a fantastic way for beginners to learn game programming at a deeper level. It is straightforward, while also having a fair amount of depth.

Before jumping right into coding, we first need to know some basic stuff. Thus, we take this short diversion to help you better understand the purpose and basics of installing and using Pygame. You can skip this part if you are already familiar with Pygame.

GUI vs. CLI

The “normal” python programs that you write with pythons built-in functions interact with the user by print and input statements. You can output text onto the screen, and the user inputs values using the keyboard. These kinds of programs are said to have a CLI (Command Line Interface, pronounced as See-El-Eye). CLI are interfaces that heavily depend on the keyboard and are generally devoid of graphics.

On the other hand, GUI (Graphical User Interface, pronounced as Gooey) displays graphical stuff, as the name indicates. All of us are most familiar with this interface. In fact, the screen you are using to read this post is a GUI, and the machine you are running it on (Windows, Android, Ubuntu, or iOS) is also a GUI.

A CLI program is somewhat limited in terms of functionality. As some of you may have noticed, a CLI program waits for the user to input an answer using the keyboard and press enter before the application can process the information. This means a program (or game) cannot process input in real-time (as the user presses a button). CLI programs also lack the visual appeal of color and graphics. Thus, it is essential to learn to program in GUI to develop advanced games using graphics (like this game of snake).

Pygame provides functions for creating programs with GUI. Pygame functions easily take care of things like drawing graphics, playing sounds, handling mouse input, and other items necessary to develop GUI applications.

Installing Pygame

I believe it is better to learn by coding rather than just reading random articles or books. Here is the source code for a simple “Hello World” program in Pygame that we will use as a reference to learn more about Pygame. I highly encourage people to write this simple snippet of code and play around with it as we discuss different features of Pygame.

Since you are here, I assume you know at least a bit of python and what pip is. If not google it! It’s never too late to learn. If you haven’t installed Pygame yet, you can do so by running the following commands:

To check if it is properly installed, you can run an example file included in the package:

If it works, you are ready to go! Else have a look here.

The World’s Most Boring Game

Type the above code in an empty file and save it with the extension “.py”. Then go on and run the program. A window like this should appear:

Yay! You just made the world’s most boring video game! It’s just a blank screen with a “Hello World!” on the top of the window (title bar). Like a standard window, clicking on the X button on the corner of the window will end the game and make the window disappear.

Lets’s take a closer look at the program.

Setting up a Pygame Program

The first few lines of the code will be found in almost any program that uses Pygame.

The first line is a simple import statement that imports the pygame and sys modules. It enables us to use the functions present in the respective modules to develop our game. All of the Pygame functions dealing with graphics, sound, and other features that Pygame provides are in the pygame module.
The second line imports several constant variables stored in the pygame.locals module that we can use in our program.

The fourth line is the pygame init function call, which always needs to be called after importing the pygame module and before calling any other Pygame function. The init function initializes all the imported modules of Pygame before they can be used. Failure to include this in any program will always lead to errors.

The fifth line calls the set_mode function that returns a pygame.Surface object for the window (Surfaces coming up in the next post). The supplied tuple (400, 300) will return a window with a width of 400 pixels and a height of 300 pixels. Note: The set_mode function takes in a tuple as an argument. A TypeError is thrown when you try to supply two ints instead of a tuple.

Line 6 sets the caption text that will appear on the title bar of the game. It takes a string as an argument and makes the text appear as the caption:

Game Loops and Game States

The while loop in line number 7 is special. It always evaluates to True and, thus, is an infinite while loop. The loop never exits unless it encounters a break, return, or in our case, the sys.exit() call.

Most of the games developed in pygame or in general have a while loop along with a comment (good programmers always comment!) calling it the “main loop” or “game loop”, even the “main game loop”. A game loop is a loop where the code does three things:

  • Handles events
  • Updates the game state
  • Draws the game state to the screen

The game state simply refers to a set of values for all the variables in a game program. In many games, the game state includes the set of variables that track a players health and position, the health and position of any enemies, any marks/trails made by the player or enemy, the score, whose turn it is and other things that describe a precise moment in the game.

A game state can be thought of as a picture of an instance of the game. Whenever you pause a game, the game state doesn’t change, and saving a game basically saves the game state.

Since players interact with the game using events (such as a mouse click or keyboard presses), the game state is usually updated in response to such events. The game loop constantly checks and re-checks many times a second for any new events that have happened and updates the game state accordingly. In Pygame, this is done by calling the pygame.event.get() function.
The main loop also contains code that updates the game state based on which events have been created. This is termed as event handling.

pygame.event.Event Objects

Any time the user does one of the several actions such as pressing a keyboard, or moving/clicking the mouse on the program’s window, a pygame.event.Event object is created to record this “event”. We can get a list of events that have happened by calling the pygame.event.get() function.
This is precisely what we are doing in the first line inside the while loop. The pygame.event.get() function returns a list of events that have happened since the last time the function was called.

The for loop will iterate over the list of events that have happened since the last time the get function was evoked. On each iteration, a variable named event is assigned the value of the next event object in the list. The list is sequential, i.e., the order of events in the list is the order in which they happen. If no events have happened, an empty list is returned.

The QUIT Event

Event objects have an attribute (or property) called type, which tells what kind of event the object represents. Pygame has a constant variable for each of the possible types in the pygame.locals module.

The first line of this code block checks if the event type is equal to the constant QUIT. If the event object is a quit event, then the pygame.quit() and sys.exit() lines are run, closing the pygame module and closing the window. The pygame.quit() function is like the opposite of the pygame.init() function and deactivates the pygame library. The sys.exit() closes the window and terminates the program.

One should always call pygame.quit() before calling sys.exit() . In most cases, it works just fine either way, but in some cases, some bugs will crash the native python IDLE (if you are using IDLE). Also, many times I have noticed that one has to manually turn off the instance of pygame from the task manager if you don't call the pygame.quit() function at the end of your program.

Since there are no other ‘if’ statements, the code doesn’t do much of event handling, and our keyboard presses and mouse movements go unnoticed. The program then continues to the final line:

The function in the last line draws the Surface object returned by pygame.display.set_mode to the screen. Since the Surface object hasn’t changed, the same black image is redrawn to the screen each time pygame.display.update() is called. That’s the whole program. The program then returns to executing the while loop from the beginning and repeating the process described again and again till we close the window.

Conclusion

Wait! It’s just this? Probably that’s what all of you are wondering right now. The post serves as a simple and easy to grasp introduction to Pygame. Here is a link to making a game of snake in Pygame for the interested readers.

Things that you learned:

  • The basic structure of a Pygame program
  • Game Loops and game states
  • Events and event handling in Pygame

Soon, I’ll post another article that dives deeper into the objects and graphics parts of the Pygame library. Follow to get notified of the next article on Pygame. If you found this article interesting or helpful, do clap, share, and recommend it!

Читать:
Как восстановить входящие письма на электронной почте майл ру

Похожие статьи