import pygame import traceback import random class Player: def __init__(self, x, y): self.x = x self.y = y def tick(self, pressed, _entities): if pressed[pygame.K_LEFT]: self.x -= 2 if pressed[pygame.K_RIGHT]: self.x += 2 if pressed[pygame.K_UP]: self.y -= 2 if pressed[pygame.K_DOWN]: self.y += 2 def draw(self, screen): pygame.draw.rect(screen, (0, 128, 255), # color (r,g,b) (self.x, self.y, 16, 16)) # rect (x,y,w,h) class Enemy: def __init__(self, x, y): self.x = x self.y = y def tick(self, _pressed, entities): player = entities[0] dx = player.x - self.x dy = player.y - self.y if dx < 0: self.x -= 1 elif dx > 0: self.x += 1 if dy < 0: self.y -= 1 elif dy > 0: self.y += 1 def draw(self, screen): pygame.draw.rect(screen, (255, 0, 0), # color (r,g,b) (self.x, self.y, 8, 8)) # rect (x,y,w,h) class RandomEnemy: def __init__(self, x, y): self.x = x self.y = y def tick(self, _pressed, _entities): self.x += random.randint(-2, 2) self.y += random.randint(-2, 2) def draw(self, screen): pygame.draw.rect(screen, (255, 0, 0), # color (r,g,b) (self.x, self.y, 16, 16)) # rect (x,y,w,h) def game_step(screen, pressed, entities): # Simulation for ent in entities: ent.tick(pressed, entities) # Rendering for ent in entities: ent.draw(screen) def play(): pygame.init() screen = pygame.display.set_mode((320, 240)) # "Surface" done = False clock = pygame.time.Clock() entities = [Player(50, 50), Enemy(100, 100), RandomEnemy(75, 150)] while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pressed = pygame.key.get_pressed() if pressed[pygame.K_ESCAPE]: done = True screen.fill((0, 0, 0)) game_step(screen, pressed, entities) pygame.display.flip() clock.tick(60) pygame.quit() try: play() except Exception: traceback.print_exc() pygame.quit()