def __init__(self): self.score = 0 self.movement_score = 0 self.items_consumed = 0 self.game_over = False self.threshold_movement_score = -25 # ground objects self.ground = Ground() # center of board board_center = (int(self.ground.columns / 2), int(self.ground.rows / 2)) # body is a list of parts self.body = [ { 'origin': board_center, 'direction': Direction.UP, 'length': 5, }, ] # marking all points of snake on grid points = self.find_all_points(self.body[0]) for point in points: self.mark_ground(point, 1) # food object self.food = Food() self.food.get_new_position(self.ground) # distance between snake and food self.delta_distance = self.find_distance( self.food.get_current_position(), self.find_end_point(self.body[0]))
def create_level(self, level): height = len(level) width = max(len(string) for string in level) self.level_width, self.level_height = width * BLOCK_SIZE, height * BLOCK_SIZE self.root = pygame.Surface((width * BLOCK_SIZE, height * BLOCK_SIZE)) all(width == len(row) for row in level) objects = pygame.sprite.Group() x = y = 0 for row in level: for col in row: if col == '-': objects.add(Ground(x, y)) elif col == '#': objects.add(Stone(x, y)) elif col == 't': objects.add(Trap(x, y)) elif col == 'p': self.player = Player(x, y) elif col == 'e': objects.add(Enemy(x, y)) elif col == 'T': objects.add(Target(x, y)) elif col == 'u': objects.add(Upper(x, y)) x += BLOCK_SIZE y += BLOCK_SIZE x = 0 self.camera = Camera(self.player, (width * BLOCK_SIZE, height * BLOCK_SIZE), self.resolution) return objects
def __init__(self): self.frame_rate = 10000 # FPS self.frames = 0 # counts number of frames elapsed self.exit = False # Flag to exit the game self.pause = False self.manual = False self.screen_on = True title = 'Snake' # Window Title icon_filename = 'res/icon.png' # loads pygame modules pygame.init() # initializing game objects self.population = Population(layers=(12, 16, 16, 3)) # screen params icon = pygame.image.load(icon_filename) pygame.display.set_icon(icon) pygame.display.set_caption(title) self.screen = pygame.display.set_mode(Ground().get_dimensions()) # reference clock self.clock = pygame.time.Clock() Game.__instance__ = self
def __init__(self): """ Constructor for the Game """ # hide the cursor and clear the screen print("\033[?25l\033[2J", end='') _t = time.time() self.__screen = Screen() self.__ground = Ground() self.__player = Mandalorian(self) self.__dragon = Dragon(self) self.__dragon_boss = DragonBoss(self) self.__score = 0 self.__init_time = _t self.__frame_count = 0 self.__shield_active = False self.__shield_recharging = True self.__last_shield = -1 self.__last_shield_charge = _t self.__last_boost = -1 self.__dragon_active = False self.__dragon_used = False self.__boss_mode = False self.__over = False # seperate them into different classes self.__objects = { "background": [self.__ground], "beams": [], "magnets": [], "player": [self.__player], "boss": [], "boss_bullet": [], "player_bullet": [], "coins": [] } # (x, y, z) # x destroys y on collision # y destroys x if z self.__colliders = [ ("beams", "player", True), ("player", "coins", False), ("player_bullet", "beams", True), ("player_bullet", "boss", True), ("boss", "player", False), ("player_bullet", "boss_bullet", True), ("boss_bullet", "player", True) ]
replay_rect = replay_img.get_rect() replay_rect.x = WIDTH // 2 - 20 replay_rect.y = 100 numbers_img = pygame.image.load('Assets/numbers.png') numbers_img = pygame.transform.scale(numbers_img, (120, 12)) # SOUNDS ********************************************************************* jump_fx = pygame.mixer.Sound('Sounds/jump.wav') die_fx = pygame.mixer.Sound('Sounds/die.wav') checkpoint_fx = pygame.mixer.Sound('Sounds/checkPoint.wav') # OBJECTS & GROUPS *********************************************************** ground = Ground() dino = Dino(50, 160) cactus_group = pygame.sprite.Group() ptera_group = pygame.sprite.Group() cloud_group = pygame.sprite.Group() stars_group = pygame.sprite.Group() # FUNCTIONS ****************************************************************** def reset(): global counter, SPEED, score, high_score if score and score >= high_score: high_score = score
class Snake: def __init__(self): self.score = 0 self.movement_score = 0 self.items_consumed = 0 self.game_over = False self.threshold_movement_score = -25 # ground objects self.ground = Ground() # center of board board_center = (int(self.ground.columns / 2), int(self.ground.rows / 2)) # body is a list of parts self.body = [ { 'origin': board_center, 'direction': Direction.UP, 'length': 5, }, ] # marking all points of snake on grid points = self.find_all_points(self.body[0]) for point in points: self.mark_ground(point, 1) # food object self.food = Food() self.food.get_new_position(self.ground) # distance between snake and food self.delta_distance = self.find_distance( self.food.get_current_position(), self.find_end_point(self.body[0])) def reset(self): """ reset's snake object by calling it's constructor """ self.__init__() def create_part(self, origin, direction, length): """ return new part with specified attributes """ part = { 'origin': origin, 'direction': direction, 'length': length, } return part def update(self): """ if body has only one part then shift the origin in it's current direction else if it has more than one part then - increase size of head by one - decrease size of tail by 1 and after decreasing tail's length, if tail's length is zero then delete that part """ body_size = len(self.body) # marking ground before moving self.mark_ground(self.body[-1]['origin'], 0) # if snake is made of only one part if body_size == 1: head = self.body[0] self.body[0] = self.shift_origin(head) # if snake is made up of more than one part else: self.increase_head_length() self.decrease_tail_length() # marking ground after moving self.mark_ground((self.find_end_point(self.body[0])), 1) # if food is consumed, then increase the length of head by two and mark the grid as well # then find new position for food if self.consumed_food(): self.items_consumed += 1 self.score += self.food.value # increases the length of snake body self.body[0]['length'] += 1 self.mark_ground((self.find_end_point(self.body[0])), 1) # set new position for food self.food.get_new_position(self.ground) # check if head of snake lies inside the grid head_point = self.find_end_point(self.body[0]) if not self.ground.is_inside_grid( *head_point ) or self.movement_score < self.threshold_movement_score: self.game_over = True return # updating distance between food and snake # and score related to it as well current_delta_distance = self.find_distance( self.food.get_current_position(), self.find_end_point(self.body[0])) if current_delta_distance < self.delta_distance: self.movement_score += 1 else: self.movement_score -= 1.5 self.delta_distance = current_delta_distance # features for snake's neural network self.features = concatenate(( self.get_wall_distances(), self.get_body_distances(), self.get_food_distances(), )) def get_wall_distances(self): head = self.body[0] deltas = Direction.get_relative_deltas(head['direction'])[:3] distances = [ self.find_wall_distance_in_direction(head, delta) for delta in deltas ] distances = array(distances) distances = distances / self.ground.diagonal distances = reshape(distances, (len(deltas), 1)) return distances def find_wall_distance_in_direction(self, head, delta): x_, y_ = self.find_end_point(head) deltax, deltay = delta distance = 0 while True: x_ += deltax y_ += deltay if self.ground.is_inside_grid(x_, y_): if abs(deltax) == 1 and abs(deltay) == 1: distance += sqrt(2) else: distance += 1 else: return distance return distance def get_body_distances(self): head = self.body[0] deltas = Direction.get_relative_deltas(head['direction']) distances = [ self.find_body_distance_in_direction(head, delta) for delta in deltas ] distances = array(distances) distances = distances / self.ground.diagonal distances = reshape(distances, (len(deltas), 1)) return distances def find_body_distance_in_direction(self, head, delta): x_, y_ = self.find_end_point(head) deltax, deltay = delta distance = 0 while True: x_ += deltax y_ += deltay if self.ground.is_inside_grid(x_, y_): if self.ground.grid[y_][x_] != 1: if abs(deltax) == 1 and abs(deltay) == 1: distance += sqrt(2) else: distance += 1 else: return distance # if it doesn't hits its body in this direction else: return -self.ground.diagonal return distance def get_food_distances(self): head = self.body[0] direction = head['direction'] xs, ys = self.find_end_point(head) xf, yf = self.food.get_current_position() if direction == Direction.UP or direction == Direction.DOWN: delta_v = yf - ys delta_h = xf - xs elif direction == Direction.LEFT or direction == Direction.RIGHT: delta_v = xf - xs delta_h = yf - ys if direction == Direction.DOWN or direction == Direction.RIGHT: delta_v = -delta_v delta_h = -delta_h distances = array((delta_v, delta_h)) distances = distances / self.ground.diagonal distances = reshape(distances, (len(distances), 1)) return distances def find_distance(self, p1, p2): """ find's euclidean distance between two points """ x1, y1 = p1 x2, y2 = p2 return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)) def get_features(self): """ return feature vector X for neural network """ return self.features def respond(self, y): # finding relative directions current_direction = self.body[0]['direction'] left_direction = Direction.get_direction_to_left(current_direction) right_direction = Direction.get_opposite_direction(left_direction) # One Vs All for multiclass neural network index = argmax(y) if y[index] > 0.5: if index == 0: self.move(left_direction) elif index == 1: self.move(current_direction) elif index == 2: self.move(right_direction) def consumed_food(self): """ checks if snake has consumed new food """ # first index for body's head head = self.body[0] head_point = self.find_end_point(head) if head_point == self.food.get_current_position(): return True return False def increase_head_length(self): """ increase size of head by 1 """ self.body[0]['length'] += 1 def decrease_tail_length(self): """ decrease size of tail by 1 """ self.body[-1]['length'] -= 1 # shift origin of last part by one unit self.body[-1] = self.shift_origin(self.body[-1]) # if tail length is zero, then delete it if self.body[-1]['length'] <= 0: del self.body[-1] def shift_origin(self, part, delta=1): """ shifts origin of the part by amount of delta units """ x_, y_ = part['origin'] direction = part['direction'] length = part['length'] if direction == Direction.LEFT: origin = (x_ - delta, y_) elif direction == Direction.RIGHT: origin = (x_ + delta, y_) elif direction == Direction.UP: origin = (x_, y_ - delta) elif direction == Direction.DOWN: origin = (x_, y_ + delta) new_part = self.create_part(origin, direction, length) return new_part def find_end_point(self, part): """ finds end point of the part other than origin """ x_, y_ = part['origin'] length = part['length'] - 1 direction = part['direction'] if direction == Direction.LEFT: end_point = ( x_ - length, y_, ) elif direction == Direction.RIGHT: end_point = ( x_ + length, y_, ) elif direction == Direction.UP: end_point = ( x_, y_ - length, ) elif direction == Direction.DOWN: end_point = ( x_, y_ + length, ) return end_point def find_all_points(self, part): """ returns all the points included for a given part """ x_, y_ = part['origin'] length = part['length'] direction = part['direction'] # stores array of points points = [] # creates points array for i in range(length): if direction == Direction.LEFT: point = (x_ - i, y_) elif direction == Direction.RIGHT: point = (x_ + i, y_) elif direction == Direction.UP: point = (x_, y_ - i) elif direction == Direction.DOWN: point = (x_, y_ + i) points.append(point) return points def move(self, new_direction): """ if new-direction == current/opposite to head-direction then return else, add new part at the start of list reduce the length of current head by 1 new part = (find_end_point(previous-head), new-direction, 1) """ head = self.body[0] is_same_direction = (head['direction'] == new_direction) is_opposite_direction = ( new_direction == Direction.get_opposite_direction( head['direction'])) if is_same_direction or is_opposite_direction: return else: end_point = self.find_end_point(head) # creating new head of length 1 new_head = self.create_part(end_point, new_direction, 1) # reducing the length of current head by 1 self.body[0]['length'] -= 1 # appending the new head to the snake's body self.body = [new_head] + self.body def draw(self, screen): # draw food point = self.food.get_current_position() rect = self.ground.get_rect(point, point) pygame.draw.rect(screen, Color.RED, rect) # draw snake's parts for part in self.body: """ for each part find rectangle and draw it using pygame draw function """ p1 = part['origin'] p2 = self.find_end_point(part) rect = self.ground.get_rect(p1, p2) pygame.draw.rect(screen, Color.WHITE, rect) def mark_ground(self, point, value): x_, y_ = point if self.ground.is_inside_grid(x_, y_): """ if a particular cell is already occupied and again trying to occupy, then game over """ if value == 1 and self.ground.grid[y_][x_] == 1: self.game_over = True self.ground.grid[y_][x_] = value
def init_board(self, reset=False): if reset: self.frame_counter = 0 w = Ground(self.width / 20, self.height / 20) w_height, w_width = w.get_size() # creating the rows full_row, full_row[:, :] = np.chararray( (w_height, self.width)), config._ground # assigning top and bottom self._b[-w_height:, :] = full_row b = Brick(self.width / 20, self.height / 20) q = Question(self.width / 20, self.height / 20) b_height, b_width = b.get_size() q_height, q_width = q.get_size() p = Pipe(4, 6) p_height, p_width = p.get_size() noground, noground[:, :] = np.chararray( (w_height, w_width)), config._empty brick, brick[:, :] = np.chararray((b_height, b_width)), config._bricks question, question[:, :] = np.chararray( (q_height, q_width)), config._question pipe, pipe[:, :] = np.chararray((p_height, p_width)), config._pipe self._b[-10:-8, 24:24 + q_width] = question self._b[-10:-8, 39:39 + b_width] = brick self._b[-10:-8, 42:42 + q_width] = question self._b[-10:-8, 45:45 + b_width] = brick self._b[-10:-8, 48:48 + q_width] = question self._b[-10:-8, 51:51 + b_width] = brick self._b[-16:-14, 45:45 + q_width] = question self._b[-2 - p_height:-2, 63:63 + p_width] = pipe p = Pipe(6, 6) p_height, p_width = p.get_size() pipe, pipe[:, :] = np.chararray((p_height, p_width)), config._pipe self._b[-2 - p_height:-2, 81:81 + p_width] = pipe p = Pipe(8, 6) p_height, p_width = p.get_size() pipe, pipe[:, :] = np.chararray((p_height, p_width)), config._pipe self._b[-2 - p_height:-2, 99:99 + p_width] = pipe self._b[-2 - p_height:-2, 117:117 + p_width] = pipe self._b[-10:-8, 138:138 + b_width] = brick self._b[-2:, 147:147 + w_width] = noground self._b[-2:, 150:150 + w_width] = noground self._b[-2:, 153:153 + w_width] = noground self._b[-16:-14, 160:160 + b_width] = brick self._b[-16:-14, 163:163 + b_width] = brick self._b[-16:-14, 166:166 + b_width] = brick self._b[-16:-14, 177:177 + b_width] = brick self._b[-16:-14, 180:180 + q_width] = question self._b[-16:-14, 183:183 + q_width] = question self._b[-16:-14, 186:186 + b_width] = brick self._b[-10:-8, 174:174 + b_width] = brick self._b[-10:-8, 177:177 + b_width] = brick for i in range(5): self._b[-2 - b_height:-2, 207 + (3 * i):207 + (3 * i) + b_width] = brick for i in range(4): self._b[-4 - b_height:-4, 210 + (3 * i):210 + (3 * i) + b_width] = brick for i in range(3): self._b[-6 - b_height:-6, 213 + (3 * i):213 + (3 * i) + b_width] = brick for i in range(2): self._b[-8 - b_height:-8, 216 + (3 * i):216 + (3 * i) + b_width] = brick self._b[-10 - b_height:-10, 219:219 + b_width] = brick self._b[-2:, 222:222 + w_width] = noground self._b[-2:, 225:225 + w_width] = noground self._b[-2:, 228:228 + w_width] = noground for i in range(5): self._b[-2 - b_height:-2, 231 + (3 * i):231 + (3 * i) + b_width] = brick for i in range(4): self._b[-4 - b_height:-4, 231 + (3 * i):231 + (3 * i) + b_width] = brick for i in range(3): self._b[-6 - b_height:-6, 231 + (3 * i):231 + (3 * i) + b_width] = brick for i in range(2): self._b[-8 - b_height:-8, 231 + (3 * i):231 + (3 * i) + b_width] = brick self._b[-10 - b_height:-10, 231:231 + b_width] = brick p = Pipe(6, 6) p_height, p_width = p.get_size() pipe, pipe[:, :] = np.chararray((p_height, p_width)), config._pipe self._b[-2 - p_height:-2, 267:267 + p_width] = pipe self._b[-10:-8, 279 + 6:279 + 6 + b_width] = brick self._b[-10:-8, 282 + 6:282 + 6 + b_width] = brick self._b[-10:-8, 285 + 6:285 + 6 + q_width] = question self._b[-10:-8, 288 + 6:288 + 6 + b_width] = brick p = Pipe(4, 6) p_height, p_width = p.get_size() pipe, pipe[:, :] = np.chararray((p_height, p_width)), config._pipe self._b[-2 - p_height:-2, 318:318 + p_width] = pipe for i in range(6): self._b[-2 - b_height:-2, 324 + (3 * i):324 + (3 * i) + b_width] = brick for i in range(5): self._b[-4 - b_height:-4, 327 + (3 * i):327 + (3 * i) + b_width] = brick for i in range(4): self._b[-6 - b_height:-6, 330 + (3 * i):330 + (3 * i) + b_width] = brick for i in range(3): self._b[-8 - b_height:-8, 333 + (3 * i):333 + (3 * i) + b_width] = brick for i in range(2): self._b[-10 - b_height:-10, 336 + (3 * i):336 + (3 * i) + b_width] = brick self._b[-12 - b_height:-12, 339:339 + b_width] = brick p = Pipe(8, 6) p_height, p_width = p.get_size() pipe, pipe[:, :] = np.chararray((p_height, p_width)), config._pipe self._b[-2 - p_height:-2, 360:360 + p_width] = pipe # DYING A SLOW DEATH # create the inital points for spawning objects # subtracting two edge blocks for each top bottom # and dividing by two for range of motion fp = (5, 3) # each object is 4 px wide total_block_x = int((self.width / config.x_fac - 2) / 2 + 1) # each object is 2px tall total_block_y = int((self.height / config.y_fac - 2) / 2 + 1) for r in range(total_block_x): for c in range(total_block_y): self.init_points.append((fp[0] + r * (2 * config.x_fac), fp[-1] + c * (2 * config.y_fac))) self.init_points = list(set(self.init_points))
import sys import pygame from objects import Bird, Ground, PipeObj from config import SIZE, BACKGROUND_COLOR pygame.init() screen = pygame.display.set_mode(SIZE) pygame.display.set_caption('FlapPy Bird') bird = Bird() ground = Ground() # First pipe pipe_lists = [PipeObj()] while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: bird.fly_up() print(event) pipe_lists = [pipe for pipe in pipe_lists if not pipe.offscreen()] # Update positions bird.update_pos() for pipe in pipe_lists: pipe.update_pos() if pipe_lists[-1].need_more_pipe():