Skip to content

Instantly share code, notes, and snippets.

@quapka
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quapka/e783d7d3160333c08c44 to your computer and use it in GitHub Desktop.
Save quapka/e783d7d3160333c08c44 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import pygame, sys
#from lib_tenis import *
class Slider(object):
def __init__(self, screen, x):
self.screen = screen
self.x = x
self.y = 0
self.rect = pygame.Rect(self.x,self.y, 30,150)
self.draw()
def draw(self):
pygame.draw.rect(self.screen,
(255,255,255),
self.rect)
def move(self, dy):
if self.y + dy >= 0 and self.y + dy <= 330:
self.rect = self.rect.move(0,dy)
self.y += dy
self.draw()
pygame.init()
screen = pygame.display.set_mode((640, 480))
# two players and their differences
player1 = Slider(screen, 0)
pl1_dy = 0
player2 = Slider(screen, 610)
pl2_dy = 0
clock = pygame.time.Clock()
# position and velocity for x,y
x, y = 100, 100
dx, dy = 1,1
rect = pygame.Rect(int(x), int(y), 25, 25)
# main game loop
while True:
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# operating sliders
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
pl1_dy = 1
if event.key == pygame.K_w:
pl1_dy = -1
if event.key == pygame.K_DOWN:
pl2_dy = 1
if event.key == pygame.K_UP:
pl2_dy = -1
elif event.type == pygame.KEYUP:
if event.key == pygame.K_s:
pl1_dy = 0
if event.key == pygame.K_w:
pl1_dy = 0
if event.key == pygame.K_DOWN:
pl2_dy = 0
if event.key == pygame.K_UP:
pl2_dy = 0
# move players
player1.move(pl1_dy)
player2.move(pl2_dy)
# bounce red rect
if rect.y <= 0 or rect.y + 25 >= 480:
dy *= -1
if rect.x <= 0 or rect.x + 25 >= 640:
dx *= -1
# adjust the red rect
rect = rect.move(dx,dy)
# check for collision
if rect.colliderect(player1.rect):
if rect.x >= player1.rect.x:
dx *= -1
else:
dy *= -1
if rect.colliderect(player2.rect):
if rect.x <= player2.rect.x:
dx *= -1
else:
dy *= -1
# draw red rect
pygame.draw.rect(screen,
(255,0,0),
rect)
clock.tick(500)
pygame.display.update()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment