Tuesday, 5 March 2019

Pygame Images; a little More.....

A Little More About Pygame Images!

In previous post, we loaded and displayed images. Since we now know, how to load images, let's check out some more things that we can do with images...

In first post, we set a text caption of the window now let's set an icon of the window.

copy and paste these lines before the Game_Window= pygame.display.set_mode(winWidth,winHeight)

ship= pygame.image.load("ship.png")

Here point to remember is you need to set the icon before creating the Game_Window. A 32X32 icon is generally recommended.

Our background is a river with banks, lets add some bushes on both the sides of bank. We first need to load the image of bush.


the bush image i'm having with me is little bigger so im going to scale it down to 50X50
now let's create an array of bushes to show many bushes on the bank of river. Here we do not need to create so many images by loading images again and again. We have a method called as copy() that will create copy of surface bush. so let's create 10 bushes here add the following lines below bush definition.
while i < 10:

now we have created 10 bushes we have to display those on the river bank.
Let's reassign i to 0 and
just below blitting the background, add the following lines
while i < len(bushes)
    if i%2==0:
So now our window is going to look like

Now Let's add a ship in our river. As we already have loaded the image, we don't need to load it again.
To display the ship on the window, we'll have to blit it on the window. Add the following line before pygame.display.update().
This will show the ship on the bottom of our window. We can also see the icon in the dock in the following image that is going to show the output of whatever we have done above.

Now Let's see how to move this ship forward till the other end of river...
we only have to update the position of the ship. so before our game loop starts, define starting "y" Position of ship as
update the y value as soon as you enter the game loop as follows:
if y>0:

 And after you have blit background on the game window, now blit the ship as

At the end of game loop instead of
pygame.display.update(),call pygame.display.flip() to update the entire screen so you'll get the ship moving upwards.

You can also play with transparency of images. All you need to do is set the alpha of the surface. The alpha values range from 0 to 255. 0 is a total transparent while 255 is completely opaque.

Following is the complete code we worked till now. In this code we have a background, aset of some bushes, a moving ship an icon to window and a semitransparent image drawn on the background.

The images required are in the same gist's attachments

Now We can display images why not to use all those to create a simple game using these assets. In next post let's create some animations and have a look on events in pygame.
I make no money out of this blog. The purpose of writing this blog is only to display my skills