Python Pygame module and universal framework for a game construct

By creating a simple dice game to explore Python. Now is to make your own game from time zero.

In my first article in this series, I have to explain how to use Python to create a simple, text-based dice game. This time, I will show how to use Python Pygame module to create a graphical game. It will need to get a few articles to really make something of the game, but by the end of this series, you will better understand how to find and learn new Python module and how to build an application on the basis of its program.

Before you start, you have to install  Pygame .

Install the new Python module

There are several ways to install Python modules, but the two most common are:

  • Your release a software repository
  • Using Python package manager pip

Both methods work well, and each has its own set of advantages. If you're on Linux or BSD developers can use your distribution's software repository to automatically and timely updates.

However, the use of Python's built-in package manager can give you the ability to control the time of the update module. Moreover, it is not specific to the operating system, which means that, even when you're not in your common development machine, you can use it. pip The other advantage is to allow local installation module, if you do not have administrative rights on the computer you are using, which is useful.

Use pip

If Python and Python3 are installed on your system, you want to use the command is likely to be  pip3, which is used to distinguish between Python 2.x of  pip command. If you are not sure, first try  pip3.

pip Some commands, like most Linux package manager to work the same. You can use the  search search Python module, then  install install them. If you do not have administrative rights on the computer you are using to install the software, you can use the  --user option to install only the modules to your home directory.

1.  `$ pip3 search pygame`
2.  `[...]`
3.  `Pygame  (1.9.3)  -  Python  Game  Development`
4.  `sge-pygame (1.5)  - A 2-D game engine for  Python`
5.  `pygame_camera (0.1.1) - A Camera lib for  PyGame`
6.  `pygame_cffi (0.2.1) - A cffi-based SDL wrapper that copies the pygame API.`
7.  `[...]`
8.  `$ pip3 install Pygame  --user`

Pygame is a Python module, which means that it is just a set of Python can be used in your program library. In other words, it's not like a IDLE or Ninja-IDE allows the same program you started.

Pygame Getting Started

A video game requires a background setting: The story takes place in. In Python, there are two different ways to create your background story:

  • Set one context color
  • Set a background image

Your background is just a picture or a color. Your video game character can not interact with the stuff in the background, so do not be too important to put some things behind. It is just set decoration.

Set your Pygame script

To start a new Pygame project, first create a folder on your computer. All game files are placed in this directory. To run all the files inside your project folder maintaining the required game is extremely important.

A Python script file types, your name, and you want to use the license to start. Use an open-source license, so your friends can improve your game and share their changes with you:


1.  `#!/usr/bin/env python3`
2.  `# by Seth  Kenlon`

4.  `##  GPLv3`
5.  `#  This program is free software: you can redistribute it and/or`
6.  `# modify it under the terms of the GNU General  Public  License  as`
7.  `# published by the Free  Software  Foundation, either version 3 of the`
8.  `#  License,  or  (at your option) any later version.`
9.  `#`
10.  `#  This program is distributed in the hope that it will be useful, but`
11.  `# WITHOUT ANY WARRANTY; without even the implied warranty of`
12.  `# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU`
13.  `#  General  Public  License  for  more details.`
14.  `#`
15.  `#  You should have received a copy of the GNU General  Public  License`
16.  `# along with  this program.  If  not, see <http://www.gnu.org/licenses/>.`

Then, you tell Python module that you want to use. Some modules are common Python library, of course, you want to include a Pygame module you just installed.


1.  `import pygame#  加载 pygame 关键字`
2.  `import sys #  让python 使用你的文件系统`
3.  `import os#  帮助 python 识别你的操作系统`

Because you will use this script file to do a lot of work, divided into paragraphs in the document it is helpful, so that you know where to put the code. You can use these block comments to do, these notes only when looking at your source code files visible. Create three blocks in your code.


1.  `'''`
2.  `Objects`
3.  `'''`

5.  `#  在这里放置  Python  类和函数`

7.  `'''`
8.  `Setup`
9.  `'''`

11.  `#  在这里放置一次性的运行代码`

13.  `'''`
14.  `Main Loop`
15.  `'''`

17.  `#  在这里放置游戏的循环代码指令`

Next, set the window size for your game. Note that not everyone has a large computer screen, so it's best to use a suitable screen size of most people's computers.

Here's a way to toggle full screen mode, many modern video games will do so, however, because you are just beginning, simplicity can be only one size.


1.  `'''`
2.  `Setup`
3.  `'''`
4.  `worldx =  960`
5.  `worldy =  720`

Before using Pygame engine in a script, you need some basic settings. You have to set the frame rate, its internal clock to start, then start ( init) Pygame.


1.  `fps =  40 #  帧频`
2.  `ani =  4  #  动画循环`
3.  `clock = pygame.time.Clock()`
4.  `pygame.init()`

Now you can set your background.

Set Background

Before you continue, open a graphics application, create a background for your game world. In your project directory  images folder to save it inside  stage.png .

Here are some free graphics applications you can use.

  • Krita  is a professional graphics material simulator that can be used to create pretty pictures. If you are very interested in creating video games artwork, you can even purchase a series of games works of art tutorial .
  • Pinta  is a basic, easy-to-learn drawing application.
  • Inkscape  is a vector graphics applications. It is used to draw a shape, lines, Bezier curves and spline curves.

You do not have to be complex images, you can go back and change it later. Once you have it, add the code in the Setup section of your file:

1.  `world    = pygame.display.set_mode([worldx,worldy])`
2.  `backdrop = pygame.image.load(os.path.join('images','stage.png').convert())`
3.  `backdropbox = world.get_rect()`

If you only use one color to fill the background of your game, you need to do is:


1.  `world = pygame.display.set_mode([worldx,worldy])`

You must also define the color to use. In your Setup section, use red, green, and blue values ​​(RGB) to create a definition of some color.


1.  `'''`
2.  `Setup`
3.  `'''`

5.  `BLUE  =  (25,25,200)`
6.  `BLACK =  (23,23,23  )`
7.  `WHITE =  (254,254,254)`

Thus, in theory, you can start your game. The problem is, it may last only for a millisecond.

To prove this point, save your file  your-name_game.py(replace with your real name  your-name). Then you start the game.

If you are using IDLE, to run your game by choosing from the "Run" menu "Run Module".

If you are using Ninja, click the "Run file" button on the left button bar.

image

You can also run a Python script directly from a Unix terminal or a Windows command prompt.


1.  `$ python3 ./your-name_game.py`

If you are using Windows, use this command:


1.  `py.exe your-name_game.py`

Start it, but do not expect a lot, because now your game lasts only a few milliseconds. You can fix it in the next section.

cycle

Unless otherwise indicated, a Python script to run once and only once. Recent computer speed is very fast, so your Python script run time will be less than 1 second.

To force you to be in the game long enough to open and active state to let people see it (not to mention play it), use a  while loop. To make your game save is open, you can set a variable to some values, and then tell a  whileloop as long as the variable Leave unchanged the cycle has been saved.

This is often referred to as a "main loop", you can use the term  main as your variable. Anywhere in your Setup section to add code:


1.  `main =  True`

During the main loop, using Pygame keyword to check whether a key on the keyboard has been pressed or released. Add the code to your main loop section:


1.  `'''`
2.  `Main loop`
3.  `'''`
4.  `while main ==  True:`
5.  `for event in pygame.event.get():`
6.  `if event.type == pygame.QUIT:`
7.  `            pygame.quit(); sys.exit()`
8.  `main =  False`

10.  `if event.type == pygame.KEYDOWN:`
11.  `if event.key == ord('q'):`
12.  `                pygame.quit()`
13.  `                sys.exit()`
14.  `main =  False`

Also in your cycle, you refresh the background of the world.

If you use a picture as the background:

1.  `world.blit(backdrop, backdropbox)`

If you use one color as the background:


1.  `world.fill(BLUE)`

Finally, tell Pygame to refresh all content on the screen, and to advance the internal clock of the game.


1.  `    pygame.display.flip()`
2.  `    clock.tick(fps)`

Save your file, run it again to see the most boring game you've ever created.

Out of the game, on your keyboard, press the  q key.

We will certainly encounter many difficulties when learning python, as well as the pursuit of new technologies, here's what we recommend learning Python buckle qun: 784758214, here is the python learner gathering place! ! At the same time, he was a senior development engineer python, python script from basic to web development, reptiles, django, data mining and other projects to combat zero-based data are finishing. Given to every little python partner! Daily share some methods of learning and the need to pay attention to small details

Click: Python exchange technology sharing

Guess you like

Origin blog.csdn.net/zhizhun88/article/details/90707068