Menu

pong in pygame

pong in pygame - student project

# *with a little bit of (mostly cosmetic) tweaks

from pygame import *
SCREENWIDTH = 900
SCREENHEIGHT = 600
screen = display.set_mode((SCREENWIDTH, SCREENHEIGHT))

font.init()
textFace = font.SysFont("Comic Sans MS", 35) # forgive me, i love this silly font

BGCOLOR = (68, 79, 90)
WHITE = (255, 251, 224)
YELLOW = (252, 227, 138)
BLUE = (41, 148, 178)

p1Y = 250
p2Y = 250
paddleWidth = 30
paddleHeight = 100
p1Points = 0
p2Points = 0

ballX = 450
ballY = 300
ballDx = 4
ballDy = 4

running = True
myClock = time.Clock()
while running:
for evt in event.get():
if evt.type == QUIT: #this is useless in this case i think, might be useful in the future though
running = False

# objects' appearances
p1Paddle = Rect(50, p1Y, paddleWidth, paddleHeight)
p2Paddle = Rect(850, p2Y, paddleWidth, paddleHeight)
ball = Rect(ballX, ballY, 10, 10)

# keyboard stuff
keys = key.get_pressed()
if (keys[K_w] and p1Y > 0):
p1Y -= 5
elif (keys[K_s] and p1Y+paddleHeight < SCREENHEIGHT):
p1Y += 5
if (keys[K_UP] and p2Y > 0):
p2Y -= 5
elif (keys[K_DOWN] and p2Y+paddleHeight < SCREENHEIGHT):
p2Y += 5

# ball behaviour
ballX += ballDx
ballY += ballDy
if (ball.colliderect(p1Paddle)):
ballDx = abs(ballDx) # jumps off the left paddle
elif (ball.colliderect(p2Paddle)):
ballDx = abs(ballDx) * -1 # jumps off the right paddle
elif (ballY <= 0):
ballDy = abs(ballDy) #jumps off the upper wall
elif (ballY >= SCREENHEIGHT):
ballDy = abs(ballDy) * -1 #jumps off the lower wall
elif (ballX >= SCREENWIDTH or ballX <= 0): # game loop end
if ballX >= SCREENWIDTH: # checking who got a point
p1Points += 1
else:
p2Points += 1
# resetting the positions
ballX = 450
ballY = 300
p1Y = 250
p2Y = 250
ballDx = ballDx * -1 #reversing the direction of the ball as i found it a little jarring to go the same way twice

# rendering
screen.fill(BGCOLOR) #yup that's necessary
draw.rect(screen, YELLOW, p1Paddle)
draw.rect(screen, BLUE, p2Paddle)
draw.rect(screen, WHITE, ball)

p1PtsTxt = textFace.render("P1 POINTS: " + str(p1Points), True, YELLOW)
p2PtsTxt = textFace.render("P2 POINTS: " + str(p2Points), True, BLUE)
screen.blit(p1PtsTxt, (130, 20))
screen.blit(p2PtsTxt, (620, 20))

display.flip()
myClock.tick(60)

quit()