You are on page 1of 3

Programming a Pygame platform

by NYSM

import pygame

BLACK = (0,0,0)
RED = (255,0,0)
BLUE = (0,0,255)
WHITE = (255,255,255)

WIDTH = 500
HEIGHT = 500
BD = 50
FPS = 60

class Player():

def __init__ (self, s, x, y):


self.s = s
self.x = x
self.y = y

def draw(self):
pygame.draw.rect(self.s, BLACK, (self.x, self.y, BD, BD))

def collide(self, obj):


if self.x > obj.x - BD and self.x < obj.x + BD:
if self.y < obj.y + BD and self.y > obj.y - BD:
return True
return False

def out_of_bounds(self, xvar, yvar):


if self.x + xvar < 0 or self.y + yvar > HEIGHT-BD:
return True
if self.x + xvar > WIDTH-BD or self.y + yvar < 0:
return True
return False

def move(self, xvar, yvar):


if not self.out_of_bounds(xvar, yvar) and not self.collide(block) :
self.x += xvar
self.y += yvar

class Block():

def __init__ (self, s, x, y):


self.s = s
self.x = x
self.y = y

def out_of_bounds(self, xvar, yvar):


if self.x + xvar < 0 or self.y + yvar > HEIGHT-BD:
return True
if self.x + xvar > WIDTH-BD or self.y + yvar < 0:
return True
return False

def collide(self, obj):


if self.x > obj.x - BD and self.x < obj.x + BD:
if self.y > obj.y - BD and self.y < obj.y + BD:
return True
return False

def move(self, xvar, yvar):


if not self.out_of_bounds(xvar, yvar) and self.collide(player) :
self.x += xvar
self.y += yvar

def draw(self):
pygame.draw.rect(self.s, RED, (self.x, self.y, BD, BD))

pygame.init()

screen = pygame.display.set_mode((WIDTH, HEIGHT))


clock = pygame.time.Clock()

running = True

player = Player(screen, 0, 0)
block = Block(screen, 100 , 100)
inverso = True
sposta = 5

while running:

for event in pygame.event.get():


print event

xvar = 0
yvar = 0

if event.type == pygame.QUIT:
running = False

if event.type == pygame.KEYDOWN:

keys = pygame.key.get_pressed()

if keys[pygame.K_RIGHT]:
xvar = sposta
if keys[pygame.K_LEFT]:
xvar = -sposta
if keys[pygame.K_UP]:
yvar = -sposta
if keys[pygame.K_DOWN]:
yvar = sposta

if keys[pygame.K_m]:
inverso = not inverso

if keys[pygame.K_c]:
sposta/=1.5
if keys[pygame.K_v]:
sposta*=1.5

if inverso == False:
xvar=-xvar
yvar=-yvar

player.move(xvar, yvar)
if player.collide(block):
block.move(xvar,yvar)

if player.out_of_bounds(sposta,sposta) or player.out_of_bounds(-sposta,-
sposta):
screen.fill(BLUE)
else:
screen.fill(WHITE)

player.draw()
block.draw()

pygame.display.update()
clock.tick(FPS)

pygame.quit()

You might also like