Pygame Game Development

Adding Scoring to Our Pygame Game

Now we are going to upgrade the game from the previous section to add the scoring to the game.  The program will now count how many times you were able to hit the soccer ball. 

The program in this section adds scoring to the game. The program will now count how many times you were able to hit the soccer ball.

The program below is the same as in the previous section. It has the added feature oof scoring.

PROGRAM EXAMPLE: KEEP SCORE – HIT BALL WITH A BAT (SCORE)

Program name: pygame_hitBall_Score_NoTime.py

Image name: ball.png

# This program moves the ball randomly.
# The bat is moved by the keyboard arrow keys.
# The player moves the bat to hit the ball.
import pygame
import time
import random
#Inialize pygame module 
pygame.init()
######      SET UP       ######
# Set screen width and height.
screen_width = 800
screen_height = 600
# Define colors tuples RGB Values
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
MAGENTA = (255, 0, 255)
# Create a display surface width = 800 pixels, height = 600 pixels.
screen = pygame.display.set_mode((screen_width, screen_height))
# Give our display window a name 'HitBall_Score_NoTime'
pygame.display.set_caption('HitBall_Score_NoTime')
# time.clock() function provides the clock for app. 
clock = pygame.time.Clock()

###### Ball Image load
img = pygame.image.load('ball.png')
####### 

#######
bat_width = 30     # Set bat width and bat height
bat_height = 50
bat_move = 20  # Set bat movement in pixels each key press.
ball_width = 100

###### Define text font to display text on hitting the ball.
font = pygame.font.SysFont("arial black", 48)
text = font.render("I hit the ball", True, BLUE)
textRect = text.get_rect()
textRect.center = screen_width//2, screen_height * 0.2
############

#### Define font for "bat_out_of_screen" message asking player to Continue or Quit
fontCorQ = pygame.font.SysFont(None, 30)
######     FUNCTIONS      ######
###### Function to ask player to Continue or Quit #######
def userInput(cont_quit, color):
    contOrQuit = fontCorQ.render(cont_quit, True, color)
    screen.blit(contOrQuit, [screen_width/5, 4*screen_height/5])
#########

###### Define function for text font for number of hits #######
def score(count):			# 1)
    fontS = pygame.font.SysFont('arial black', 24) # Score Text font and size
    textS = fontS.render('Strikes ='+str(count), True, MAGENTA) #Score text color
    screen.blit(textS, (20, 0)) # Position of  score count text
    pygame.display.update()
######
    
###### Main loop ######
def mainLoop():
    running = True
    bat_out_of_screen = False
####### Initialize hit count in the game ######
    count = 0
    
###### Initialize bat position ######
    xBat = screen_width / 2
    yBat = screen_height / 2
 
    batXstep = 0  # Initialize bat move at each key press. 
    batYstep = 0 
###### Ball initial position coordinates.
    x = screen_width / 2
    y = screen_height * 0.7
######
    while running:
###### Ask player to play again or quit.
        while bat_out_of_screen == True:
            screen.fill(WHITE)
            userInput("Bat is out of window! Press Q to Quit or C to Continue", RED)
            pygame.display.update()
 
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        running = False
                        bat_out_of_screen = False
                    if event.key == pygame.K_c:
                        mainLoop()
###### Keyboard Events for bat movement.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    batXstep = -bat_move
                    batYstep = 0
                elif event.key == pygame.K_RIGHT:
                    batXstep = bat_move
                    batYstep = 0
                elif event.key == pygame.K_UP:
                    batYstep = -bat_move
                    batXstep = 0
                elif event.key == pygame.K_DOWN:
                    batYstep = bat_move
                    batXstep = 0
            if event.type == pygame.KEYUP:
                    batYstep = 0 # if the key is up, do not change bat position.
                    batXstep = 0

####### Check if bat is out of display window.
        if xBat >= screen_width - 50 or xBat < 50 or yBat >= screen_height - 50 or yBat < 50:
            bat_out_of_screen = True
 
        xBat += batXstep
        yBat += batYstep
######
        screen.fill(WHITE)
###### Draw bat rectangle and update the screen.
        pygame.draw.rect(screen, GREEN, [xBat, yBat, bat_width, bat_height])
        pygame.display.update()

###### Generate new ball location randomly for each new frame.   
        x = x + random.randint(-30, 30) 
        y = y + random.randint(-30, 30)
        
###### Check if ball reaches the screen window.
###### Back-off the ball back by 50 pixels if the ball reaches screen boundary.
        back_off = 50
        if  x > 700:
            x = x - back_off
        elif x < 0:
            x = back_off
        if y > 500:
            y = y - back_off
        elif y < 0:
            y = back_off
            
###### The blit function draws the ball image on the display at location (x, y).
        screen.blit(img, (x, y))
        pygame.display.update()
###### Call score function.               
        score(count)					#2
######
# If bat comes within 30 pixels of ball’s left x-coordinate
# AND the bat comes within ball’s left edge coordinate + ball_width, then
# test if the bat comes within 30 pixels of ball’s top y-coordinate
# AND the ball’s top edge y-coordinate +ball_width.
        if xBat > x - 30 and xBat < x + ball_width:	#3
            if yBat > y - 30 and yBat < y + ball width:
                count += 1
                screen.blit(text, textRect) 
# If Bat hit the ball, then print text "I hit the ball".
                pygame.display.update()

        clock.tick(60)
        pygame.time.delay(50)  

    pygame.quit()
    quit()
 
mainLoop()

Detailed Line-by-line Explanation of the Program:

The program is identical to the previous program with the changes to count the number of times the bat hit the ball. It also keeps the score of the number of hits.

The following are the changes:

1) Define function ‘score’.

  • We define a new function named “score” with one parameter named “count”.
  • Then, we create a new font variable named fontS (S for score) with font type arial black and font size = 24.
  • Then, we use the render() method to create a font object ‘textS’. The render() function increments the “count” parameter every time the bat hits the ball. We use MAGENTA color for the text.
  • Next, we blit the text (score) to the Screen object at location (x, y) = (0, 0)
  • Finally, we call the display.update() function to make the score text visible on the screen.
###### Print number of bat hits
def score(count):     #1)
    fontS = pygame.font.SysFont('arial black', 24) # Text font size = 24
    textS = fontS.render('Strikes ='+str(count), True, MAGENTA) # Font color=Magenta
    screen.blit(textS, (0, 0))
    pygame.display.update() 
######

2) Call the ‘score’ function defined in step 1).

###### Call score function               #2)
        score(count)

It prints the number of hits (count) at pixel location (0,0) in MAGENTA Color.

3) If the bat and the ball have a collision (we determine collision by checking if the bat is within 30 pixels of the ball), increment the “count” variable.  At the end of the game, the count variable will show how many times you were able to hit the ball.

        if xBat > x - 30 and xBat < x + 90:      #3)
            if yBat > y - 30 and yBat < y +90:
                count += 1
Verified by MonsterInsights