lesje-python/pong_6.py

89 lines
3.4 KiB
Python
Raw Permalink Normal View History

2022-12-06 17:01:23 +00:00
import pygame
import sys
# Some constants that we use in the program
BACKGROUND_COLOR = (0, 0, 0) # Black background
SCREEN_SIZE = (500, 500) # Screen size is 500 x 500
PADDLE_COLOR = (255, 255, 255) # Paddle color is white
PADDLE_SIZE = (10, 100) # Paddle size is 10 x 100
BALL_COLOR = (255, 255, 255) # Ball color is white
BALL_RADIUS = 10 # Ball radius is 10 pixels
PLAYER_START_X_OFFSET = 50 # The amount of pixels the player is away from the wall on the X axis
PLAYER_START_Y_OFFSET = 200 # The amount of pixels the player is away from the wall on the Y axis
PLAYER_MOVE_SPEED = 400 # The amount the player moves when a key is pressed
FRAMERATE = 60 # The target framerate of the game
class Player:
def __init__(self, x, y):
self.x = x
self.y = y
# Will move the player on the Y axis but only if it is certain
# that the player will not move out of the bounds of the screen
def move(self, amount):
if self.y + amount >= 0 and self.y + PADDLE_SIZE[1] + amount < SCREEN_SIZE[1]:
self.y += amount
# This class will represent our game
class Game:
# This function will be called when the class is first created
def __init__(self):
pygame.init()
self.window = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("Hello world")
self.player1 = Player(PLAYER_START_X_OFFSET, PLAYER_START_Y_OFFSET)
self.player2 = Player(SCREEN_SIZE[0] - PLAYER_START_X_OFFSET, PLAYER_START_Y_OFFSET)
# Draw one paddle at a given location
def draw_paddle(self, location):
pygame.draw.rect(self.window, PADDLE_COLOR, (location[0], location[1], PADDLE_SIZE[0], PADDLE_SIZE[1]))
# Draw the ball at a given location
def draw_ball(self, location):
pygame.draw.circle(self.window, BALL_COLOR, location, BALL_RADIUS)
# This function will render the contents of the screen
def render(self):
self.window.fill(BACKGROUND_COLOR)
# Draw the two players
self.draw_paddle((self.player1.x, self.player1.y))
self.draw_paddle((self.player2.x, self.player2.y))
# Draw the ball
self.draw_ball((250, 250))
pygame.display.flip()
def start(self):
# The main loop will run until the QUIT event is triggered
# this event will be triggered by closing the window
clock = pygame.time.Clock()
while True:
# Check for user input
# Get a map of all currently pressed keys
keys = pygame.key.get_pressed()
# Change the movement of the player based on which key is pressed
movement = PLAYER_MOVE_SPEED * (clock.get_time() / 1000)
if keys[pygame.K_d]: self.player1.move(movement)
elif keys[pygame.K_f]: self.player1.move(-movement)
if keys[pygame.K_j]: self.player2.move(movement)
elif keys[pygame.K_k]: self.player2.move(-movement)
# Loop over all current events and check if the quit event was fired
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# snip ...
self.render()
clock.tick(FRAMERATE)
# Create the game object and start the game
game = Game()
game.start()