Ping pong python pygame

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Implementation of classic ping-pong game using PyGame.

License

mementomorri/pygame_ping_pong

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

screenshot of the game

Implementation of classic ping-pong game using PyGame.

To this game via source code basic requirement would be to have a Python interpreter on your local machine and meet a short list of packages required:

  • PyGame — obviously to run the game;
  • Pillow — to read byte string and convert it to Surface object.

Both can be installed with requirements.txt via python package manager pip . A more detailed description of package installation process is explained in the Dependencies installation section.
The game is well tested with Python 3.11 and Pygame 2.4.8, so it’s recommended to use this versions of packages and Python itself.

There is two ways of running the game:

To run it as a script, all the requirements should be met and current working directory should be ping-pong , then the run will succeed and game will launch. Here is an example of running the game as a script:

A more simple approach is to use executable file that bundled with all packages and tools required to run the game. There is no need to trouble your self with package management, just run executable file as usual and enjoy the game of ping pong.

Installing dependencies with package manager pip is done easily with requirements.txt . To use it as intended create venv and run command below:

$ (venv) pip install -r requirements.txt

When packages are installed command prompt will be returned to you, and you’ll be able to run script with your local Python interpreter. Here is a table of all packages necessary:

Package Version
pygame 2.4.0
Pillow 9.5.0

Build executable from source code

If you’re done playing this simple version of ping-pong and want to add some features, change sprites or add some more content, there is a way to re-build executable file to distribute your version of game. One way is to use Pyinstaller as a tool to convert your modified code to and executable. There is a main.spec file at ping-pong directory for such a case, you can use it, here is an example how:

$ (venv) pyinstaller main.spec

As a result, Pyinstaller will produce an executable named ping-pong at dist folder. Game uses images at img folder, so if you change images, you should re-produce byte-strings with img_to_str function implemented at encode_imgs.py and use it in main.py script.

About

Implementation of classic ping-pong game using PyGame.

Источник

Пинг понг на Python PyGame

Python PyGame как сделать игру пинг понг

В этой статье мы разберём как создать игру Пинг понг на библиотеки PyGame для языка программирования Python, думаю будет очень интересно.

Также перед прочтением этой статья настоятельно рекомендую почитать мой цикл про основы PyGame:

Знания из них пригодиться в этой статье.

Создание PyGame пинг понг:

Перед тем как с\начинать создавать игру, нужно подключить нужные компоненты, вот что мы подключаем:

Как видите мы подключили сам PyGame и sys, последний нужен нам для того чтобы закрывать игру.

Дальше продолжаем подготовку, назначим несколько переменных которые нам пригодятся:

В начале мы инициализируем проект на PyGame, потом назначаем цвета которые будем использовать, после назначаем координаты объектов, сначала блока которым будем управлять, потом шарика, который надо отбивать.

Дальше, самое интересное, создаём переменные которые отвечают за направление шарика, первая это circle_right , если значение True , то направляться будет на право, если False налево, и circle_top , если True , то направление шарика на верх, если False то вниз.

Последние, мы закачаем переменные для скорости и параметров окна игры, создаём окно и берём компонент часы, он нам нужен будет, чтобы настроить FPS.

Теперь перейдём к основному, для этого мы сделаем цикл, в котором будет происходить вся логика:

Источник

Ping pong python pygame

Introduction:

In this project, we have tried to create a ping pong game via using the “pygame” module of python. If we talk about the game then, in this game, there are two sides considered as player1 and player2, and a ball is present which needed to get hit by the paddle. If any one of the sides gets fails to hit the ball then the opposite side will score 1 point.

Source Code:
Join our Telegram for Free Coding Ebooks & Handwritten Notes!
 # Importing the library codewithcurious.com import pygame import sys import random import time # Initialising the pygame pygame.init() # frames per second c = pygame.time.Clock() # Dimensions for window width = 900 height = 600 # creating game window screen = pygame.display.set_mode((width, height)) # Title and icon pygame.display.set_caption("Ping Pong Game") # Game rectangle ball = pygame.Rect(width / 2 - 15, height / 2 - 15, 30, 30, ) player1 = pygame.Rect(width - 20, height / 2 - 70, 10, 140) player2 = pygame.Rect(10, height / 2 - 70, 10, 140) # Game variables ball_speedx = 6 * random.choice((1, -1)) ball_speedy = 6 * random.choice((1, -1)) player1_speed = 0 player2_speed = 6 player1_score = 0 player2_score = 0 # Function for ball to move def ball_movement(): global ball_speedx, ball_speedy, player1_score, player2_score ball.x += ball_speedx ball.y += ball_speedy # Bouncing the ball if ball.top = height: ball_speedy *= -1 if ball.left = width: player2_score += 1 ball_restart() if ball.colliderect(player1) or ball.colliderect(player2): ball_speedx *= -1 # function for the movement of player1 def player1_movement(): global player1_speed player1.y += player1_speed if player1.top = height: player1.bottom = height # function for the movement of player2 def player2_movement(): global player2_speed if player2.top < ball.y: player2.top += player2_speed if player2.bottom >ball.y: player2.bottom -= player2_speed if player2.top = height: player2.bottom = height # Function to reset the ball position def ball_restart(): global ball_speedx, ball_speedy ball.center = (width / 2, height / 2) ball_speedy *= random.choice((1, -1)) ball_speedx *= random.choice((1, -1)) # Font variable font = pygame.font.SysFont("calibri", 25) # Game Loop while True: for event in pygame.event.get(): # Checking for quit event if event.type == pygame.QUIT: pygame.quit() sys.exit() # checking for key pressed event if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: player1_speed += 8 if event.key == pygame.K_UP: player1_speed -= 8 # checking for key released event if event.type == pygame.KEYUP: if event.key == pygame.K_DOWN: player1_speed -= 8 if event.key == pygame.K_UP: player1_speed += 8 # calling the functions ball_movement() player1_movement() player2_movement() # setting the score condition if ball.x < 0: player1_score += 1 elif ball.x >width: player2_score += 1 # Visuals screen.fill((0, 0, 0)) pygame.draw.rect(screen, (220, 220, 220), player1) pygame.draw.rect(screen, (220, 220, 220), player2) pygame.draw.ellipse(screen, (220, 220, 220), ball) pygame.draw.aaline(screen, (220, 220, 220), (width / 2, 0), (width / 2, height)) # To draw score font player1_text = font.render("Score:" + str(player1_score), False, (255, 255, 255)) screen.blit(player1_text, [600, 50]) player2_text = font.render("Score:" + str(player2_score), False, (255, 255, 255)) screen.blit(player2_text, [300, 50]) # Updating the game window pygame.display.update() # 60 frames per second c.tick(60)  
Explanation:
  • First of all, we need to move the ball with a particular speed and for the same, we need to bounce the ball whenever it will get hit by any of the rectangular areas
  • We need to code for the movement of both players
  • The third step is to reset the position of the ball if hits the boundaries rather than the paddle
  • The last step is to create a font variable and display the score by following the game rules

→ In this program, now we have created a user-defined function named “ball_movement()”. We are setting the scope of the variable as global so that the variables can be used throughout, in the first place we are just increasing the ball’s speed concerning x and y coordinates. Now, to bounce the ball we are checking the conditions that if the ball hits boundaries by .top and .bottom functions, then updating the speed following that axis. Under this code, we are also checking that if the opponent won’t be able to hit the ball then increase the score of that particular player, and thus after that we are calling the “ball_restart( )” function to reset the ball position.

→ Creating a UDF named as “player1_movement( )” is next in the program’s sequence. In this, we have just simply put the condition that the paddle should not move out of the screen. We have set the conditions for the top and bottom. The same process is followed by another UDF “player2_movement( )”

→ In the “ball_restart( )” function we have set the ball’s speed to be chosen randomly between and 1 and -1 by “.choice( )” method in the “random” module.

→ In the next step we have declared a font variable and set the font by using “pygame.font.SysFont(“font name”,” size”)” method of the “Sys” module

→ Until now, we have completed all the basic needs of our game and now the main step is to be followed, i.e. to create a game loop under which we will call all these functions to get executed

→ With the help of the “while” loop will create a game loop under which we will run this loop until we will get an event, to check the event condition we will use “pygame.event.get()” method. Under this, we will make use of the if-else ladder to get to know the type of event.

To do so we will use “.type”

→ Firstly we have checked the quit event, by “pygame. QUIT”, if the user has clicked the cross button of the game window then the window will get close

In the next series, we checked the event, if any keyboard keys are pressed or not for that we used “pygame. KEYDOWN”. Since the games will make use of arrow keys(down arrow key and up arrow key) and to check the arrow keys we have used “pygame.K_DOWN”, “pygame.K_UP”.

To check the event if the keyboard keys are released we make use of “pygame.KEYUP”

→ In the next step, we have called all the functions which we have made. We have set the scoring conditions for the game as well

→ To draw the score, firstly will render it with the help of “.render()” then we will draw it by using the “.blit(value, color)” function

→ In the end, we will give the command to update the mentioned changes in the game window by using the “pygame.display.update()”.

Источник

Читайте также:  Javascript function parameter defaults
Оцените статью