import pygame class Ranger: def __init__(self, screen_w, screen_h, ranger_speed): self.plant = False self.new_plant = False self.cut_tree = False self.speed = ranger_speed self.image = pygame.image.load("images/ranger_hat.png") image_rect = self.image.get_rect() size_reduction = 5 self.collision_rect = pygame.Rect(image_rect.left + size_reduction, \ image_rect.top + size_reduction, \ image_rect.width - size_reduction, \ image_rect.height - size_reduction) self.position = [0, 0] self.screen_w = screen_w self.screen_h = screen_h self.direction_x = 0 self.direction_y = 0 def input(self, event): # Handle movement for the character if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: self.direction_x = -1 self.direction_y = 0 if event.key == pygame.K_RIGHT: self.direction_x = 1 self.direction_y = 0 if event.key == pygame.K_UP: self.direction_y = -1 self.direction_x = 0 if event.key == pygame.K_DOWN: self.direction_y = 1 self.direction_x = 0 if event.type == pygame.KEYUP: if (event.key == pygame.K_LEFT and self.direction_x == -1 and self.direction_y == 0) or\ (event.key == pygame.K_RIGHT and self.direction_x == 1 and self.direction_y == 0) or\ (event.key == pygame.K_UP and self.direction_y == -1 and self.direction_x == 0) or\ (event.key == pygame.K_DOWN and self.direction_y == 1 and self.direction_x == 0): self.direction_x = 0 self.direction_y = 0 # Handle Tree planting key if event.type == pygame.KEYDOWN: if self.new_plant == False: if event.key == pygame.K_p: self.plant = True # Handle Tree cutting key #if event.type == pygame.KEYDOWN: # if self.cut_tree == False # if event.key == pygame.K_c: # self.cut_tree == True def update(self): image_center = self.image.get_width()/2 # Move the character around the screen self.position = ((self.position[0] + self.direction_x * self.speed + image_center)%self.screen_w - image_center), \ ((self.position[1] + self.direction_y * self.speed + image_center)%self.screen_h - image_center) def collides_with(self, other): return self.get_absolute_rect().colliderect(other.get_absolute_rect()) def draw(self, on_surface): on_surface.blit(self.image, self.position) def get_absolute_rect(self): return self.collision_rect.move(self.position) def plant(self, trees): trees.append(Tree(self.position))