def generate_object(self, desc, x, y): """ Retourne un GameObject qui dépends de la description que l'on donne. Il est placé directement aux coordonnées x, y demandées. """ words = desc.split(";") identifiant = int(words[0]) behaviour = 0 if len(words) > 1: behaviour = int(words[1]) if identifiant == 0: game_object = None elif identifiant == 1: game_object = GameObject( pygame.image.load('assets/Herbe' + str(random.randint(0, 1) + 1) + '.png'), self, x, y, identifiant, False) elif identifiant in range(2, 4) or identifiant in range(10, 12): game_object = Unit( pygame.image.load('assets/' + str(identifiant) + '.png'), self, x, y, identifiant, behaviour) self.units.append(game_object) elif identifiant in range(4, 10): game_object = GameObject( pygame.image.load('assets/' + str(identifiant) + '.png'), self, x, y, identifiant, True) else: game_object = GameObject( pygame.image.load('assets/' + str(identifiant) + '.png'), self, x, y, identifiant, False) return game_object
def __init__(self): GameObject.__init__(self) self.x = 0 self.y = 0 self.width = BLOCK_SIZE * 10 self.height = BLOCK_SIZE * 10 self.color = 0xFFFFFF self.shape = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ] self.blocks = [] for row_index, row in enumerate(self.shape): myrow = [] for col_index, col in enumerate(row): if col == 1: myrow.append(Block(self, self.color, col_index * BLOCK_SIZE, row_index * BLOCK_SIZE)) self.blocks.append(myrow)
def __init__(self, name, xy, tiletype, can_be_eaten=True, hp_gain=0, mp_gain=0): GameObject.__init__(self, xy, tiletype, solid=False, draw_once_seen = False) self.name = name self.time_to_live = 10 self.can_be_eaten = can_be_eaten self.hp_gain = hp_gain self.mp_gain = mp_gain
def generateRocks(self, area): numRocks = randrange(0, int(area.height*area.width*0.005)) for rock in range(numRocks): randx = randrange(area.x-area.width//2+2, area.x+area.width//2-2) randy = randrange(area.y-area.height//2+2, area.y+area.height//2-2) foundCollision = False if ((randx, randy) in area.objList.values()): foundCollision = True; if not foundCollision: typeOfRock = randrange(0,101) if typeOfRock > 90: bigRock = GameObject('#', (102,51,0), randx, randy, visionBlock=True, moveBlock=True) area.objList[(bigRock.x, bigRock.y)] = bigRock for x in range(bigRock.x-1, bigRock.x+2): for y in range(bigRock.y-1, bigRock.y+2): foundCollision = False if ((x, y) in area.objList.values()): foundCollision = True; if not foundCollision: if randrange(0,101) > 35: smallRock = GameObject('o', (153, 102, 0), x, y, moveBlock=True) area.objList[(smallRock.x, smallRock.y)] = smallRock else: smallRock = GameObject('o', (153, 102, 0), randx, randy, moveBlock=True) area.objList[(smallRock.x, smallRock.y)] = smallRock
def __init__(self, group, eff_group, speedx, speedy, start_x, start_y, animation_speed=60): GameObject.__init__(self, group, speedx, speedy, start_x, start_y, animation_speed) self.images = [] self.animation_step = 0 self.animation_len = 0 self.last_death = 0 self.elapsed = pygame.time.get_ticks() self.animation_speed = animation_speed self.effect_group = eff_group self.hp = 100 self.damage = 30 # Взрыв self.explosion = GameEffect(self.effect_group, 0, 0, start_x, self.rect.top) self.explosion.set_images([ "assets/objects/explosion/regularExplosion01.png", "assets/objects/explosion/regularExplosion02.png", "assets/objects/explosion/regularExplosion03.png", "assets/objects/explosion/regularExplosion04.png", "assets/objects/explosion/regularExplosion05.png", "assets/objects/explosion/regularExplosion06.png", "assets/objects/explosion/regularExplosion07.png", "assets/objects/explosion/regularExplosion08.png", ]) # удаляем из груп чтобы избежать отрисовки раньше времени self.effect_group.remove(self.explosion) self.is_destroyed = False
def __init__(self, screen, speedx, speedy, start_x, start_y, animation_speed = 60 ): GameObject.__init__(self, screen, speedx, speedy, start_x, start_y, animation_speed) self.image = pygame.image.load("assets/objects/shoots/laserGreen.png").convert_alpha() self.rect = self.image.get_rect() self.rect.bottom = start_y self.rect.centerx = start_x self.speedy = speedy
def test_eq(self): a = GameObject() a.pos_x = 100 b = GameObject() b.pos_x = 100 self.assertTrue(a == b) pass
def __init__(self, position, facing, mass, height): self.mass = mass self.height = height orientation = array([0, 1, 0]) # Start upright self.forward = dot(array([1, 0, 0]), rotationMatrix(array([0, 1, 0]), facing)) self.velocity = array([0, 0, 0]) GameObject.__init__(self, position, orientation, facing)
def __init__(self, root, x, y): GameObject.__init__(self, root, x, y) self.lifeAlarm = 0 self.direction = 0 self.sprite = load_image("sprites/projectiles/shots/0.png") self.rect = self.sprite.get_rect()
def __init__(self, xy, name, type, variant=0, resources_left=1): GameObject.__init__(self, xy, type, solid=True, draw_once_seen=True) self.action = None self.view = make_rect(Pos(0,0), globals.SCREEN_SIZE) self.tile_variant = variant self.name = name self.resources_left = resources_left self.seen = False
def __init__(self, x, y, color, blocks_numb=4): w = BLC_W + 4 h = BLC_H * (blocks_numb + 0.5) GameObject.__init__(self, x, y, w, h) self.color = color self.blocks_numb = blocks_numb self.is_fulled = False self._blocks = deque([], maxlen=self.blocks_numb)
def __init__(self): GameObject.__init__(self) self.orientation = -1 # 0 = horizontal, 1=vertical self.graphic = 0 self.startPosition = [0, 0] self.length = 0 self.portalList = [] self.wallExists = [] self.exteriorWallID = -1
def __init__(self, game, position=(0, 0), angle=0, is_inside=True, radius=1, image='images/default.png', density=20, friction=8, name='Circle'): GameObject.__init__(self, game, position=position, angle=angle, is_inside=is_inside, image=image) size = self.surface.origin.get_size() self.name = name self.radius = ((size[0] + size[1]) / 4) / game.PPM self.body.CreateCircleFixture(radius=radius, density=density, friction=friction)
def __init__(self): GameObject.__init__(self) self.orientation = -1 # 0 = horizontal, 1=vertical self.graphic = 0 self.startPosition = [0,0] self.length = 0 self.portalList = [] self.wallExists = [] self.exteriorWallID = -1
def __init__(self, position, facing): orientation = array([0, 1, 0]) # Start upright # Work out the direction we're moving in # The unicycle starts vertical, so the "facing" angle is the angle from the x axis. self.forward = dot(array([1, 0, 0]), rotationMatrix(array([0, 1, 0]), facing)) self.isFallen = False GameObject.__init__(self, position, orientation, facing)
def draw(self): if self.game.debug: for i in range(len(self.body.fixtures)): pt = self._place(i) pygame.draw.circle(self.game.screen, (20, 20, 20), self.game.to_screen(pt), int(10 * self.game.camera.zoom), 1) pt = self._place(i, False) pygame.draw.circle(self.game.screen, (20, 20, 20), self.game.to_screen(pt), int(10 * self.game.camera.zoom), 1) GameObject.draw(self)
def __init__(self, name=None, position=None, texImg=None, specTexImg=None, radius=None, mass=None, spin=None, shininess=None, ka=None, kd=None, ks=None, program=None): GameObject.__init__(self, name=name, position=position, texImg=texImg, specTexImg=specTexImg, shininess=shininess, ka=ka, kd=kd, ks=ks, program=program) self.radius = radius self.mass = mass self.spin = spin self._initModel()
def __init__(self, name=None, min=[0, 0, 0], max=[5, 5, 5]): self.name = name self.min = min self.max = max self.type = "Box" self.pointselection = -1 GameObject.__init__(self)
def __init__(self, name = None, min = [0,0,0], max = [5,5,5]): self.name = name self.min = min self.max = max self.type = "Box" self.pointselection = -1 GameObject.__init__(self)
def __init__(self, game, brain, x, y): GameObject.__init__(self, game, x, y) game.creaturelist.append(self) self.size = 10 self.score = 0 self.direction = 0 self.brain = brain self.lefteye = eye.Eye(self, game) self.righteye = eye.Eye(self, game) self.leftimage = [] self.rightimage = []
def __init__(self): self.program = Program() self.vao = GLuint(0) self.vbuf = None self.ibuf = None self.vertices = [] self.normals = [] self.indices = [] self.uvs = [] # we should really be getting the camera not creating a new instance.. self.camera = Camera(800, 600) GameObject.__init__(self)
def __init__(self): self.height = 0 self.width = 0 self.floorGraphic = 0 self.wall = [] self.roomID = 0 self.features = [] self.monsters = [] GameObject.__init__(self) self.map = None self.safeRoom = 0 self.name = "Dungeon Room"
def __init__(self, game, position=(0, 0), angle=0, is_inside=True, size=(1, 0.4), image='images/default.png', density=20, friction=8, name='Rect'): GameObject.__init__(self, game, position=position, angle=angle, is_inside=is_inside, image=image) width, height = size self.name = name self.body.CreatePolygonFixture( vertices=[(-width / 2, height / 2), (width / 2, height / 2), (width / 2, -height / 2), (-width / 2, -height / 2)], density=density, friction=friction)
def __init__(self): GameObject.__init__(self) # Start Position is the top or left of the portal self.startPosition = 0 self.size = 0 # Destination is where the player goes if he goes PAST this portal. # destination: Container ID, Room ID, X offset, Y Offset # Destination is the offset from the portal's position in the first room to the portal's # equivalent position on the other side. self.destination = (0, 0, 0, 0) self.doorID = -1 # No door = -1 self.secret = 0 # 1= secret, 2 = illusionary self.stateData = [] # For saved-game info
def draw(self): mouse_x, mouse_y = pygame.mouse.get_pos() if point_direction(self.x, self.y, mouse_x + self.root.Xview, mouse_y + self.root.Yview) > 90 and point_direction(self.x, self.y, mouse_x + self.root.Xview, mouse_y + self.root.Yview) < 270: if self.flip == 0: self.sprite = pygame.transform.flip(self.sprite, 1, 0) self.flip = 1 else: if self.flip: self.sprite = pygame.transform.flip(self.sprite, 1, 0) self.flip = 0 GameObject.draw(self)
def __init__(self, name=None, x=1, y=1, z=1): self.name = name self.x = x self.y = y self.z = z self.type = "Point" self.pointselection = -1 self.r = 1 GameObject.__init__(self)
def __init__(self, root, x, y): GameObject.__init__(self, root, x, y) self.owner = None self.firingSprite = None self.ammo = 0 self.maxAmmo = 0 self.justShot = False self.readyToShoot = True self.refireAlarm = 0 self.direction = 0
def __init__(self, name = None, x = 1, y = 1, z = 1): self.name = name self.x = x self.y = y self.z = z self.type = "Point" self.pointselection = -1 self.r = 1 GameObject.__init__(self)
def __init__(self): GameObject.__init__(self) # Start Position is the top or left of the portal self.startPosition = 0 self.size = 0 # Destination is where the player goes if he goes PAST this portal. # destination: Container ID, Room ID, X offset, Y Offset # Destination is the offset from the portal's position in the first room to the portal's # equivalent position on the other side. self.destination = (0,0,0,0) self.doorID = -1 # No door = -1 self.secret = 0 # 1= secret, 2 = illusionary self.stateData = [] # For saved-game info
def initialize(self): self.score = 0 self.marisa = Marisa(image=MARISA_PATH, size=None, update_ms=60, pos=(150, 150), velocity=(1, 0)) self.apples = [] self.mushrooms = [] pygame.mixer.music.load(BGM_PATH) pygame.mixer.music.play(-1) while len(self.apples) < NUM_APPLE: collide = False new_apple = GameObject(image=APPLE_PATH, size=(30, 30), update_ms=1000, pos=get_rand_pos(self.window_sz, (128, 128)), velocity=(0, 0)) for apple in self.apples: if GameObject.collide(apple, new_apple): collide = True break if collide is False: self.apples.append(new_apple) else: del new_apple while len(self.mushrooms) < NUM_MUSHROOM: collide = False new_mushrooms = GameObject(image=MUSHROOM_PATH, size=(40, 40), update_ms=1000, pos=get_rand_pos( self.window_sz, (128, 128)), velocity=(0, 0)) for mushroom in self.mushrooms: if GameObject.collide(mushroom, new_mushrooms): collide = True break if collide is False: self.mushrooms.append(new_mushrooms) else: del new_mushrooms self.last_time = int(pygame.time.get_ticks())
def __init__(self, filename=None, program=None, texImg=None, specTexImg=None, normalMap=None, shininess=None, ka=None, kd=None, ks=None): GameObject.__init__(self, name=None, position=None, texImg=texImg, specTexImg=specTexImg, normalMap=normalMap, shininess=shininess, ka=ka, kd=kd, ks=ks, program=program) self.variables = dict([(x,True)for x in ["hAngle", "vAngle", "right"]]) self.oldhAngle = 0 self.oldvAngle = 0 self.zRotAngle = 0 self.xRotAngle = 0 self.vertices, self.normals, self.texCoords = loadObj(filename) self._initModel()
def test_IsCollidingWith_6(self): a = GameObject() b = GameObject() a.pos_x = 0 a.pos_y = 0 a.half_width = 1 a.half_height = 1 b.pos_x = 1 b.pos_y = 1 b.half_width = 1 b.half_height = 1 self.assertTrue(a.IsCollidingWith(b) == 1) self.assertTrue(b.IsCollidingWith(a) == 1) pass
def __init__(self, xy, item_type=None, pickup_description=None, on_pickup=None, dropped_this_turn=False): GameObject.__init__(self, xy, item_type.tile, solid=False, draw_once_seen=True) self.dropped_this_turn = dropped_this_turn self.item_type = item_type if item_type: if not pickup_description: self.pickup_description = (BABY_BLUE, "You pick up the ", WHITE, item_type.name, BABY_BLUE, ".") def on_pickup(player, _): player.add_item(item_type) self.on_pickup = on_pickup else: self.pickup_description = pickup_description self.on_pickup = on_pickup self.is_inv_item = False
def __init__(self, name = None, min = [0,0,0], max = [5,5,5]): self.name = name self.min = min self.max = max self.type = "BoxAberration" self.scale = [1.0, 1.0, 1.0] self.pointselection = -1 GameObject.__init__(self) self.transparent = True
def __init__(self, name = None, x = 1, y = 1, z = 1, r = 1): self.name = name self.x = x self.y = y self.z = z self.r = r self.reflectivity = 0.0 self.type = "Sphere" self.pointselection = -1 GameObject.__init__(self)
def move(self, direction, parent): '''Moves the given blob in the given direction. If it is recovering from being shot out, it moves back towards its parent''' if self.recover: px, py = parent.get_absolute_position() parent_vector = (px - self.x, py-self.y) x, y = GameObject.normalize(parent_vector) if math.hypot(px - self.x, py - self.y) < 1.5 * parent.r: self.recover = False elif self.shoot: x, y = GameObject.normalize(self.init_direction) else: x, y = GameObject.normalize(direction) self.x += self.velocity() * x self.y += self.velocity() * y
def game(self): self.initialize() self.last_time = int(pygame.time.get_ticks()) self.particles = [] while True: for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): self.terminate() keyEvents = self.get_key() elapsed_ms = self.ms_tick() # Collision for apple in self.apples: if GameObject.collide(self.marisa, apple): self.score += 1 collide = True while collide is True: collide = False apple.pos = get_rand_pos(self.window_sz, (30, 30)) for mushroom in self.mushrooms: if GameObject.collide(apple, mushroom, r=2000): collide = True self.marisa.get_apple() for mushroom in self.mushrooms: mushroom.velocity = [ (self.marisa.pos[0] - mushroom.pos[0]) * .002, (self.marisa.pos[1] - mushroom.pos[1]) * .002 ] mushroom.location_update() if GameObject.collide(self.marisa, mushroom): self.gameover() return # Update self.marisa.keyEventHandle(keyEvents=keyEvents, elapsed_ms=elapsed_ms) self.marisa.sprite_update(keyEvents=keyEvents, elapsed_ms=elapsed_ms) self.marisa.location_update() # Display self.update_display() self.marisa.clear()
def __init__(self, root): GameObject.__init__(self, root, 0, 0) self.flip = 0 self.onGround = False self.noclip = False self.noclip = True self.maxJumps = 1 self.currentJumps = 0 self.accel = 1000 self.moveSpeed = 120 self.jumpForce = 200 #was 80 #this should be based on the game, not on the character self.gravity = 400 #was 100
def __init__(self, screen, settings, group): self.max_stars = 250 self.star_speed = 2 self.stars = [] self.group = group self.screen = screen # galaxy sprite self.galaxy_last_release = pygame.time.get_ticks() self.galaxy_released = True self.galaxy_period = 10000 self.galaxy_speedx = 0 self.galaxy_speedy = 3 self.galaxy = GameObject(group, self.galaxy_speedx, self.galaxy_speedy, randrange(100, 539), -100) self.galaxy.set_image("assets/objects/galaxy.png")
def update(self): if self.MOVE_LEFT: self.move() if self.MOVE_RIGHT: self.move(-1) for person in self.game.g_objects: if person is not self: for item in person.give_all_obj(): q = Geo.quarter_direction(self.get_position(), item.get_position()) if not person.is_inside: q = Vec2(q) * -1 force = Geo.to_centre(self.get_position(), item.get_position()) force = force[0] * q[0] * self.gravity, force[1] * q[1] * self.gravity # item.body.ApplyLinearImpulse(force, item.get_position(), wake=True) GameObject.update(self)
def init_bins(self): '''initialize the bins their default state which involves identifying the images in the resources folder and applying them to the correct bin''' #get list of game_object files game_objects = os.listdir('resources/game_objects') for item in game_objects: self.object_bin.add_item( GameObject('resources/game_objects/{}'.format(item))) #get list of terrain files and add them to the texture bin tiles = os.listdir('resources/terrain') for item in tiles: self.tile_bin.add_item(Tile('resources/terrain/{}'.format(item))) for i in range(0, 450 / Tile.HEIGHT): self.tiles.append([]) for j in range(0, 450 / Tile.WIDTH): tile = Tile('resources/terrain/grass0.png', x=(self.object_bin.rect.width + j * Tile.WIDTH), y=i * Tile.HEIGHT) tile.in_bin = False self.tiles[i].append(tile) self.buttons.append(Button('Save', 600, 25, self.save)) self.buttons.append(Button('Load', 650, 25, self.load))
def __init__(self, pl_group, ef_group, screen, settings, speedx, speedy, start_x, start_y, animation_speed = 60): GameObject.__init__(self, pl_group, speedx, speedy, start_x, start_y, animation_speed) """Инициализирует корабль и задает его начальную позицию.""" # Загрузка изображения корабля и получение прямоугольника. self.image_neutral = pygame.image.load(settings.player_ship).convert_alpha() self.image_left = pygame.image.load(settings.player_ship_left).convert_alpha() self.image_right = pygame.image.load(settings.player_ship_right).convert_alpha() self.hp = 100 self.shield_hp = 100 self.damage = 30 self.effect_group = ef_group self.screen = screen self.screen_rect = self.screen.get_rect() self.image = self.image_neutral self.rect = self.image.get_rect() # Каждый новый корабль появляется у нижнего края экрана. self.rect.centerx = start_x self.rect.bottom = start_y # ДК, для анимации выстрела self.last_shot = pygame.time.get_ticks() self.blast = GameEffect(self.group, 0, 0, start_x, self.rect.top, 60); self.blast.set_images(["assets/objects/shoots/laserGreenShot.png"]) self.blast.set_y(self.rect.top - self.blast.get_height() + 10) # удаляем из груп чтобы избежать отрисовки раньше времени self.effect_group.remove(self.blast) # Щит self.shield = GameEffect(self.effect_group, 0, 0, start_x, self.rect.top, 150) self.shield.set_images([settings.player_shield]) self.last_damage = pygame.time.get_ticks() # Воccтановления щита, если 5 сек. без повреждений то восстанавливаем # 2 еденицы энергии каждые 5 сек self.last_damage = 0 self.shield_last_restore = pygame.time.get_ticks() self.shield_recahrge_period = 10000 self.shield_energy_restore = 5 self.shield_restore_delay = 1000 # Флаг перемещения self.moving_right = False self.moving_left = False self.speed = settings.player_speed self.center = float(self.rect.centerx)
def __init__(self, name=None, x=0, y=1, z=0, c=0): self.type = "Plane" self.name = name n = norm([x, y, z]) self.x = n[0] self.y = n[1] self.z = n[2] self.c = -c self.reflectivity = 0.0 self.extension = 1000 GameObject.__init__(self)
def __init__(self, name=None, position=None, texImg=None, specTexImg=None, normalMap=None, radius=None, parent=None, mass=None, velocity=None, distance=None, spin=None, shininess=None, ka=None, kd=None, ks=None, program=None): GameObject.__init__(self, name=name, position=position, texImg=texImg, specTexImg=specTexImg, normalMap=normalMap, shininess=shininess, ka=ka, kd=kd, ks=ks, program=program) self.parent = parent self.radius = radius self.mass = mass self.velocity = velocity self.distance = distance self.spin = spin self.rot = 0 self._setRandomStartingPoint() self._initModel()
def __init__(self, game, position=(0, 0), angle=0, radius=10, n=3): GameObject.__init__(self, game, position, angle, image='images/default.png') self.center_box = self.game.world.CreateStaticBody( position=position, shapes=B2.b2PolygonShape(box=(0.5, 0.5)) ) for item in self.center_box.fixtures: item.filterData.maskBits = Bits.NOTHING_MASK item.filterData.categoryBits = Bits.NOTHING_BITS self.game.world.CreateRevoluteJoint(bodyA=self.body, bodyB=self.center_box, anchor=position) self.recreate(radius, n) for item in self.body.fixtures: item.filterData.maskBits = Bits.FULL_MASK item.filterData.categoryBits = Bits.FULL_BITS
def __init__(self, group, speedx, speedy, start_x, start_y, ttl=250, animation_speed=60): GameObject.__init__(self, group, speedx, speedy, start_x, start_y, animation_speed) self.images = [] # TTL - time to life, a time after will self remove from groups self.ttl = ttl self.last_appears = pygame.time.get_ticks() self.animation_step = 0 self.animation_len = 0 self.elapsed = pygame.time.get_ticks() self.animation_speed = animation_speed
def __init__(self, game, position=(0, 0), angle=0, is_inside=True, image='images/default.png', vertices=[(-2, -1), (2, -1), (0, 1)], density=20, friction=8, name='Fixture'): self.density = density self.friction = friction self.name = name GameObject.__init__(self, game, position=position, angle=angle, is_inside=is_inside, image=image) self.body.CreatePolygonFixture( vertices=vertices, density=density, friction=friction)
def __init__(self, name=None, x=1, y=1, z=1, r=1): self.name = name self.x = x self.y = y self.z = z self.x2 = x + r * 4 self.y2 = y self.z2 = z self.r = r self.reflectivity = 0.0 self.type = "SpherePortal" self.pointselection = -1 GameObject.__init__(self)
def update(self): # ahhh! # o_ / # _/\\ # \| # /|~ # _\|_ # / # ___O_____ # # Keep the old value for the autoBalance function to use self.unicycle._thetaFB_old = self.unicycle.thetaFB if self.unicycle.isFallen: self.rider.move() if pygame.time.get_ticks() - self.timeFallen > 1000: self.reset() return if self.unicycle.isFallenOver(): self.rider.velocity = self.unicycle.velocity.copy() self.timeFallen = pygame.time.get_ticks() if self.sound: self.sound.grunt() return # Base class update stuff GameObject.update(self.unicycle) GameObject.update(self.rider) self.wobble() # Adjust the acceleration to match the angle self.autoBalance() # update unicycle position using wheel accn self.unicycle.move() # update rider position by sticking him back on the top of the unicycle self.rider._position = self.unicycle.position + self.unicycle.orientation / linalg.norm( self.unicycle.orientation) * UNICYCLE_HEIGHT
def rock2obj_collision_check(list1, list2): ''' naiive collision algorithm to compute collisions between rocks or ships or both ''' for obj in list1: for other_obj in list2: if obj == other_obj: continue else: if(GameObject.will_collide_with(obj, other_obj)): obj.handle_collision(other_obj)
def on_key_press(key, modifiers): if key == pyglet.window.key.E: self.add_game_objects((GameObject( Collider.random_polygon(6, np.random.randint(50, 101)), Rigidbody(1., 2e4, np.array([650., 800 + i * 300]), np.pi / 3)) for i in range(8))) print(len(self.constraints)) elif key == pyglet.window.key.R: self.offset = np.zeros(2) self.objects = deepcopy(snapshot) elif key == pyglet.window.key.P: self.paused = not self.paused
def load(self, path): f = open(path, 'r') line = f.readline() line = line.split(' ') print(line) num_cols = line[1] num_rows = line[2] x_offset = int(line[3]) y_offset = int(line[4]) tiles = [] for i in range(0, int(num_rows)): tiles.append([]) for j in range(0, int(num_cols)): line = f.readline().split(' ') tile = Tile(line[0], x=int(line[1]), y=int(line[2])) tile.in_bin = False tiles[i].append(tile) #end of row f.readline() #end of line f.readline() #GameObject header f.readline() objects = [] for line in f: line = line.split(' ') item = GameObject(line[0]) item.rect.x = int(line[1]) item.rect.y = int(line[2]) item.in_bin = False objects.append(item) f.close() return (tiles, objects, x_offset, y_offset)
def render(self): GameObject.render(self) self.program.bind() view_location = glGetUniformLocation(self.program.get_handle(), "view") if view_location > -1: v = self.camera.view v = v[:] v_ctype = (GLfloat * len(v))(*v) glUniformMatrix4fv(view_location, 1, GL_FALSE, v_ctype) proj_location = glGetUniformLocation(self.program.get_handle(), "proj") if proj_location > -1: p = self.camera.projection p = p[:] p_ctype = (GLfloat * len(p))(*p) glUniformMatrix4fv(proj_location, 1, GL_FALSE, p_ctype) model_location = glGetUniformLocation(self.program.get_handle(), "model") if model_location > -1: self.matrix = Matrix4.new_translate(self.position.x, self.position.y, self.position.z) if self.parent: m = Matrix4().identity() m = self.parent.matrix * self.matrix m = m[:] else: m = self.matrix[:] m_ctype = (GLfloat * len(m))(*m) glUniformMatrix4fv(model_location, 1, GL_FALSE, m_ctype) # bind vao for use glBindVertexArray(self.vao) # Draw a rectangle from the 2 triangles using 6 indices if self.indices: glDrawElements(GL_TRIANGLES, len(self.indices), GL_UNSIGNED_INT, 0) elif self.vertices: pass #gldrawarray? # stop the vao glBindVertexArray(0)
def generateTrees(self, area): numPatches = randrange(0, int(area.height*area.width*0.001)) for patch in range(numPatches): randx = randrange(area.x-area.width//2+10, area.x+area.width//2-9) randy = randrange(area.y-area.height//2+10, area.y+area.height//2-9) numTrees = randrange(0, 81) for tree in range(numTrees): randTreeX = randrange(randx-10, randx+11) randTreeY = randrange(randy-10, randy+11) foundCollision = False if ((randTreeX, randTreeY) in area.objList.values()): foundCollision = True; if not foundCollision: newTree = GameObject('T', (0, 102, 0), randTreeX, randTreeY, moveBlock=True) area.objList[(newTree.x, newTree.y)] = newTree
def getGameObjectFromXMLElement(element): # prefab means we should create an instance of a prefab and extend it prefab = element.get("prefab") name = element.get("name") or "unnamed game object" if prefab: go = getGameObjectFromPrefabFileName(prefab, name) else: # prefab attribute not set. Use a new game object go = GameObject(name) for go_or_comp in element: # a game object can contain game objects and components if go_or_comp.tag == "gameobject": xml_go = go_or_comp child = getGameObjectFromXMLElement(xml_go) child.parent = go else: # must be a component otherwise getComponentFromXMLElement(go_or_comp, go) return go
from graphics import Camera from pygame.math import Vector2 from gameobject import GameObject pygame.init() display = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption("Ultimate Pong") clock = pygame.time.Clock() fps_delay = 60 fps_delta = 0 camera = Camera() background = GameObject(position=Vector2(0, 0), scale=Vector2(SCREENWIDTH, SCREENHEIGHT)) background.colorize(pygame.Color(255, 255, 255)) ball = GameObject(position=Vector2(40, 40)) ball.colorize(pygame.Color(255, 0, 0)) while True: #TODO: Move inputs into a custom class and handle with single function call for event in pygame.event.get(): if event.type == QUIT: print("Closing game...") pygame.quit() sys.exit(0) elif event.type == KEYDOWN: print("Key Down: ", event.key)
def __init__(self, x, y, r, color, speed): GameObject.__init__(self, x - r, y - r, r * 2, r * 2, speed) self.radius = r self.diameter = r * 2 self.color = color
def addRequestedGameObject(self, name=None): """Add a game object to the local scene (only this P3D instance).""" go = GameObject(name) go.transform.parent = Root(render) self.gameobjects.append(go)
def addObject(self, attributes): gameObject = GameObject(attributes, self, self.innerX, self.innerY, self.innerDimension, self.baseDimension) self.objects.append(gameObject)