import random import pygame class Cell: def __init__(self,pos,size): self.pos = pos self.size = size def grow(self): self.size = self.size + 1 def movement(self): keys_pressed = pygame.key.get_pressed() if keys_pressed[pygame.K_UP]: pos = (cell.pos[0], cell.pos[1] - 1) self.pos = pos if keys_pressed[pygame.K_DOWN]: pos = (cell.pos[0], cell.pos[1] + 1) self.pos = pos if keys_pressed[pygame.K_LEFT]: pos = (cell.pos[0] - 1, cell.pos[1]) self.pos = pos if keys_pressed[pygame.K_RIGHT]: pos = (cell.pos[0] + 1, cell.pos[1]) self.pos = pos def appearance(self,screen): pygame.draw.circle(screen, RED, self.pos, self.size) class Nutrient: def __init__(self,visible,pos,size): self.visible = visible self.pos = pos self.size = size def appear(self,screen): pygame.draw.circle(screen, BLUE, self.pos, CIRCLE_RADIUS) def consumed(self,pos): del self del nutrients[pos] cell.grow() def check_collision(self): if ((cell.pos[0] - self.pos[0]) ** 2) + ((cell.pos[1] - self.pos[1]) ** 2) <= (cell.size + self.size) ** 2: self.consumed(self.pos) nutrients = {} width = 640 height = 600 SIZE = (width, height) WHITE = (255, 255, 255) RED = (255, 0, 0) BLUE = (0, 0, 255) CIRCLE_RADIUS = 2 BLACK = (0, 0, 0) def main(): screen = init_game() game_loop(screen) exit_game() def init_game(): global clock clock = pygame.time.Clock() pygame.init() screen = pygame.display.set_mode(SIZE) return screen def game_loop(screen): global cell cell = Cell((300,300),5) spawn_nutrition() while True: if not event_handling(): break if not update_game(): break event = event_handling() update_game() draw_screen(screen) def event_handling(): for event in pygame.event.get(): if event.type == pygame.QUIT: return False return True def update_game(): n_copy = nutrients.copy() for x,y in n_copy: nutrients[(x,y)].check_collision() del n_copy cell.movement() clock.tick(60) return True def draw_screen(screen): screen.fill(WHITE) x = 0 cell.appearance(screen) for x,y in nutrients: if nutrients[x,y].visible: nutrients[x,y].appear(screen) x+=1 pygame.display.flip() def spawn_nutrition(): for _ in range(100): pos = (random.randint(0, SIZE[0]), random.randint(0, SIZE[1])) nutrients[pos]=(Nutrient(True, pos,2)) def exit_game(): pygame.quit() main()