def __init__(self, window): self.window = window self.speed = 1 self.direction = pval((0, 1)) self.head_pos = pval((0, 0)) self.length = 5 self.body_parts = deque(maxlen=self.length) # store body parts for i in range(5): self.body_parts.append(BodyPart()) self.eaten_fruits = [ ] # store fruit eaten by snake until they make snake grow
def move(self): for s in range(self.speed): #rect = self.body_parts[-1].rect.copy() next_head_pos = self.head_pos + self.direction next_rect = self.head.rect.copy() next_rect.topleft = next_head_pos.get() # if next position is outside game area if not self.window.get_rect().colliderect(next_rect): next_rect = self.go_trough(next_rect) next_head_pos = pval(next_rect.topleft) # if snake bites himself if any( next_rect.colliderect(part.rect) for part in [b for b in self.body_parts][:-3]): #self.body_parts[:-3]): print("You're dead") # if a fruit has been eaten if self.eaten_fruits: # if its position whe, eaten collide with the tail if any( self.tail.rect.colliderect(f.rect) for f in self.eaten_fruits): # grow and remove fruit from list self.grow(self.eaten_fruits.pop(0).nutritive_value) # create a new BodyPart object at new position self.head_pos = next_head_pos new_part = BodyPart() new_part.rect = next_rect self.body_parts.append(new_part)
def __init__(self, window, v=1, size=(8, 8), color=(200, 0, 0)): self.window = window # create fruit on a random position self.position = pval((random.randint(0, self.window.get_width()), random.randint(0, self.window.get_height()))) self.nutritive_value = v # = v will be added to snake size self.size = size # size on the screen self.color = color # what will be drawn on the screen self.surface = pygame.Surface((self.size)) self.surface.fill(self.color) # store fruit size and position self.rect = self.surface.get_rect() self.rect.topleft = self.position.get()
def change_direction(self, direction): if pval.dot(self.direction, direction) == 0: # can't do backtracking self.direction = pval(direction) * 10 # self.body_part_size
# installed library import pygame # self-made modules from snake import Snake from fruit import random_fruit from object_position import PositionValueObject as pval # local var DIR_EVENT_DICT = { pygame.K_RIGHT: (1, 0), pygame.K_LEFT: (-1, 0), pygame.K_DOWN: (0, 1), pygame.K_UP: (0, -1) } GAME_WINDOW_OFFSET = pval((30, 30)) GAME_WINDOW_SIZE = pval((800, 600)) class MainWindow: def __init__(self): # create a new window self.window = pygame.display.set_mode((800, 600)) # set game window name pygame.display.set_caption("Snake game") # create a grey background self.background = pygame.Surface((800, 600)) self.background.fill(pygame.Color("#222222"))