Python Forum

Full Version: code not running even without errors
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm using trinket to run my code but for some reason there is no errors but it's still not running

import pygame

window = pygame.display.set_mode((800, 600))
keys = pygame.key.get_pressed()

class Player:
  def __init__(self):
    self.instance = pygame.image.load('red-box.png')
    self.rect = self.instance.get_rect(center=(100, 300))
    
    self.vy = 0
    self.jump = bool()
  def frame(self):
    if any(keys) and not self.jump:
      self.vy = 3
      self.jump = True
    
    if self.jump:
      self.rect.y -= self.vy
      self.vy -= 0.2
    
    if self.rect.colliderect(ground.rect):
      self.jump = False
      self.vy = 0
      self.rect.y = 300

    for obstacle in obstacles:
      if obstacle.rect.colliderect(self.rect):
        pygame.quit()
        exit()
    
    window.blit(self.instance, self.rect)
    
class Obstacle:
  def __init__(self, name):
    self.instance = pygame.image.load('rocketship.gif')
    self.rect = self.instance.get_rect(center=(800, 300))
    self.name = name
    
    self.instance = pygame.transform.rotate(self.instance, 270)
  def frame(self):
    self.rect.x -= 3
    
    window.blit(self.instance, self.rect)
    
    if self.rect.x < 0:
      del obstacles[name]
      del self
      
player = Player()
obstacles = {}

while True:
  for event in pygame.event.get();
    if event.type == pygame.QUIT:
      pygame.quit()
      exit()
      
  player.frame()
  
  if random.randint(1, 500) == 1:
    idselected = random.randint(1, 10)
    obstacles += {idselected: Obstacle(idselected)}
  for obstacle in obstacles:
    obstacle.frame()

  player.frame()
  
  pygame.display.flip()
  pygame.time.Clock().tick(120)
There is a sytax error on line 28 that prevents the code from running.
for event in pygame.event.get();
There is nothing named ground in the program, so this crashes the program first time Obstacle.frame is called:
f self.rect.colliderect(ground.rect):
You have to call this function each time you check which keys are pressed. Not just once.
keys = pygame.key.get_pressed()
You are still using non-standard indexing. It makes it painful to look at your code in an editor that knows how python is supposed to be formatted. Please change you indent from 2 spaces to 4 spaces.

Obstacle and Player should be pygame sprites. The code will be shorter and the program will run better.
i'm using a trinket editor because I can't download .exe files on a Chromebook (school property)
I don't know how to make it 4 spaces :(