Create a Ping Pong game using Python
Create a Ping Pong game using Python
Ping Pong is one of the maximum punctual arcade laptop games, first introduced in 1972 through Atari. It is a -participant sport depending on table tennis. The sport highlights honest 2D illustrations. It accommodates of oars used to go back a bobbing ball backward and forward throughout the screen. The rating is stored through the numbers at the best factor of the screen. With the assist of this article we're going to make the game using pygame and numpy library.
Use of pygame
Game programming is very rewarding nowadays. It can also be used in advertising and as a teaching tool too. Game development includes many aspects such as mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game programming is done in pygame. Pygame is one of the best modules for doing so.
Pygame requires Python. Fisrt thing is that you should have python installed in your system, you can download it from python.org. Use python 3.6.1 or greater, because it is easier for beginners and works faster.
The best way to install pygame. Pip tool is used by python to install packages.
Note:- Pip comes with python in recent versions.
We use the –user flag to tell it to install into the home directory, rather than globally.
python3 -m pip install -U pygame --user
To see if it works, run one of the included examples:
python3 -m pygame.examples.aliens
If it works, we are ready to go!
Create a template, where we create a blank pop up window
Simple PyGame Application
Below, there is a very simple app is demonstrated which is built using PyGame pipleline.
import pygame pygame.init() screen = pygame.display.set_mode((400, 300)) done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pygame.display.flip()
To uderstand the code more efficiently there are some brief poitns related to this:
import pygame – To acess PyGame framework this line is needed.
pygame.init() – All the modules required for PyGame are initialized here.
pygame.display.set_mode((width, height)) –The desired size window will be launched. The graphical operations are performed on this returned surface value.
pygame.event.get() – This empties the event queue. On not calling this, the windows messages will start to gather up on compile and your game will become unresponsive in your operating system.
pygame.QUIT – This is often the event type that's fired once you click on the close button within the corner of the window.
pygame.display.flip() – PyGame is double-buffered so this swaps the buffers. All you would like to understand is that this call is required so as for any updates that you simply make to the game screen to appear .
Nopw lets look at the output of the above code. It looks something like this:
NOW WE CAN START WITH OUR PING PONG GAME:
FOLLOWING IS THE PROCESS:
1) Fill background
import pygame, sys # General setup pygame.init() clock = pygame.time.Clock() # Setting up the main window screen_width = 1280 screen_height = 960 screen = pygame.display.set_mode((screen_width,screen_height)) pygame.display.set_caption('Pong') while True: #Handling input for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Updating the window pygame.display.flip() clock.tick(60)
The above code will set up our pong game.
2) Create objects: ball and paddles
Here we will create the objects required in the game like a ball and paddle
this will be the ball
This will be the paddle.
3) What is AI ?
AI or Artificial Intelligence is a major application for python language and enables computers to perform intelligent tasks like humans. For example in the upcoming game project we are going to use AI to make our computer as a opponent for the ping pong game.
4) What is blitting?
To “blit” is to copy bits from one part of a computer’s graphical memory to another part. In this technique the pixels of an image are directly dealt, and draws them directly to the screen, which makes it a very fast rendering technique that’s often perfect for fast-paced 2D action games.
when drawing a circle:
circle = pygame.draw.circle(screen, (0, 0, 0), (100, 100), 15, 1)
I don’t need to do screen.blit(circle), but when displaying text:
text = font.render("TEXT", 1, (10, 10, 10))
textpos = text.get_rect()
textpos.centerx = screen.get_rect().centerx
Without blit, the text won’t appear.
5) Make the ball move
Here we will ad animation to our Balls
import pygame, sys def ball_animation(): global ball_speed_x, ball_speed_y ball.x += ball_speed_x ball.y += ball_speed_y if ball.top <= 0 or ball.bottom >= screen_height: ball_speed_y *= -1 if ball.left <= 0 or ball.right >= screen_width: ball_speed_x *= -1 if ball.colliderect(player) or ball.colliderect(opponent): ball_speed_x *= -1 # General setup pygame.init() clock = pygame.time.Clock() # Main Window screen_width = 1280 screen_height = 960 screen = pygame.display.set_mode((screen_width,screen_height)) pygame.display.set_caption(‘Pong’) # Colors light_grey = (200,200,200) bg_color = pygame.Color(‘grey12’) # Game Rectangles ball = pygame.Rect(screen_width / 2 – 15, screen_height / 2 – 15, 30, 30) player = pygame.Rect(screen_width – 20, screen_height / 2 – 70, 10,140) opponent = pygame.Rect(10, screen_height / 2 – 70, 10,140) # Game Variables ball_speed_x = 7 ball_speed_y = 7 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Game logic ball_animation() screen.fill(bg_color) pygame.draw.rect(screen, light_grey, player) pygame.draw.rect(screen, light_grey, opponent) pygame.draw.ellipse(screen, light_grey, ball) pygame.draw.aaline(screen, light_grey, (screen_width / 2, 0),(screen_width / 2, screen_height)) pygame.display.flip() clock.tick(60)
6) Player movement
Now we will assign movement to our existing Player1 and Player2
class Player(Block): def __init__(self,path,x_pos,y_pos,speed): super().__init__(path,x_pos,y_pos) self.speed = speed self.movement = 0 def screen_constrain(self): if self.rect.top <= 0: self.rect.top = 0 if self.rect.bottom >= screen_height: self.rect.bottom = screen_height def update(self,ball_group): self.rect.y += self.movement self.screen_constrain()
7) Scoring system
We will implement a scoring system where the compiler will count the points scored
#Display scores: font = pygame.font.Font(None, 74) text = font.render(str(scoreA), 1, WHITE) screen.blit(text, (250,10)) text = font.render(str(scoreB), 1, WHITE) screen.blit(text, (420,10))
8) AI function
The function of Artificial Intelligence[AI] in this game is to keep a counter when we score points and to update the score board
Another function is to reset the game when there is collision
This is how you will define it
def collisions(self): if self.rect.top <= 0 or self.rect.bottom >= screen_height: pygame.mixer.Sound.play(plob_sound) self.speed_y *= -1
With this we are ready with our ping pong game!