Написание игр на Perl - часть 1 - Прыгающий мячик

Daniel Ruoso, “Writing games in Perl - part 1 - Bouncing Ball”, public translation into Russian from English More about this translation.

See also 59 similar translations

Translate into another language.

Participants

Morris778 points
iDeBugger269 points
zibsoft100 points
And others...
Join Translated.by to translate! If you already have a Translated.by account, please sign in.
If you do not want to register an account, you can sign in with OpenID.
Pages: ← previous Ctrl next next untranslated
1 2 3 4 5

Writing games in Perl - part 1 - Bouncing Ball

Написание игр на Perl - часть 1 - Прыгающий мячик

History of edits (Latest: zibsoft 1 year, 4 months ago) §

I've been saying I will write a lengthy description of my experiments with SDL in Perl for a while, today kthakore uploaded a SDL experimental version with all the code involved in this experiments. So I decided to start, but I decided to make it a serial post. I'm still unsure about how the format will look like for the rest of the posts, but I certainly would love any comment with ideas of where I should go next.

Как я уже говорил, я напишу довольно длинное описание моих экспериментов с SDL на Perl - сегодня kthakore (см. http://search.cpan.org/~KTHAKORE/) залил экспериментальную версию SDL со всеми исходными текстами, использованными мною в экспериментах.
Так что я наконец решил начать, однако, я решил сделать это в виде серии постов.
Я пока не уверен, как будут выглядеть другие посты, и мне хотелось бы увидеть какие-нибудь комментарии с идеями об этом

History of edits (Latest: iDeBugger 1 year, 4 months ago) §

So at the first post, I'll try to make a very simple application: "bouncing ball". It is simply a ball bouncing in the screen, where the left and right cursors will accelerate them to each side.

В первом посте я попробую создать очень простое приложение: "прыгающий мячик". Это просто мячик, прыгающий по экрану, которым можно управлять нажимая кнопки ← и →

History of edits (Latest: iDeBugger 1 year, 4 months ago) §

— Неоднозначно написано - надо таки взглянуть, как он там на самом деле прыгает-то! :) Habazlam

Starting the environment

Начало разработки

History of edits (Latest: Habazlam 1 year, 4 months ago) §

Well, at first you need version 2.3_5 or greater of the SDL module available here. Building the SDL perl binding will require the headers for most of the sdl related libraries. If you're in a Debian machine (or most debian-based distros) you can simply install the regular version of the SDL perl bindings. You can also do:

Итак, для начала вам понадобится SDL версии 2.3_5 или выше, которую можно скачать здесь. Использование Perl SDL обязательно потребует заголовки большинства популярных SDL-библиотек. Если вы работаете в Debian (или Debian-подобном дистрибутиве), вы можете просто установить актуальную версию SDL Perl. Для этого выполните в консоли следующие команды:

History of edits (Latest: iDeBugger 1 year, 4 months ago) §

# apt-get build-dep libsdl-perl

# apt-get build-dep libsdl-perl

History of edits (Latest: zibsoft 1 year, 4 months ago) §

This line requires you to have a deb-src line in your /etc/apt/sources.list. Mine looks like:

Эта строка требует наличия источника обновления в файле /etc/apt/sources.list. У меня это выглядит так:

History of edits (Latest: iDeBugger 1 year, 4 months ago) §

deb-src http://ftp.br.debian.org/debian lenny main

deb-src http://ftp.br.debian.org/debian lenny main

History of edits (Latest: zibsoft 1 year, 4 months ago) §

In the case you change your sources.list file, remember you need to call apt-get update for it to get the new info.

Если вы изменили ваш source.list, то необходимо выполнить следующую команду, чтобы получить актуальный список пакетов:
# apt-get update

History of edits (Latest: iDeBugger 1 year, 4 months ago) §

After that you can simply download SDL 2.3_5 from CPAN and follow the README instructions, which basically means (note that this version is experimental so you might notice some failing tests):

Кроме этого вы можете просто скачать SDL 2.3_5 из CPAN и следовать инструкциям в файле README, там все просто описано (обратите внимание, что библиотека этой версии является пробной, поэтому некоторые тесты могут закончиться ошибкой):

History of edits (Latest: iDeBugger 1 year, 4 months ago) §

— Не совсем понял что имелось ввиду в скобках iDeBugger

— Как я понял SDL это библиотека, поэтому поправил то, что было указано в скобках. Morris

Сдается мне, что в данном случае "after that" должно переводиться как "кроме того", хотя я могу ошибаться.  Morris

— Вы правы - звучит лучше :) iDeBugger

# perl Build.PL

# perl Build.PL

History of edits (Latest: zibsoft 1 year, 4 months ago) §

# ./Build

# ./Build

History of edits (Latest: zibsoft 1 year, 4 months ago) §

# ./Build test

# ./Build test

History of edits (Latest: zibsoft 1 year, 4 months ago) §

# ./Build install

# ./Build install

History of edits (Latest: zibsoft 1 year, 4 months ago) §

You might setup a local::lib if you still want to run other applications that require the older and stable version of SDL (yes, there are a lot of API changes). I'm not a Windows user, but it has been reported that it works like charm when using Strawberry Perl.

Вы можете установить локальное окружение, если вы хотите запускать другие приложения, которые требуют старшую и более стабильную версию SDL (да, API сильно меняется). Я не пользователь Windows, но мне сообщили, что иначе не работает так, как положено Strawberry Perl.

History of edits (Latest: iDeBugger 1 year, 4 months ago) §

— Можеть правильней "установить библиотеку локально"? iDeBugger

If everything is fine, you should be able to get "2.35" when you do:

Если все в порядке, то вы получите ответ "2.35" на введенную команду:

History of edits (Latest: Morris 1 year, 4 months ago) §

$ perl -MSDL -E 'say $SDL::VERSION'

$ perl -MSDL -E 'say $SDL::VERSION'

History of edits (Latest: zibsoft 1 year, 4 months ago) §

You might always get into #sdl@irc.perl.org if you run into trouble.

Не забывайте, что всегда можно написать по адресу #sdl@irc.perl.org если у вас возникли трудности с запуском.

History of edits (Latest: Morris 1 year, 4 months ago) §

The way I write games

Как я пишу игры

History of edits (Latest: Morris 1 year, 4 months ago) §

Comment was deleted

Alright, before getting into the technicalities of how to write a game with SDL in Perl, let's think a bit on the mechanics of how a game works.

Окей, прежде чем копаться в технических аспектах создания игры с SDL на Perl, давайте немного подумаем о механике работы игры.

History of edits (Latest: iDeBugger 1 year, 4 months ago) §

The first thing to realize is that a game needs to simulate some universe, and that this universe needs to have some universal rules like the physics you apply. For instance, it is very important that you decide, from the beggining, if you're going to have gravity in your game.

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

History of edits (Latest: iDeBugger 1 year, 4 months ago) §

The second thing to realize is that, even if we have the impression that the time is a continuum, time is actually a sequence of events, like the shutter of a camera in burst mode (okay, for the not interested in photography, think in stop motion). That basically

Вторая вещь, которую нужно понять, что несмотря на то, что по нашим ощущениям время непрерывно, тут время это цепочка событий, подобная цепочке кадров снятых фотоаппаратом при серийной съемке (ну хорошо, те, кто не интересуется фотографией, пусть представят покадровую съемку).

History of edits (Latest: Morris 1 year, 4 months ago) §

— %) Временной континуум iDeBugger

— Пришлось "облитературить" оригинал. Morris

means: in frame A the ball was at position 10,10 and in frame B it was at 20,30. There's no in-between, you don't have to worry about it. You might be wondering if a collision might be lost in that move, but the point is, if the machine can't evaluate enough frames per second as to avoid that, it probably wouldn't be able to evaluate a more ellaborated calculation of the tragetories to see if they would have collided.

По сути это означает, что: в кадре A мяч находился на позиции 10,10, а в кадре B находился на 20,30. То, что между кадрами нет промежуточного состояния вас не должно волновать. Возможно вы заинтересуетесь, не затерялось ли в данном движении столкновение, но дело в том, что если машина не может предоставить достаточного количества кадров для выяснения этого, то она, вероятно, не сможет и более точно рассчитать траекторию, чтобы узнать был ли удар.

History of edits (Latest: Morris 1 year, 4 months ago) §

— Нужно вычитать данный абзац. Возможно смысл немного отличается. Morris

This provides an important simplification on how to think your game model. In this first example I'm going to overlook the modelling for interaction with different objects, since we have just a bouncing ball.

Это значительно упрощает вам обдумывание вашей игровой модели. В этом первом примере я не буду рассматривать моделирование взаимодействия с различными объектами, так как у нас всего лишь прыгающий мячик.

History of edits (Latest: Morris 1 year, 4 months ago) §

One last thing before we go on. You might be tempted to use pixels as your measuring unit, there's one important aspect to keep in mind. A Pixel is an integer value, which means that you'll need to do roundings for each frame. And if you need to store it as a integer value, you're going to accumulate imprecision, which might lead to weird effects, specially when the fps rate changes dramatically. My suggestion is to stick with the good old international measuring system and just use meters, a simple calculation can covert from/to pixels.

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

History of edits (Latest: Morris 1 year, 4 months ago) §

package Util;

package Util;

History of edits (Latest: zibsoft 1 year, 4 months ago) §

use strict;

use strict;

History of edits (Latest: zibsoft 1 year, 4 months ago) §

use warnings;

use warnings;

History of edits (Latest: zibsoft 1 year, 4 months ago) §

our $DPI = 96; # I think there's a sane way to fetch this value

our $DPI = 96; # Я думаю есть более правильные способы получения этого значения

History of edits (Latest: Morris 1 year, 4 months ago) §

sub m2px { int(((shift) * ($DPI / 0.0254)) + 0.5) }

sub m2px { int(((shift) * ($DPI / 0.0254)) + 0.5) }

History of edits (Latest: Morris 1 year, 4 months ago) §

sub px2m { (shift) / ($DPI / .0254) }

sub px2m { (shift) / ($DPI / .0254) }

History of edits (Latest: Morris 1 year, 4 months ago) §

Modelling the ball

Моделирование мяча

History of edits (Latest: Morris 1 year, 4 months ago) §

I think there probably isn't a better fit for Object Orientation than games, since you're actually dealing with simulated objects, and the most obvious choice is to use object orientation to work with it. So that's the attributes I can think right now to our object.

package Ball;

package Ball;

History of edits (Latest: Morris 1 year, 4 months ago) §

use Moose;

use Moose;

History of edits (Latest: Morris 1 year, 4 months ago) §

use constant g => 1.5;

use constant g => 1.5;

History of edits (Latest: Morris 1 year, 4 months ago) §

use Util;

use Util;

History of edits (Latest: Morris 1 year, 4 months ago) §
Pages: ← previous Ctrl next next untranslated
1 2 3 4 5