Sunday, July 3, 2011

Adding more options in Game


In my previous post I have explained you how I set up my game window. I had set the car also. Now I want to add enemies. For that I want to add the enemy cars first. Using the statement,

enemies_im=pygame.image.load("enemies.gif")

I also added the energy symbols also in the above method. Now I want to display them in the screen. For that I use a random function and that’s why I imported random.

for i in range(15):
    x=random.randrange(0,400)
    y=random.randrange(0,440)
    enemies.append([x,y])

The above code creates a list that has the enemy cars in random positions. I also set another list of energy symbols in the same way.

screen.blit(road, [0,0])

The above code is used to display the road image in the position x=0 and y=0 in the screen.

screen.blit(car, [x_coord,y_coord])

This code is used to display the car in the middle bottom of the screen.

if enemies[i][1] > 480:
            y=random.randrange(-480,-10)
            enemies[i][1]=y
            x=random.randrange(0,400)
            enemies[i][0]=x

This code helps to redraw the enemies/energy from the top of the screen when they hit the car. So that the user gets a nice feeling that he hit the objects.

Now we want to calculate the score by recognizing the hits. The below code is used for that.

if carrect.collidepoint(enemies[i][0], enemies[i][1]):
            score = score – 3

We can also play some music in background or play music when objects hits.

enemyhit = pygame.mixer.Sound("hit.wav")
enemyhit.play()

The above code is used for that purpose.

We can also display the scoreboard that updates lively.

screen.blit(scoreboard.render("Score " + str(score) , 4, (255,255,255)) , [40,40])

The above code is used for that. The score is printed in white color (that’s why the RGB code 255,255,255 is passed as a parameter). The 40,40 is the position where the score is to be displayed.

We can further include some more actions to reduce the bugs. We can include a sys.exit() to close the window when the user click on the close button of game. We can also set the conditions where the user wins or loses the game.

You can download the source code and can run/edit the code. Click here to download.



















Thanks

AJAY

No comments:

Post a Comment