Explore my code experiments and prototypes:Â
💻 Python code samples: https://pyscript.com/@taraneh_y
🎮 Java Script code samples: https://codepen.io/tar4n3Â
Here’s a breakdown of one of my Python projects that I created to improve my coding skills. This Pong vs AI game is built using Pygame and simulates a simple match between a player-controlled paddle and an AI opponent. It helped me explore game mechanics, handling user input, and implementing basic AI behavior. Below, I’ll walk through the key parts of the code and explain how everything comes together.
Pong is one of the simplest yet classic games in history, and today, we’re going to build a Pong game with AI using Python and Pygame. In this version, you (Player 1) control a paddle manually, while the AI (Player 2) controls the other paddle. The goal is to hit the ball back and forth and score points when the opponent misses.Â
First, we import the necessary libraries:
pygame is used to build the game.
pygame.locals provides constants like QUIT, KEYDOWN, etc.
sys.exit() allows us to close the game window when needed.
random can be used to introduce randomness if required.
pygame.init() initializes all the necessary modules for Pygame.
display.set_mode((640, 480)) creates a window with a resolution of 640x480 pixels.
set_caption("Pong Game") sets the title of the game window.
Paddles (bar1, bar2) are rectangles with (10px width, 50px height).
Ball (circle) is a 15px green circle with a transparent background.
Player controls (UP & DOWN keys) move the paddle.
Pressing a key moves the paddle, releasing it stops movement.
AI paddle moves automatically based on ball position (next section).
AI paddle tracks the ball’s y position and moves up/down to block it.
This makes the AI "smart" but still beatable.
Ball moves at its defined speed (speed_x, speed_y).
If the ball hits a paddle, it bounces back (speed_x = -speed_x).
If the ball goes off the left side, AI scores.
If the ball goes off the right side, the Player scores.
The ball resets to the center after scoring.
Draws paddles, ball, middle line, and borders.
pygame.display.update() refreshes the screen every frame.