External Exam Download Resources Web Applications Games Recycle Bin

Dude player class

dude.py

import pygame
pygame.init()
from player_class import objPlayer
dude = objPlayer()
black = (0, 0, 0) #RGB
screen = pygame.display.set_mode((400, 300))
clock = pygame.time.Clock() #allows us to throttle frame rate
done = False

while not done:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      done = True
      
  keys = pygame.key.get_pressed()
  if keys[pygame.K_LEFT]:
    dude.left(1) #1px
  if keys[pygame.K_RIGHT]:
    dude.right(1)
    
  screen.fill(black)
  pygame.draw.rect(
    screen,
    dude.colour,
    pygame.Rect(dude.draw()) #.draw() >> x,y,width,height
  )   
  pygame.display.flip()
  clock.tick(60) #caps at 60fps
  
pygame.quit()

player_class.py

class objPlayer:
  def __init__(player, x=0, y=0, size=10): #create event
    player.x = x
    player.y = y
    player.size = size
    player.colour = (250,128,114) #salmon
    
  def draw(player):
    x = player.x
    y = player.y
    width = player.size
    height = player.size
    return(x,y,width,height) #for pygame.Rect(tuple)
    
  def left(player, amt):
    player.x = player.x - amt

  def right(player, amt):
    player.x = player.x + amt

  def up(player, amt):
    player.y = player.y - amt

  def down(player, amt):
    player.y = player.y + amt

save all files to same project folder, and launch dude.py: