import pygame from pygame.locals import * WINDOW_X = 1350 WINDOW_Y = 850 RECT_SIZE = 50 class Truck: def __init__(self, window, ): self.window = window self.image = pygame.image.load("resources/truck.jpeg").convert() self.x = 701 # (x,y) - position of the truck self.y = 401 self.grid = Grid(self.window) self.shelves = Shelves(window) # drawing the truck def draw(self): self.grid.redraw() self.shelves.draw_shelves() self.window.blit(self.image, (self.x, self.y)) pygame.display.flip() # moving the truck def move_right(self): self.x += RECT_SIZE self.draw() def move_left(self): self.x -= RECT_SIZE self.draw() def move_up(self): self.y -= RECT_SIZE self.draw() def move_down(self): self.y += RECT_SIZE self.draw() class Grid: def __init__(self, window): self.window = window # function to draw a grid, it draws a line every 50px(RECT_SIZE) for both x and y axis def draw_grid(self): num_of_columns = int(WINDOW_X / RECT_SIZE) num_of_rows = int(WINDOW_Y / RECT_SIZE) x = 0 y = 0 for i in range(num_of_columns): x += RECT_SIZE pygame.draw.line(self.window, (255, 255, 255), (x, 0), (x, WINDOW_Y)) for i in range(num_of_rows): y += RECT_SIZE pygame.draw.line(self.window, (255, 255, 255), (0, y), (WINDOW_X, y)) # filling a background with color and grid def redraw(self): self.window.fill((70, 77, 87)) self.draw_grid() class Shelves: def __init__(self, window): self.window = window def draw_shelves(self): width = RECT_SIZE - 1 length = 6*RECT_SIZE for i in range(2*RECT_SIZE+1, WINDOW_X - 2*RECT_SIZE, 3*RECT_SIZE): pygame.draw.rect(self.window, (143, 68, 33), pygame.Rect(i, 0, width, length)) pygame.draw.rect(self.window, (143, 68, 33), pygame.Rect(i, (WINDOW_Y - 6*RECT_SIZE)+1, width, length)) class Program: def __init__(self): pygame.init() self.window = pygame.display.set_mode((WINDOW_X, WINDOW_Y)) # decides window's size self.track = Truck(self.window) self.track.draw() def run(self): running = True while running: for event in pygame.event.get(): # integrating with keyboard if event.type == KEYDOWN: if event.key == K_LEFT: self.track.move_left() if event.key == K_RIGHT: self.track.move_right() if event.key == K_UP: self.track.move_up() if event.key == K_DOWN: self.track.move_down() elif event.type == QUIT: running = False if __name__ == "__main__": program = Program() program.run()