Saturday, 18 November 2017

Collision Detection and adding in the Score!

In this post, we will work on collision detection. This means that we need to figure out a way for game to know when the block collides with the players paddle and in turn, bounce the ball back up and increment their score.

First we need to add the line of code in of initialising score to 0. You can place this just underneath the setting up of the player's paddle.

 Near the end of the while loop, below windowSurface.fill(WHITE), this is where you add in the collision detection. This is done with one nested if statement. This is done by calling the colliderect on the player object passing the block object in as the argument. If there is an overlap between player and block the method returns True.
Once in this if statement, you need to find out if moveUp is set to true and if so, set it to false and moveDown to true. Then add the MOVESPEED to the block.bottom. Else, set moveUp to true and moveDown to false and subtract the MOVESPEED from the block.bottom. This means that when the block collides with the paddle the block will bounce back up the window. Also, add 1 point to the score. You can increment the score by whatever number to want but for this blog I am going to keep it simple and leave it at one point.

Before adding the score to the screen, we need to assign a variable to the font type. You can add this in up the top where you have set up the pygame. We use the pygame.font.SysFont method and we want to set the first parameter to none so we get the default font and then the second parameter to the size we want the font to be. Around 48 should do perfectly.



To add the score to the screen, it is a simple line of code using the drawText method. The first parameter is the text you want shown, the second is the type of font which we saved in a variable called font, the third is the variable windowSurface so that it knows where to draw it. Then the fourth and fifth ones are where you want to place it on the screen with the x and y position.







No comments:

Post a Comment