Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to place a platform in a Pygame game

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to place the platform in the Pygame game, many novices are not very clear about this. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.

In Pygame, the platform itself is a leprechaun, just like your playable leprechaun. This is important because there is an object platform that makes it easier for your player goblins to interact with it.

There are two main steps in creating a platform. First, you must write code for the object, and then you must map out where you want the object to appear.

Coding platform object

To build a platform object, you create a class called Platform. It is a leprechaun, just like your Player goblin, with many of the same attributes.

Your Platform class needs to know a lot about platform types, where it should appear in the game world, what images it should contain, and so on. Much of this information may not exist yet, depending on how much you plan for your game, but it doesn't matter. Just as you didn't tell your players how fast goblins move until the end of the article on moving your game characters, you don't have to tell Platform everything in advance.

Near the beginning of the script you wrote in this series, create a new class. In this code example, the first three lines are used to illustrate the context, so add the code below the comment:

The new import pygameimport sysimport os## code is as follows: class Platform (pygame.sprite.Sprite): # x location, y location, img width, img height, img file def _ _ init__ (self,xloc,yloc,imgw,imgh,img): pygame.sprite.Sprite.__init__ (self) self.image = pygame.image.load (os.path.join ('images') Img) .convert () self.image.convert_alpha () self.image.set_colorkey (ALPHA) self.rect = self.image.get_rect () self.rect.y = yloc self.rect.x = xloc

When called, this class creates an on-screen object at some X and Y position, with a certain width and height, and uses an image as a texture. This is very similar to how to draw a player or enemy on the screen.

Type of platform

The next step is to map out where your platform needs to appear.

Ceramic tile mode

There are several different ways to implement a platform game world. In the original horizontal roller games, such as Mario Super Brothers and Sonic the hedgehog, the technique was to use the "tile" approach, that is, there were several blocks representing the ground and various platforms. and these blocks are reused to make a level. You can only have 8 or 12 different blocks, and you can arrange them on the screen to create the ground, floating platform, and everything else you need in the game. Some people find that this is the easiest way to make a game, because you only need to make (or download) a small group of level material to create many different levels. However, the code here requires a little mathematical knowledge.

SuperTux, a tile-based computer game.

Manual drawing mode

Another way is to treat each material as a whole image. If you like to create material for the game world, you will spend a lot of time building every part of the game world with graphical applications. This approach does not require much mathematical knowledge, because all platforms are holistic and complete objects, and you just need to tell Python where to put them on the screen.

Each method has its advantages and disadvantages, and the code is slightly different depending on how you choose to use it. I will cover these two aspects, so you can use one or the other, or even a mixture of the two, in your project.

Level drawing

In general, mapping your game world is an important part of level design and game programming. It requires mathematical knowledge, but it's not too difficult, and Python is good at math, which will help.

You may find it useful to design on paper first. Take a sheet of paper and draw a box to represent your game form. Draw the platform in the box and mark its X and Y coordinates for each platform, as well as its width and height. The actual position in the box doesn't have to be accurate, you just have to keep the numbers reasonable. For example, suppose your screen is 720 pixels wide, then you can't put 8 pieces of 100 pixel platform on a screen.

Of course, not all platforms in your game have to be contained in a screen-sized box, because your game will scroll as your player walks. So, you can continue to draw your game world to the right side of the screen until the level is over.

If you prefer precision, you can use checkered paper. This is especially useful when designing a tile game because each square can represent a tile.

An example of a level map.

Coordinate system

You may have studied the Cartesian coordinate system in school. What you learn also applies to Pygame, except that in Pygame, the origin of the coordinate system of your game world is placed in the upper left corner of your screen instead of in the middle, and the coordinates you used in geography class are in the middle.

Example of coordinates in Pygame.

The X axis starts at the leftmost 0 and increases to the right. The Y axis starts at 0 at the top of the screen and extends downward.

Picture size

There is no point in drawing a game world if you don't know how big your players, enemies, and platforms are. You can find the size of your platform or tile in the graphics program. For example, in Krita, click the Image menu and select Properties. You can find its size at the top of the Properties window.

Alternatively, you can create a simple Python script to tell you the size of an image. Open a new text file and enter the code into it:

#! / usr/bin/env python3 from PIL import Imageimport os.pathimport sys if len (sys.argv) > 1: print (sys.argv [1]) else: sys.exit ('Syntax: identify.py [filename]') pic = sys.argv [1] dim = Image.open (pic) X = dim.size [0] Y = dim.size [1] print (XMagy)

Save the text file as identify.py.

To use this script, you must install some additional Python modules that contain the new keywords used in the script:

$pip3 install Pillow-user

Once installed, run this script in your game project directory:

$python3. / identify.py images/ground.png (1080, 97)

In this example, the size of the graphics for the ground platform is 1080 pixels wide and 97 pixels high.

Platform block

If you choose to draw each footage individually, you must create several platforms and other elements that you want to insert into your game world, each in its own file. In other words, you should have a file for each material, like this:

One drawing file per object.

You can reuse each platform as many times as you want, as long as you make sure that each file contains only one platform. You can't use one file to contain all the material, like this:

Your level cannot be a graphics file.

When you're done, you may want your game to look like this, but if you create your levels in a large file, you have no way to distinguish a platform from the background, so either draw objects in their own files, or cut them out of a larger file and save them as separate copies.

Note: like your other material, you can use GIMP, Krita, MyPaint, or Inkscape to create your game material.

The platform appears on the screen at the beginning of each level, so you have to add a platform function to your Level class. The exception here is the ground platform, which is so important that it should have its own group. By thinking of the ground as a special type of platform, you can choose whether it is rolling or whether it can stand on it, while other platforms can float on it. It's up to you.

Add these two functions to your Level class:

Def ground (lvl,x,y,w,h): ground_list = pygame.sprite.Group () if lvl = = 1: ground = Platform 'block-ground.png') ground_list.add (ground) if lvl = 2: print ("Level" + str (lvl)) return ground_list def platform (lvl): plat_list = pygame.sprite.Group () if lvl = = 1: plat = Platform (200,worldy-97-128,285) plat_list.add (plat) plat = Platform 'block-small.png') plat_list.add (plat) if lvl = 2: print ("Level" + str (lvl)) return plat_list

The ground function requires an X and Y position so that Pygame knows where to place the ground platform. It also needs to know the width and height of the platform so that Pygame knows how far the ground extends in each direction. This function uses your Platform class to generate an on-screen object and then adds the object to the ground_list group.

The platform function is essentially the same, except that it has more platforms. In this example, there are only two platforms, but you can have as many as you want. After entering one platform, you must add it to plat_list before listing another. If you do not add a platform to the group, it will not appear in your game.

Tip: it's hard to imagine that 0 in your game world is at the top, because what happens in the real world is the opposite; when estimating how tall you are, you don't measure yourself from top to bottom, but from foot to top.

If it is easier for you to build your game world from the ground, it may be helpful to represent the Y-axis value as a negative number. For example, you know that the bottom of your game world is the worldy value. So worldy minus the height of the ground (97 in this example) is where your player normally stands. If your character is 64 pixels tall, the ground minus 128 is exactly twice as tall as your player. In fact, a platform placed at 128 pixels is about two stories high relative to your player. A platform is higher than a three-story building at-320. Wait.

As you may know by now, your classes and functions are worthless if you don't use them. Add this code to your settings section (* lines are just context, so add two lines):

Enemy_list = Level.bad (1, eloc) ground_list = Level.ground plat_list = Level.platform (1)

And add these lines to your main loop (again, the * lines are for context only):

Enemy_list.draw (world) # refresh enemy ground_list.draw (world) # refresh ground plat_list.draw (world) # refresh platform tile platform

The tile game world is easier to make because you only need to draw a few blocks in front and you can use them again and again to create each platform in the game. There is even a set of tiles for you to use on sites like OpenGameArt.org.

The Platform class is the same as the class in the previous section.

Ground and platform are in the Level class, however, you must use loops to calculate how many blocks are used to create each platform.

If you plan to have a solid ground in your game world, this ground is very simple. You just need to "clone" your floor tiles from one side of the window to the other. For example, you can create a list of X and Y values to specify where each tile should be placed, and then use a loop to get each value and draw each tile. This is just an example, so don't add this to your code:

# Do not add this to your codegloc = [0people 656 128656192656256656320656384656]

However, if you look carefully, you can see that all the Y values are the same, and the X value continues to increase in increments of 64-this is the size of the tiles. This kind of repetition is precise and good at computers, so you can use a little bit of mathematical logic to get the computer to do all the calculations for you:

Add these to the settings section of your script:

Gloc = [] tx = 64ty = 64 i=0while I 0: self.frame + = 1 if self.frame > ani*3: self.frame = 0 self.image = self.images [(self.frame//ani) + 4] # collisions enemy_hit_list = pygame.sprite.spritecollide (self, enemy_list False) for enemy in enemy_hit_list: self.health-= 1 print (self.health) ground_hit_list = pygame.sprite.spritecollide (self, ground_list) False) for g in ground_hit_list: self.health-= 1 print (self.health) class Enemy (pygame.sprite.Sprite):''Spawn an enemy' def _ init__ (self,x,y,img): pygame.sprite.Sprite.__init__ (self) self.image = pygame.image.load (os.path.join ('images') Img) # self.image.convert_alpha () # self.image.set_colorkey (ALPHA) self.rect = self.image.get_rect () self.rect.x = x self.rect.y = y self.counter = 0 def move (self):''enemy movement' distance = 80 speed = 8 If self.counter > = 0 and self.counter = distance and self.counter

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report