def __init__(self): self.image_opened = image.load(data_file('garbagecan-open.png')) self.image_closed = image.load(data_file('garbagecan-closed.png')) self.image_lid = image.load(data_file('garbagecan-lid.png')) self.image_opened.anchor_x = self.image_opened.width/2 self.image_opened.anchor_y = self.image_opened.height/2 self.image_closed.anchor_x = self.image_opened.width/2 self.image_closed.anchor_y = self.image_opened.height/2 self.candidateLeaves = {} self.opened = True self.lid_active = False self.can_active = False self.fallen = False self.can_highlighted = False self.lid_highlighted = True self.can_rect = Rect(0, 0, self.image_closed) self.can_rect.center = (80, 90) self.can_sprite = Sprite(self.image_opened) self.can_sprite.set_position(self.can_rect.x, self.can_rect.y) self.lid_rect = Rect(20, 40, self.image_lid) window.game_window.push_handlers(self.on_mouse_release) window.game_window.push_handlers(self.on_mouse_press) window.game_window.push_handlers(self.on_mouse_drag) window.game_window.push_handlers(self.on_mouse_motion) events.AddListener(self)
def __init__(self): super(GameLayer, self).__init__() # Lista de sprites (X's e O's) self.sprites = [None]*9 # Intância do jogo self.game = None # Variavel para verificar se o usuário está habilitado à jogador. A # variável estará falsa somente no caso de alguém ganhar ou o jogo # empatar, esperando a finalização dos efeitos para habilitar o jogo # novamente self.ableToPlay = True # Lista de imagens do jogo, elas são definidas separadamente para não # fiarem duplicadas em vários sprites. self.imageEmpty = image.load('resources/cell.png') self.imageX = image.load('resources/cell-x.png') self.imageO = image.load('resources/cell-o.png') # Imagem de fundo self.background = cocos.sprite.Sprite('background.png', (150, 150)) self.add(self.background) # Inicia um novo jogo self.newGame()
def load_texture(self): if self.texture_file: self.texture_file = join(dirname(__file__), self.texture_file) self.original_texture = image.load(self.texture_file).texture file = BytesIO() self.original_texture.save(self.texture_file, file, encoder=self.encoder) file.seek(0) self.saved_texture = image.load(self.texture_file, file).texture
def __init__(self, x, y): spark_tex = image.load(os.path.join(os.path.dirname(__file__), 'images/flare3.png')).get_texture() sparks = ParticleGroup( controllers=[ Lifetime(2), Movement(damping=0.93), Fader(fade_out_start=0, fade_out_end=1.8), ], renderer=BillboardRenderer(SpriteTexturizer(spark_tex.id))) spark_emitter = StaticEmitter( template=Particle( position=(x,y), color=(1,1,1)), deviation=Particle( position=(1,1,0), velocity=(300,300,0), age=1.5), size=[(1,1,0), (2,2,0), (2,2,0), (2,2,0), (3,3,0), (4,4,0)]) spark_emitter.emit(50, sparks) fire_tex = image.load(os.path.join(os.path.dirname(__file__), 'images/puff.png')).get_texture() fire = ParticleGroup( controllers=[ Lifetime(4), Movement(damping=0.95), Growth(10), Fader(fade_in_start=0, start_alpha=0, fade_in_end=0.5, max_alpha=0.4, fade_out_start=1.0, fade_out_end=1.0) ], renderer=BillboardRenderer(SpriteTexturizer(fire_tex.id))) fire_emitter = StaticEmitter( template=Particle( position=(x, y), size=(10,10,0)), deviation=Particle( position=(2,2,0), velocity=(70,70,0), size=(5,5,0), up=(0,0,pi*2), rotation=(0,0,pi*0.06), age=.3,), color=[(0.5,0,0), (0.5,0.5,0.5), (0.4,0.1,0.1), (0.85,0.3,0)], ) fire_emitter.emit(200, fire)
def test_set_icon_sizes(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.set_icon(image.load(icon_file1), image.load(icon_file2), image.load(icon_file3), image.load(icon_file4), image.load(icon_file5)) glClearColor(1, 1, 1, 1) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.flip() w.dispatch_events() w.close()
def loadTexture( self ): textureSurface = image.load('data/multicolor512.png') self.text0 = textureSurface.get_mipmapped_texture() textureSurface = image.load('data/grass512.jpg') self.text1 = textureSurface.get_mipmapped_texture() textureSurface = image.load('data/sand512.png') self.text2 = textureSurface.get_mipmapped_texture() textureSurface = image.load('data/stone512.jpg') self.text3 = textureSurface.get_mipmapped_texture() textureSurface = image.load('data/water1024.jpg') self.sea_tex = textureSurface.get_mipmapped_texture()
def __init__(self, filename): """Read data from the file""" self.contents = {} mtl = None for line in open(filename, "r"): if line.startswith('#'): continue values = line.split() if not values: continue if values[0] == 'newmtl': if len(values) == 1: values.append('NoNameMat') mtl = self.contents[values[1]] = {} elif mtl is None: raise ValueError("mtl file doesn't start with newmtl stmt") elif values[0] == 'map_Kd': pos = filename.find('/') + 1 mtl['map_Kd'] = filename[0:pos] + values[1] mtl['image'] = image.load(mtl['map_Kd']) elif values[0] == 'Ns': # Map from range 0-1000 to the range 0-128 of GL_SHININESS mtl['Ns'] = float(values[1]) * .128 else: mtl[values[0]] = map(float, values[1:])
def __init__(self): # A Batch is a collection of vertex lists for batched rendering. self.batch = pyglet.graphics.Batch() # A TextureGroup manages an OpenGL texture. self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture()) # A mapping from position to the texture of the block at that position. # This defines all the blocks that are currently in the world. self.world = {} # Same mapping as `world` but only contains blocks that are shown. self.shown = {} # Mapping from position to a pyglet `VertextList` for all shown blocks. self._shown = {} # Mapping from sector to a list of positions inside that sector. self.sectors = {} # Simple function queue implementation. The queue is populated with # _show_block() and _hide_block() calls self.queue = deque() self._initialize()
def __init__(self): # A Batch is a collection of vertex lists for batched rendering. self.batch = pyglet.graphics.Batch() # A TextureGroup manages an OpenGL texture. self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture()) # A mapping from position to the texture of the block at that position. # This defines all the blocks that are currently in the world. self.world = {} # Same mapping as `world` but only contains blocks that are shown. self.shown = {} # Mapping from position to a pyglet `VertextList` for all shown blocks. self._shown = {} # Mapping from sector to a list of positions inside that sector. self.sectors = {} # Simple function queue implementation. The queue is populated with # _show_block() and _hide_block() calls self.queue = deque() #22222222222222 try: with open(WORLD_FILE, 'r') as f: json_representation = json.load(f) json_world = json_representation['world'] for c in json_world: self.add_block(tuple([int(d) for d in c.split(',')]), json_world[c], immediate=False) except IOError: self._initialize()
def init_textures(texture_file): """Initializes textures.""" global textures image = load(texture_file) texture_group = TextureGroup(image.get_texture()) width_ratio = 1.0 / (float(image.width) / settings.texture_size) height_ratio = 1.0 / (float(image.height) / settings.texture_size) for name, coords in texture_mappings.texture_map.iteritems(): master_x = coords[0] * width_ratio master_y = coords[1] * height_ratio x = coords[0] * settings.texture_size y = coords[1] * settings.texture_size #region = image.get_region(x, y, settings.texture_size, settings.texture_size).get_texture() # The vertices for the 2d texture, as percentages of the overall texture #textures[name]['coordinates'] = [x+width_ratio, y+height_ratio, x, y+height_ratio, x, y, x+width_ratio, y] textures[name] = {} textures[name]['coordinates'] = [1, 1, 0, 1, 0, 0, 1, 0] textures[name]['coordinates_for'] = lambda x, y: [x, y, 0, y, 0, 0, x, 0] textures[name]['master_coordinates'] = [master_x+width_ratio, master_y+height_ratio, master_x, master_y+height_ratio, master_x, master_y, master_x+width_ratio, master_y] #textures[name]['texture'] = region #textures[name]['group'] = TextureGroup(region) textures['master'] = {} textures['master']['group'] = texture_group
def __init__(self, app, camera, showTime): self.__theApp = app self.__camera = camera splashImage = image.load( join('..','gfx','splash.png') ) self.__texture = splashImage.texture self.__alpha = 0.0 self.__showTime = showTime
def load_textures(): global texture textureSurface = image.load('star.bmp') texture=textureSurface.texture glBindTexture(GL_TEXTURE_2D, texture.id) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR )
def LoadTextures(self): '''texture 0-5: faces, 6-11: hints, 12: blending screen, 13: char''' i = self.loading if i < len(self.textures): # for i in xrange(len(self.textures)): if i < len(self.ary_norm): imgfile = TEXIMG_FACE % i # bmp24 256x256 elif i <= len(self.ary_norm) * 2: imgfile = TEXIMG_HINT else: imgfile = TEXIMG_CHAR[i - len(self.ary_norm) * 2 - 1] img = image.load(imgfile) self.textures[i] = img.get_texture() ix, iy = img.width, img.height rawimage = img.get_image_data() formatstr = 'RGBA' pitch = rawimage.width * len(formatstr) dat = rawimage.get_data(formatstr, pitch) self.dat[i] = (dat, ix, iy) if i > len(self.ary_norm): # skip face(0-5) and hint(6:white) j = i - len(self.ary_norm) d = [] it = iter(dat) while it.__length_hint__(): r, g, b, a = [ord(it.next()) for k in xrange(4)] if i < len(self.ary_norm) * 2 and r >= 128 and g >= 128 and b >= 128: r, g, b = r if j & 1 else 0, g if j & 2 else 0, b if j & 4 else 0 elif i == len(self.ary_norm) * 2: r, g, b, a = [int(self.instbgc[k] * 255) for k in xrange(4)] else: r, g, b, a = r, g, b, 255 * (r + g + b) / (255 * 3) d.append('%c%c%c%c' % (r, g, b, a)) dat = ''.join(d) glEnable(self.textures[i].target) glBindTexture(self.textures[i].target, self.textures[i].id) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, dat) self.loading = i + 1
def __init__(self): super().__init__() self.scale = 0.8 self.position = -50, -50 explosion_animation = image.Animation.from_image_sequence( image.ImageGrid(image.load('explosion.png'), 1, 8), 0.1, ) self.explosion = sprite.Sprite( explosion_animation, position=(320, 240), scale=1.5, ) self.explosion2 = sprite.Sprite( explosion_animation, position=(160, 120), scale=1.7, ) self.explosion3 = sprite.Sprite( explosion_animation, position=(32, 32), ) self.add(self.explosion) self.explosion.add(self.explosion2) self.explosion2.add(self.explosion3)
def load(self): self._pyglet_image = image.load(self._filename) self._size_x = self._pyglet_image.width self._size_y = self._pyglet_image.height self._opengl_id = self._pyglet_image.get_texture().id self._loaded = True
def __init__(self): self.images = [ image.load(data_file('fire0.png')), image.load(data_file('fire2.png')), image.load(data_file('fire1.png')), ] self.image = self.images[0] pos = (randint(140, 350), randint(270, 400)) self.rect = Rect(pos[0], pos[1], self.image) self.lives = 3 self.delay = 0.2 self.timer = self.delay self.image_count = 0
def __init__(self, pos, angle): super( Pellet, self ).__init__(image.load(os.path.normpath(r'../assets/Graphics/Pellet.png'))) self.initialPosition = pos self.position = (pos) self.angle = angle self.time_alive = 0 self.cshape = CircleShape(Vector2(self.get_rect().center[0], self.get_rect().center[1]), self.width/2)
def __init__(self): super( Ship, self ).__init__(image.load(os.path.normpath(r'../assets/Graphics/BookCraft.png'))) self.drawModules() self.position = (250,250) self.heath = 100 self.bulletList = [] self.centerPoint = self.get_rect().center self.midline = (self.centerPoint, self.get_rect().midtop) self.cshape = CircleShape(Vector2(self.centerPoint[0],self.centerPoint[1]),self.width/2) # Constants for craft movement self.CRAFT_MAX_VELOCITY = 1000 self.CRAFT_ACCELERATION = 100 self.CRAFT_MAX_TURNRATE = 1 # Keep track of the current move speed of the ship. These are accessed # directly by the scene controlling the ship self.craftMovingUp = False self.craftMovingDown = False self.craftMovingRight = False self.craftMovingLeft = False self.craft_x_velocity = 0 self.craft_y_velocity = 0
def __init__( self, radius=1, position=[0, 0, 0], velocity=[0, 0, 0], rotate=None, visible=False, slices=0, stacks=0, color=None, texture=None, ): self.radius = radius self.position = position self.velocity = velocity self.rotate = rotate self.visible = visible self.slices = slices self.stacks = stacks self.color = color self.texture = texture self.quadric = gluNewQuadric() if self.texture: self.image = image.load(self.texture) self.texture = self.image.get_texture() gluQuadricTexture(self.quadric, GL_TRUE) glEnable(self.texture.target) glBindTexture(self.texture.target, self.texture.id) glDisable(self.texture.target)
def load_texture(file): raw = image.load(file) width, height = raw.width, raw.height texture = image.load(file).get_data('RGBA', width * 4) # 4bpp, RGBA format buffer = [0] # Buffer to hold the returned texture id glGenTextures(1, (GLuint * len(buffer))(*buffer)) glBindTexture(GL_TEXTURE_2D, buffer[0]) #Load textures with no filtering. Filtering generally makes the texture blur. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture) return buffer[0]
def __init__(self, show=-1): self.started = False self.condition = '' self.fullCondition = '?' self.preselectedShow = show self.clip = 0 self.lastClip = 0 self.conversation = 0 self.clipLines = [] self.minLineIdx = 0 self.maxLineIdx = 0 self.clipDuration = 0 self.lineInterval = 0 self.clipStartTime = 0 self.currentClip = None self.curShow = None self.clipQuestion = None self.tabletTexture = image.load('img/dashboard-tablet.png').texture self.hh = 1.0 self.ww = 1.0 self.tabletDisplayText = '' self.maxDisplayLength = 10 # max num of lines displayed self.tabletLineWidth = 40 self.allShows = ['show1', 'show2'] # easy / hard self.allNumFragments = [32,34] self.shows = self.allShows self.numFragments = self.allNumFragments self.answers = [] self.questionOrder = [] self.questionIndx = 0 self.correctAnswer = 0 self.responded = False self.playedLetter = False self.playedRepeat = False self.phase = 0 self.responseCountdown = 0.0 self.responseLimit = 15.0 self.clipInterval = 1.5 self.lastLineTime = 0.0 self.isi = 0.0 self.run = -1 self.doPractice = False self.roadCond = 'simple' #self.incorrectSound = pyglet.resource.media('incorrect.wav') #self.correctSound = pyglet.resource.media('correct.wav') self.db = None
def __init__(self, parent): super().__init__() self.images = [load("resources/gold_" + str(i + 1) + '.png') for i in range(4)] self.current_index = None self.parent = None self.update_turn = False self.parent = parent
def load_textures(): global texture texturefile = os.path.join('data','nehe.bmp') textureSurface = image.load(texturefile) texture=textureSurface.texture glBindTexture(GL_TEXTURE_2D, texture.id) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
def load_image(self, filename): img = image.load(filename) return ( img.width, img.height, img.format, img.get_image_data().get_data(img.format, img.width * len(img.format)), )
def __init__(self, terrain): self.position = [25, 0, 25] self._direction = [ 1, 0, 0 ] self.speed = 0 self.t = terrain self.yrot = 90. self.input = [ False, False ] textureSurface = image.load('data/rockbump.jpg') self.text0 = textureSurface.get_mipmapped_texture() textureSurface = image.load('data/rockbump.tga') self.nmap = textureSurface.get_mipmapped_texture() self.model = cube(); self.loadShader()
def __init__(self, pos, angle, speed): super( Enemy, self ).__init__(image.load(os.path.normpath(r'../assets/Graphics/IAmABall.png'))) self.position = pos self.health = 100 self.angle = angle self.speed = speed self.time_alive = 0 self.cshape = CircleShape(Vector2(self.get_rect().center[0], self.get_rect().center[1]), self.width/1.5)
def __init__(self): self.current_phase = 0 self.days_until_phasechange = 2 self.phases = [image.load(data_file('moon-full.png')), ] self.deg = 0 OrbitingObject.__init__(self)
def load_textures(self): texture_file = os.getcwd() + os.path.join('/images', self.image_file) texture_surface = image.load(texture_file) texture = texture_surface.image_data.create_texture(image.Texture) glBindTexture(GL_TEXTURE_2D, texture.id) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) self.texture = texture
def __init__(self): GrillObject.__init__(self) self.image = image.load(data_file('beef.png')) self.rect = Rect(520, 230, self.image) self.cooking = False self.reset()
def load_textures(self): file = os.path.join('img','metal.png') surface = image.load(file) t1 = surface.image_data.create_texture(image.Texture) glBindTexture(GL_TEXTURE_2D, t1.id) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) self.texture = t1
def load_animation(self, imgage, delay): seq = ImageGrid(load(imgage), 4, 1) return Animation.from_image_sequence(seq, delay)
def __init__(self, image_file, anchor_x=0, anchor_y=0): self._image = image.load(image_file) self._image.anchor_x = self._image.width / 2 self._image.anchor_y = self._image.height
def __init__(self): super(CrateModule, self).__init__( image.load( os.path.normpath(r'../assets/Graphics/CrateModule.png'))) pass
def __init__(self, logger, parent_viewport): super().__init__(logger, parent_viewport) self.inactive_image = load( 'img/game_progress_bars/progress_bar_inactive.png') self.active_image = load( 'img/game_progress_bars/progress_bar_money_active.png')
def copy_left_to_right(self, encoder=None): buf = BytesIO() self.left_texture.save("file.png", buf, encoder=encoder) buf.seek(0) self.right_texture = image.load("file.png", buf).texture
def run(ScreenCls, width=1024, height=768, core=False): ''' config = pyglet.gl.Config( double_buffer=True, sample_buffers=1, samples=16, stencil_size=8, ) ''' icons = [ image.load(os.path.join(ICON_PATH, 'icon%i.png' % x)) for x in (16, 32, 64, 128) ] window = Window(caption=system.__name__, resizable=True, vsync=True, width=width, height=height) window.set_icon(*icons) try: screen = ScreenCls(window) except Exception as e: print(e) sys.exit(-2) @window.event def on_draw(): screen.draw() @window.event def on_key_press(symbol, modifiers): screen.on_key_press(symbol, modifiers) @window.event def on_key_release(symbol, modifiers): screen.on_key_release(symbol, modifiers) @window.event def on_mouse_motion(x, y, dx, dy): screen.on_mouse_motion(x, y, dx, dy) @window.event def on_mouse_press(x, y, button, modifiers): screen.on_mouse_press(x, y, button, modifiers) @window.event def on_mouse_drag(x, y, dx, dy, button, modifiers): screen.on_mouse_drag(x, y, dx, dy, button, modifiers) @window.event def on_mouse_scroll(x, y, scroll_x, scroll_y): screen.on_mouse_scroll(x, y, scroll_x, scroll_y) @window.event def on_resize(width, height): screen.resize(width, height) pyglet.clock.schedule_interval(screen.update, 1 / 60.) pyglet.clock.schedule_interval(screen.clock, 1.) pyglet.app.run()
def load_left(self, image_file, decoder=None): self.left_texture = image.load(image_file, decoder=decoder).texture
BLOCK_MAP['tnt'] = pyglet.image.load(TNT_SIDE) BLOCK_MAP['planks_oak'] = pyglet.image.load(PLANKS_OAK) BLOCK_MAP['redstone_ore'] = pyglet.image.load(REDSTONE_ORE) BLOCK_MAP['stonebrick_carved'] = pyglet.image.load(STONEBRICK_CARVED) BLOCK_MAP['brick'] = pyglet.image.load(BRICK) BLOCK_MAP['cobblestone'] = pyglet.image.load(COBBLESTONE) BLOCK_MAP['cobblestone_mossy'] = pyglet.image.load(COBBLESTONE_MOSSY) BLOCK_MAP['grass_side'] = pyglet.image.load(GRASS_SIDE) BLOCK_MAP['gravel'] = pyglet.image.load(GRAVEL) BLOCK_MAP['diamond'] = pyglet.image.load(DIAMOND) BLOCK_MAP['cactus'] = pyglet.image.load(CACTUS_SIDE) BLOCK_MAP['cactus_top'] = pyglet.image.load(CACTUS_TOP) # A TextureGroup manages an OpenGL texture. TEXTURE_MAP = {} TEXTURE_MAP['tnt_top'] = TextureGroup(image.load(TNT_TOP).get_texture()) TEXTURE_MAP['tnt_bottom'] = TextureGroup(image.load(TNT_BOTTOM).get_texture()) TEXTURE_MAP['tnt'] = TextureGroup(image.load(TNT_SIDE).get_texture()) TEXTURE_MAP['planks_oak'] = TextureGroup(image.load(PLANKS_OAK).get_texture()) TEXTURE_MAP['redstone_ore'] = TextureGroup( image.load(REDSTONE_ORE).get_texture()) TEXTURE_MAP['stonebrick_carved'] = TextureGroup( image.load(STONEBRICK_CARVED).get_texture()) TEXTURE_MAP['brick'] = TextureGroup(image.load(BRICK).get_texture()) TEXTURE_MAP['cobblestone'] = TextureGroup( image.load(COBBLESTONE).get_texture()) TEXTURE_MAP['cobblestone_mossy'] = TextureGroup( image.load(COBBLESTONE_MOSSY).get_texture()) TEXTURE_MAP['grass_side'] = TextureGroup(image.load(GRASS_SIDE).get_texture()) TEXTURE_MAP['grass_top'] = TextureGroup(image.load(GRASS_TOP).get_texture()) TEXTURE_MAP['gravel'] = TextureGroup(image.load(GRAVEL).get_texture())
def preview(expr, output='png', viewer=None, euler=True, packages=(), **latex_settings): r""" View expression or LaTeX markup in PNG, DVI, PostScript or PDF form. If the expr argument is an expression, it will be exported to LaTeX and then compiled using available the TeX distribution. The first argument, 'expr', may also be a LaTeX string. The function will then run the appropriate viewer for the given output format or use the user defined one. By default png output is generated. By default pretty Euler fonts are used for typesetting (they were used to typeset the well known "Concrete Mathematics" book). For that to work, you need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the texlive-fonts-extra package). If you prefer default AMS fonts or your system lacks 'eulervm' LaTeX package then unset the 'euler' keyword argument. To use viewer auto-detection, lets say for 'png' output, issue >>> from sympy import symbols, preview, Symbol >>> x, y = symbols("x,y") >>> preview(x + y, output='png') # doctest: +SKIP This will choose 'pyglet' by default. To select a different one, do >>> preview(x + y, output='png', viewer='gimp') # doctest: +SKIP The 'png' format is considered special. For all other formats the rules are slightly different. As an example we will take 'dvi' output format. If you would run >>> preview(x + y, output='dvi') # doctest: +SKIP then 'view' will look for available 'dvi' viewers on your system (predefined in the function, so it will try evince, first, then kdvi and xdvi). If nothing is found you will need to set the viewer explicitly. >>> preview(x + y, output='dvi', viewer='superior-dvi-viewer') # doctest: +SKIP This will skip auto-detection and will run user specified 'superior-dvi-viewer'. If 'view' fails to find it on your system it will gracefully raise an exception. You may also enter 'file' for the viewer argument. Doing so will cause this function to return a file object in read-only mode. Currently this depends on pexpect, which is not available for windows. Additional keyword args will be passed to the latex call, e.g., the symbol_names flag. >>> phidd = Symbol('phidd') >>> preview(phidd, symbol_names={phidd:r'\ddot{\varphi}'}) # doctest: +SKIP """ # we don't want to depend on anything not in the # standard library with SymPy by default import pexpect special = ['pyglet'] if viewer is None: if output == "png": viewer = "pyglet" else: # sorted in order from most pretty to most ugly # very discussable, but indeed 'gv' looks awful :) candidates = { "dvi": ["evince", "okular", "kdvi", "xdvi"], "ps": ["evince", "okular", "gsview", "gv"], "pdf": ["evince", "okular", "kpdf", "acroread", "xpdf", "gv"], } try: for candidate in candidates[output]: if pexpect.which(candidate): viewer = candidate break else: raise SystemError( "No viewers found for '%s' output format." % output) except KeyError: raise SystemError("Invalid output format: %s" % output) else: if viewer not in special and not pexpect.which(viewer): raise SystemError("Unrecognized viewer: %s" % viewer) actual_packages = packages + ("amsmath", "amsfonts") if euler: actual_packages += ("euler", ) package_includes = "\n".join( ["\\usepackage{%s}" % p for p in actual_packages]) format = r"""\documentclass[12pt]{article} %s \begin{document} \pagestyle{empty} %s \vfill \end{document} """ % (package_includes, "%s") if isinstance(expr, str): latex_string = expr else: latex_string = latex(expr, mode='inline', **latex_settings) tmp = tempfile.mktemp() with open(tmp + ".tex", "w") as tex: tex.write(format % latex_string) cwd = os.getcwd() os.chdir(tempfile.gettempdir()) if os.system("latex -halt-on-error %s.tex" % tmp) != 0: raise SystemError("Failed to generate DVI output.") os.remove(tmp + ".tex") os.remove(tmp + ".aux") os.remove(tmp + ".log") if output != "dvi": command = { "ps" : "dvips -o %s.ps %s.dvi", "pdf" : "dvipdf %s.dvi %s.pdf", "png" : "dvipng -T tight -z 9 " + \ "--truecolor -o %s.png %s.dvi", } try: if os.system(command[output] % (tmp, tmp)) != 0: raise SystemError("Failed to generate '%s' output." % output) else: os.remove(tmp + ".dvi") except KeyError: raise SystemError("Invalid output format: %s" % output) src = "%s.%s" % (tmp, output) src_file = None if viewer == "file": src_file = open(src, 'rb') elif viewer == "pyglet": try: from pyglet import window, image, gl from pyglet.window import key except ImportError: raise ImportError( "pyglet is required for plotting.\n visit http://www.pyglet.org/" ) if output == "png": from pyglet.image.codecs.png import PNGImageDecoder img = image.load(src, decoder=PNGImageDecoder()) else: raise SystemError("pyglet preview works only for 'png' files.") offset = 25 win = window.Window(width=img.width + 2 * offset, height=img.height + 2 * offset, caption="sympy", resizable=False) win.set_vsync(False) try: def on_close(): win.has_exit = True win.on_close = on_close def on_key_press(symbol, modifiers): if symbol in [key.Q, key.ESCAPE]: on_close() win.on_key_press = on_key_press def on_expose(): gl.glClearColor(1.0, 1.0, 1.0, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) img.blit((win.width - img.width) / 2, (win.height - img.height) / 2) win.on_expose = on_expose while not win.has_exit: win.dispatch_events() win.flip() except KeyboardInterrupt: pass win.close() else: os.system("%s %s &> /dev/null &" % (viewer, src)) time.sleep(2) # wait for the viewer to read data os.remove(src) os.chdir(cwd) if src_file is not None: return src_file
def __init__(self, arena_width: int, arena_height: int, arena_border: int, square_size: int, draw: bool, fps_limit: int = 12, single_life: bool = False): self.single_life = single_life self.screen_width = arena_width + 2 * arena_border self.screen_height = arena_height + 70 self.arena_width = arena_width self.arena_height = arena_height self.arena_border = arena_border self.square_size = square_size self.grid_width = int(self.arena_width / self.square_size) self.grid_height = int(self.arena_height / self.square_size) if self.grid_width < 1 or self.grid_height < 1: raise ValueError("Square size too big or arena size too small.") self.iteration = 0 self.draw = draw self.fps = fps_limit self.win = window.Window(width=self.screen_width, height=self.screen_height, visible=False) self.colors = [] self.squares_verts = [] if draw: self.header_img = image.load("header.png").texture clock.set_fps_limit(self.fps) self.font = font.load("Arial", 12, bold=True, italic=False) self.arena_verts = [(self.arena_border - 1, self.arena_border - 2), (self.arena_border + self.arena_width + 1, self.arena_border - 2), (self.arena_border + self.arena_width + 1, self.arena_border + self.arena_height), (self.arena_border - 1, self.arena_border + self.arena_height), (self.arena_border - 1, self.arena_border - 2)] self.points_coord = [(150, self.screen_height - 20), (150, self.screen_height - 40), (420, self.screen_height - 20), (420, self.screen_height - 40)] self.colors = [(0, 0, 0), (0, 0, 1), (1, 1, 0), (1, 0, 1), (0, 1, 1), (0.5, 0.5, 0), (0.5, 0, 0.5), (0, 0.5, 0.5), (1, 1, 1), (1, 1, 1), (1, 1, 1), (0, 1, 0), (1, 0, 0)] self.square_verts = [(0, 0), (self.square_size - 1, 0), (self.square_size - 1, self.square_size - 1), (0, self.square_size - 1)] for y in range(self.grid_height): self.squares_verts.append([]) for x in range(self.grid_width): self.squares_verts[y].append([]) for vx, vy in self.square_verts: self.squares_verts[y][x].append(vx + self.arena_border + (x * self.square_size)) self.squares_verts[y][x].append(vy + self.arena_border + (y * self.square_size)) self.grid = Grid(self.grid_width, self.grid_height)
def __init__(self, game_class, x, y, w, h, sprite_sheet=None, sprite_width=32, sprite_height=32): """ To add an object to a map: map.objects['object name'] = object Object states: Each state has a name (consider using integers if you want to advance through them sequentially) Each state is a dict of properties that the object will update to when state_index is changed to that state name Ensure that these properties are spelt correctly! To change state elsewhere, just set object.state_index = <state_name_here>, properties will automatically update Flair: Flair is a dict of 'name': (surface, position (relative to object centre)) to additionally render attached to sprite E.g. Hats, speech bubbles. Collision: Each object has a collision_weight. Objects can only push objects with equal or less weight. Objects can only push a chain of objects up to their own weight. If an objects' collision weight is 0, it does not collide with objects. Collision rectangle updates automatically if you change obj dimensions (or coord). """ self.game_class = game_class self.states = {'state1': {'max_speed': 1, 'fear_radius': 50}, 'state2': {'max_speed': 5, 'fear_radius': 150}} self._state_index = 'state1' self._coord = (x, y) # top left self._dimensions = (w, h) self.velocity = (0, 0) self.min_speed = 0 self.current_speed = 0 self.normal_speed = 0 self.feared_speed = 0 self.fear_radius = 50 self.scared_of = [] self.fears = FearsList(self) self.rect = rect.Rect(self.coord, self.dimensions) self.update_timer = 40 self.fear_timer = 0 self.scream_timer = 0 self.fear = 0 self.scream_thresh = 50 #variables for animation if sprite_sheet is not None: self.sprite_sheet_name = sprite_sheet else: self.sprite_sheet_name = 'DudeSheet.png' self.sprite_sheet = image.load(os.path.join(CHARACTERS_DIR, self.sprite_sheet_name)) # disable texture filtering texture = self.sprite_sheet.get_texture() gl.glBindTexture(texture.target, texture.id) gl.glTexParameteri(texture.target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glBindTexture(texture.target, 0) self._animation_state = 0 self.sprite_height = sprite_height self.sprite_width = sprite_width self._animations = [] self._create_animations() self.sprite = sprite.Sprite(self._animations[self._animation_state], x=self._coord[0], y=self._coord[1]) #trigger functions self.has_touched_function = [] self.is_touched_function = [] self.has_untouched_function = [] self.is_untouched_function = [] self.move_up = False self.move_down = False self.move_left = False self.move_right = False self.highlight_radius = 20 self.flair = {} self.collision_weight = 1 # set to 0 for no collision, can only push things that are lighter, or same weight self.cutscene_controlling = [] self.path = []
def preview(expr, output='png', viewer=None, euler=True, packages=(), filename=None, outputbuffer=None, preamble=None, dvioptions=None, outputTexFile=None, **latex_settings): r""" View expression or LaTeX markup in PNG, DVI, PostScript or PDF form. If the expr argument is an expression, it will be exported to LaTeX and then compiled using the available TeX distribution. The first argument, 'expr', may also be a LaTeX string. The function will then run the appropriate viewer for the given output format or use the user defined one. By default png output is generated. By default pretty Euler fonts are used for typesetting (they were used to typeset the well known "Concrete Mathematics" book). For that to work, you need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the texlive-fonts-extra package). If you prefer default AMS fonts or your system lacks 'eulervm' LaTeX package then unset the 'euler' keyword argument. To use viewer auto-detection, lets say for 'png' output, issue >>> from sympy import symbols, preview, Symbol >>> x, y = symbols("x,y") >>> preview(x + y, output='png') This will choose 'pyglet' by default. To select a different one, do >>> preview(x + y, output='png', viewer='gimp') The 'png' format is considered special. For all other formats the rules are slightly different. As an example we will take 'dvi' output format. If you would run >>> preview(x + y, output='dvi') then 'view' will look for available 'dvi' viewers on your system (predefined in the function, so it will try evince, first, then kdvi and xdvi). If nothing is found you will need to set the viewer explicitly. >>> preview(x + y, output='dvi', viewer='superior-dvi-viewer') This will skip auto-detection and will run user specified 'superior-dvi-viewer'. If 'view' fails to find it on your system it will gracefully raise an exception. You may also enter 'file' for the viewer argument. Doing so will cause this function to return a file object in read-only mode, if 'filename' is unset. However, if it was set, then 'preview' writes the genereted file to this filename instead. There is also support for writing to a BytesIO like object, which needs to be passed to the 'outputbuffer' argument. >>> from io import BytesIO >>> obj = BytesIO() >>> preview(x + y, output='png', viewer='BytesIO', ... outputbuffer=obj) The LaTeX preamble can be customized by setting the 'preamble' keyword argument. This can be used, e.g., to set a different font size, use a custom documentclass or import certain set of LaTeX packages. >>> preamble = "\\documentclass[10pt]{article}\n" \ ... "\\usepackage{amsmath,amsfonts}\\begin{document}" >>> preview(x + y, output='png', preamble=preamble) If the value of 'output' is different from 'dvi' then command line options can be set ('dvioptions' argument) for the execution of the 'dvi'+output conversion tool. These options have to be in the form of a list of strings (see subprocess.Popen). Additional keyword args will be passed to the latex call, e.g., the symbol_names flag. >>> phidd = Symbol('phidd') >>> preview(phidd, symbol_names={phidd:r'\ddot{\varphi}'}) For post-processing the generated TeX File can be written to a file by passing the desired filename to the 'outputTexFile' keyword argument. To write the TeX code to a file named "sample.tex" and run the default png viewer to display the resulting bitmap, do >>> preview(x + y, outputTexFile="sample.tex") """ special = ['pyglet'] if viewer is None: if output == "png": viewer = "pyglet" else: # sorted in order from most pretty to most ugly # very discussable, but indeed 'gv' looks awful :) # TODO add candidates for windows to list candidates = { "dvi": ["evince", "okular", "kdvi", "xdvi"], "ps": ["evince", "okular", "gsview", "gv"], "pdf": ["evince", "okular", "kpdf", "acroread", "xpdf", "gv"], } try: for candidate in candidates[output]: path = find_executable(candidate) if path is not None: viewer = path break else: raise SystemError( "No viewers found for '%s' output format." % output) except KeyError: raise SystemError("Invalid output format: %s" % output) else: if viewer == "StringIO": viewer = "BytesIO" if outputbuffer is None: raise ValueError("outputbuffer has to be a BytesIO " "compatible object if viewer=\"StringIO\"") elif viewer == "BytesIO": if outputbuffer is None: raise ValueError("outputbuffer has to be a BytesIO " "compatible object if viewer=\"BytesIO\"") elif viewer not in special and not find_executable(viewer): raise SystemError("Unrecognized viewer: %s" % viewer) if preamble is None: actual_packages = packages + ("amsmath", "amsfonts") if euler: actual_packages += ("euler", ) package_includes = "\n" + "\n".join( ["\\usepackage{%s}" % p for p in actual_packages]) preamble = r"""\documentclass[varwidth,12pt]{standalone} %s \begin{document} """ % (package_includes) else: if packages: raise ValueError("The \"packages\" keyword must not be set if a " "custom LaTeX preamble was specified") latex_main = preamble + '\n%s\n\n' + r"\end{document}" if isinstance(expr, str): latex_string = expr else: latex_string = ('$\\displaystyle ' + latex(expr, mode='plain', **latex_settings) + '$') try: workdir = tempfile.mkdtemp() with io.open(join(workdir, 'texput.tex'), 'w', encoding='utf-8') as fh: fh.write(unicode(latex_main) % u_decode(latex_string)) if outputTexFile is not None: shutil.copyfile(join(workdir, 'texput.tex'), outputTexFile) if not find_executable('latex'): raise RuntimeError("latex program is not installed") try: # Avoid showing a cmd.exe window when running this # on Windows if os.name == 'nt': creation_flag = 0x08000000 # CREATE_NO_WINDOW else: creation_flag = 0 # Default value check_output([ 'latex', '-halt-on-error', '-interaction=nonstopmode', 'texput.tex' ], cwd=workdir, stderr=STDOUT, creationflags=creation_flag) except CalledProcessError as e: raise RuntimeError( "'latex' exited abnormally with the following output:\n%s" % e.output) if output != "dvi": defaultoptions = { "ps": [], "pdf": [], "png": ["-T", "tight", "-z", "9", "--truecolor"], "svg": ["--no-fonts"], } commandend = { "ps": ["-o", "texput.ps", "texput.dvi"], "pdf": ["texput.dvi", "texput.pdf"], "png": ["-o", "texput.png", "texput.dvi"], "svg": ["-o", "texput.svg", "texput.dvi"], } if output == "svg": cmd = ["dvisvgm"] else: cmd = ["dvi" + output] if not find_executable(cmd[0]): raise RuntimeError("%s is not installed" % cmd[0]) try: if dvioptions is not None: cmd.extend(dvioptions) else: cmd.extend(defaultoptions[output]) cmd.extend(commandend[output]) except KeyError: raise SystemError("Invalid output format: %s" % output) try: # Avoid showing a cmd.exe window when running this # on Windows if os.name == 'nt': creation_flag = 0x08000000 # CREATE_NO_WINDOW else: creation_flag = 0 # Default value check_output(cmd, cwd=workdir, stderr=STDOUT, creationflags=creation_flag) except CalledProcessError as e: raise RuntimeError( "'%s' exited abnormally with the following output:\n%s" % (' '.join(cmd), e.output)) src = "texput.%s" % (output) if viewer == "file": if filename is None: buffer = BytesIO() with open(join(workdir, src), 'rb') as fh: buffer.write(fh.read()) return buffer else: shutil.move(join(workdir, src), filename) elif viewer == "BytesIO": with open(join(workdir, src), 'rb') as fh: outputbuffer.write(fh.read()) elif viewer == "pyglet": try: from pyglet import window, image, gl from pyglet.window import key except ImportError: raise ImportError( "pyglet is required for preview.\n visit http://www.pyglet.org/" ) if output == "png": from pyglet.image.codecs.png import PNGImageDecoder img = image.load(join(workdir, src), decoder=PNGImageDecoder()) else: raise SystemError("pyglet preview works only for 'png' files.") offset = 25 config = gl.Config(double_buffer=False) win = window.Window(width=img.width + 2 * offset, height=img.height + 2 * offset, caption="sympy", resizable=False, config=config) win.set_vsync(False) try: def on_close(): win.has_exit = True win.on_close = on_close def on_key_press(symbol, modifiers): if symbol in [key.Q, key.ESCAPE]: on_close() win.on_key_press = on_key_press def on_expose(): gl.glClearColor(1.0, 1.0, 1.0, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) img.blit((win.width - img.width) / 2, (win.height - img.height) / 2) win.on_expose = on_expose while not win.has_exit: win.dispatch_events() win.flip() except KeyboardInterrupt: pass win.close() else: try: # Avoid showing a cmd.exe window when running this # on Windows if os.name == 'nt': creation_flag = 0x08000000 # CREATE_NO_WINDOW else: creation_flag = 0 # Default value check_output([viewer, src], cwd=workdir, stderr=STDOUT, creationflags=creation_flag) except CalledProcessError as e: raise RuntimeError( "'%s %s' exited abnormally with the following output:\n%s" % (viewer, src, e.output)) finally: try: shutil.rmtree(workdir) # delete directory except OSError as e: if e.errno != 2: # code 2 - no such file or directory raise
def __init__(self, name): self.color_data = image.load(join(path['texture'], 'colormap', name + '.png')) if self.color_data is None: return self.color_data = self.color_data.get_data('RGB', self.color_data.width * 3)
def get_block_icon(block, size): # 显示 3D 方块的缩略图 global _fbo if hasattr(block, 'img'): if not isinstance(block, Block): pass else: return image.load(join(path['texture'], 'block', block.name + '.png')) block_icon = block.group.texture.get_region( int(block.texture_data[2 * 8] * 16) * size, int(block.texture_data[2 * 8 + 1]) * size, size, size) if _fbo == None: _fbo = GLuint(0) glGenFramebuffers(1, byref(_fbo)) glBindFramebuffer(GL_FRAMEBUFFER, _fbo) icon_texture = pyglet.image.Texture.create(size, size, GL_RGBA) glBindTexture(GL_TEXTURE_2D, icon_texture.id) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size, size, 0, GL_RGBA, GL_FLOAT, None) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, icon_texture.id, 0) viewport = (GLint * 4)() glGetIntegerv(GL_VIEWPORT, viewport) glViewport(0, 0, size, size) glClearColor(1.0, 1.0, 1.0, 0.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() glOrtho(-1.5, 1.5, -1.5, 1.5, -10, 10) glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glColor4f(1.0, 1.0, 1.0, 1.0) glRotatef(-45.0, 0.0, 1.0, 0.0) glRotatef(-30.0, -1.0, 0.0, 1.0) glScalef(1.5, 1.5, 1.5) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) vertex_data = block.get_vertices(0, 0, 0) texture_data = block.texture_data count = len(texture_data) // 2 batch = pyglet.graphics.Batch() if hasattr(block, 'get_item_color'): batch.add(count, GL_QUADS, block.group, ('v3f/static', vertex_data), ('t2f/static', texture_data), ('c3f/static', block.get_item_color())) else: batch.add(count, GL_QUADS, block.group, ('v3f/static', vertex_data), ('t2f/static', texture_data)) batch.draw() glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() glBindFramebuffer(GL_FRAMEBUFFER, 0) glViewport(*viewport) glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) return icon_texture.get_image_data()
KEYS = { 'up': UP, 'down': DOWN, 'left': LEFT, 'right': RIGHT, 'focus': LSHIFT, 'shoot': Z, 'bomb': X, } KEY_PRESSED = 2 IMAGES = { 'ui': { 'borders': load('resources/graphics/ui/borders.png'), 'mainmenu_bg': load('resources/graphics/ui/mainmenu_bg.png'), 'mainmenu_bg2': load('resources/graphics/ui/mainmenu_bg2.png'), 'mainmenu_left': load('resources/graphics/ui/mainmenu_left.png') }, 'bullets': { 'round': load('resources/graphics/bullets/round.png') }, 'player': { 'player1': load('resources/graphics/player/player1.png') }, 'enemies': {}, 'backgrounds': { 'clouds': load('resources/graphics/backgrounds/clouds.png'), 'grass': load('resources/graphics/backgrounds/grass.png') }
def load_right_arb(self, image_file, pixel_format): img = image.load(image_file) img.format = pixel_format img.data # forces conversion self.right_texture = img.texture
glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(70, 1.0 * width / height, 0.1, 1000.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() win.on_resize = on_resize glEnable(GL_BLEND) glShadeModel(GL_SMOOTH) glBlendFunc(GL_SRC_ALPHA, GL_ONE) glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) glDisable(GL_DEPTH_TEST) spark_tex = image.load(os.path.join(os.path.dirname(__file__), 'flare3.png')).get_texture() sparks = ParticleGroup(controllers=[ Lifetime(3), Movement(damping=0.93), Fader(fade_out_start=0.75, fade_out_end=3.0), ], renderer=BillboardRenderer( SpriteTexturizer(spark_tex.id))) spark_emitter = StaticEmitter(template=Particle(position=(0, 0, -100), color=(1, 1, 1), size=(2, 2, 0)), deviation=Particle(position=(1, 1, 1), velocity=(75, 75, 75), size=(0.2, 0.2, 0),
def load_image(self, filename): img = image.load(filename) return (img.width, img.height, img.format, img.get_image_data().get_data(img.format, img.width * len(img.format)))
import random import numpy from pyglet import image, sprite images = [image.load('./images/circle.png')] time_scale = 1 class Basic: def __init__(self, position, target, team, batch_set, order_group): self.position = position self.team = team self.speed = 1 self.range = 5 self.target_position = self.position self.target_grid = target self.sprite = sprite.Sprite(images[0], batch=batch_set, group=order_group, x=position[0], y=position[1]) def move(self): if self.position[0] != self.target_position[0] and self.position[ 1] != self.target_position[1]: direction = random.randint(0, 1) else: if self.position[0] != self.target_position[0]: direction = 0 else: direction = 1 if self.position[direction] > self.target_position[direction]: self.position[direction] -= self.speed / time_scale
def load_animation(self, imgage, delay): seq = ImageGrid(load(imgage), 1, self.num_frames) return Animation.from_image_sequence(seq, delay, loop=False)
# Imported modules import os from pyglet.image import load, ImageGrid, Animation from itertools import cycle # Constant values WINDOW_WIDTH = 1200 WINDOW_HEIGHT = 400 GENERATIONS = 25 FONT_NAME = os.path.join(os.path.dirname(__file__), "data/fonts/press_start_2p.ttf") # Sprites GAME_SPRITES = load(os.path.join(os.path.dirname(__file__), "data/images/sprites.png")) TERRAIN_IMG = GAME_SPRITES.get_region(2, 0, 2402, 27) DINOSAUR_RUN_ANIMATION = Animation.from_image_sequence( ImageGrid(GAME_SPRITES.get_region(1854, 33, 176, 95), 1, 2, item_width=88, item_height=96), 0.3, loop=True ) DINOSAUR_DUCK_ANIMATION = Animation.from_image_sequence( ImageGrid(GAME_SPRITES.get_region(2203, 33, 240, 61), 1, 2, item_width=118, item_height=62), 0.3, loop=True ) DINOSAUR_JUMP_IMG = GAME_SPRITES.get_region(1678, 33, 88, 95) DINOSAUR_COLLISION_IMG = GAME_SPRITES.get_region(2030, 33, 88, 95) CACTI_IMGS = ( GAME_SPRITES.get_region(446, 58, 34, 70), # Small cacti 1
def load_image(*filename): filename = os.path.join(*filename) if filename not in _data: _data[filename] = image.load(filename) return _data[filename]
class Window(pyglet.window.Window): worldsize=80 batch=pyglet.graphics.Batch() group=TextureGroup(image.load(TEXTURE_PATH).get_texture()) world={} shown={} _shown={} sectors={} queue=deque() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.exclusive = False self.strafe = [0, 0] self.label = pyglet.text.Label('', font_name='Arial', font_size=18, x=10, y=self.height - 10, anchor_x='left', anchor_y='top', color=(0, 0, 0, 255)) self.myworld=World(self.worldsize, self.batch, self.group, self.world, self.shown, self._shown, self.sectors, self.queue) self.player=Player() self.player.setRotation((0,0)) self.player.setPosition((0,0,0)) self.player.setSector(None) pyglet.clock.schedule_interval(self.update, 1.0 / TICKS_PER_SEC) def update(self,dt): self.myworld.processQueue() sector=self.myworld.sectorize(self.player.position) if sector!=self.player.sector: self.myworld.changeSectors(self.player.sector,sector) if self.player.sector is None: self.myworld.processEntireQueue() self.player.setSector(sector) m=8 dt=min(dt,0.2) for _ in range(m): self.player.updatePlayer(dt/m,self.strafe) position=self.collide(self.player.position,self.player.PLAYER_HEIGHT) self.player.setPosition(position) def collide(self, position, height): """ Checks to see if the player at the given `position` and `height` is colliding with any blocks in the world. Parameters ---------- position : tuple of len 3 The (x, y, z) position to check for collisions at. height : int or float The height of the player. Returns ------- position : tuple of len 3 The new position of the player taking into account collisions. """ # How much overlap with a dimension of a surrounding block you need to # have to count as a collision. If 0, touching terrain at all counts as # a collision. If .49, you sink into the ground, as if walking through # tall grass. If >= .5, you'll fall through the ground. pad = 0.25 p = list(position) #当前位置 np = self.myworld.normalize(position) #把位置数据整数化 for face in self.myworld.FACES: # check all surrounding blocks for i in range(3): # check each dimension independently if not face[i]: #检测到1跳过 continue # How much overlap you have with this dimension.检测在这个方向上有多少重叠的部分 d = (p[i] - np[i]) * face[i] #face控制前后 if d < pad: continue for dy in range(height): # check each height op = list(np) op[1] -= dy op[i] += face[i] if tuple(op) not in self.world: continue p[i] -= (d - pad) * face[i] if face == (0, -1, 0) or face == (0, 1, 0): # You are colliding with the ground or ceiling, so stop # falling / rising.把速度将为0 self.player.setDy(0) break return tuple(p) def on_mouse_press(self, x, y, button, modifiers): if self.exclusive: # vector = self.get_sight_vector() # block, previous = self.model.hit_test(self.position, vector) #返回视线矢量方向上的检测到的块 # if (button == mouse.RIGHT) or \ # ((button == mouse.LEFT) and (modifiers & key.MOD_CTRL)): # # ON OSX, control + left click = right click. # if previous: # self.model.add_block(previous, self.block) # elif button == pyglet.window.mouse.LEFT and block: # texture = self.model.world[block] # if texture != STONE: # self.model.remove_block(block) pass else: self.set_exclusive_mouse(True) def on_mouse_motion(self, x, y, dx, dy): if self.exclusive: m = 0.15 #鼠标灵敏度 x, y = self.player.rotation x, y = x + dx * m, y + dy * m y = max(-90, min(90, y)) #限制y的范围 self.player.rotation = (x, y) def on_key_press(self, symbol, modifiers): if symbol == key.W: self.strafe[0] -= 1 elif symbol == key.S: self.strafe[0] += 1 elif symbol == key.A: self.strafe[1] -= 1 elif symbol == key.D: self.strafe[1] += 1 elif symbol == key.SPACE: if self.player.dy == 0: self.player.setDy(self.player.JUMP_SPEED) elif symbol == key.ESCAPE: self.set_exclusive_mouse(False) elif symbol == key.TAB: self.player.flying = not self.player.flying def on_key_release(self, symbol, modifiers): if symbol == key.W: self.strafe[0] += 1 elif symbol == key.S: self.strafe[0] -= 1 elif symbol == key.A: self.strafe[1] += 1 elif symbol == key.D: self.strafe[1] -= 1 def on_resize(self, width, height): pass def draw_label(self): """ Draw the label in the top left of the screen. """ # x, y, z = self.position xx,yy=self.player.rotation x,y,z=self.player.position self.label.text = '%02d (%.2f, %.2f, %.2f) %0.2f / %0.2f' % ( pyglet.clock.get_fps(),x,y,z,xx,yy ) self.label.draw() def on_draw(self): self.clear() self.set3d() pyglet.gl.glColor3d(1, 1, 1) self.batch.draw() # self.draw_focused_block() self.set2d() self.draw_label() # self.draw_reticle() def set_exclusive_mouse(self, exclusive): """ If `exclusive` is True, the game will capture the mouse, if False the game will ignore the mouse. """ super().set_exclusive_mouse(exclusive) self.exclusive = exclusive def setupFog(self): """ Configure the OpenGL fog properties. """ # Enable fog. Fog "blends a fog color with each rasterized pixel fragment's # post-texturing color." pyglet.gl.glEnable(pyglet.gl.GL_FOG) # Set the fog color. pyglet.gl.glFogfv(pyglet.gl.GL_FOG_COLOR, (pyglet.gl.GLfloat * 4)(0.5, 0.69, 1.0, 1)) # Say we have no preference between rendering speed and quality. pyglet.gl.glHint(pyglet.gl.GL_FOG_HINT, pyglet.gl.GL_DONT_CARE) # Specify the equation used to compute the blending factor. pyglet.gl.glFogi(pyglet.gl.GL_FOG_MODE, pyglet.gl.GL_LINEAR) # How close and far away fog starts and ends. The closer the start and end, # the denser the fog in the fog range. pyglet.gl.glFogf(pyglet.gl.GL_FOG_START, 20.0) pyglet.gl.glFogf(pyglet.gl.GL_FOG_END, 60.0) def set2d(self): """ Configure OpenGL to draw in 2d. """ width, height = self.get_size() pyglet.gl.glDisable(pyglet.gl.GL_DEPTH_TEST) pyglet.gl.glViewport(0, 0, width, height) pyglet.gl.glMatrixMode(pyglet.gl.GL_PROJECTION) pyglet.gl.glLoadIdentity() pyglet.gl.glOrtho(0, width, 0, height, -1, 1) pyglet.gl.glMatrixMode(pyglet.gl.GL_MODELVIEW) pyglet.gl.glLoadIdentity() def set3d(self): """ Configure OpenGL to draw in 3d. """ width, height = self.get_size() pyglet.gl.glEnable(pyglet.gl.GL_DEPTH_TEST) pyglet.gl.glViewport(0, 0, width, height) pyglet.gl.glMatrixMode(pyglet.gl.GL_PROJECTION) pyglet.gl.glLoadIdentity() pyglet.gl.gluPerspective(65.0, width / height, 0.1, 60.0) pyglet.gl.glMatrixMode(pyglet.gl.GL_MODELVIEW) pyglet.gl.glLoadIdentity() x, y = self.player.rotation # x, y = 120, -50 pyglet.gl.glRotatef(x, 0, 1, 0) pyglet.gl.glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x))) # x, y, z = self.position x,y,z= self.player.position pyglet.gl.glTranslatef(-x, -y, -z) def setUp(self): """ Basic OpenGL configuration. """ # Set the color of "clear", i.e. the sky, in rgba. pyglet.gl.glClearColor(0.5, 0.69, 1.0, 1) # Enable culling (not rendering) of back-facing facets -- facets that aren't # visible to you. pyglet.gl.glEnable(pyglet.gl.GL_CULL_FACE) # Set the texture minification/magnification function to GL_NEAREST (nearest # in Manhattan distance) to the specified texture coordinates. GL_NEAREST # "is generally faster than GL_LINEAR, but it can produce textured images # with sharper edges because the transition between texture elements is not # as smooth." pyglet.gl.glTexParameteri(pyglet.gl.GL_TEXTURE_2D, pyglet.gl.GL_TEXTURE_MIN_FILTER, pyglet.gl.GL_NEAREST) pyglet.gl.glTexParameteri(pyglet.gl.GL_TEXTURE_2D, pyglet.gl.GL_TEXTURE_MAG_FILTER, pyglet.gl.GL_NEAREST) self.setupFog()
""" Module's main purpose is to store some values. It is shared to all modules. """ from os.path import join from pyglet import image from pyglet import media from pyglet import font VERSION = "v0.1" WIDTH = 800 HEIGHT = 600 num_second_windows = 0 icon1 = image.load(join("gfx", "icon1.png")) icon2 = image.load(join("gfx", "icon2.png")) background = image.load(join("gfx", "table2.png")) img1 = image.load(join("gfx", "start_stop_button.png")) img2 = image.load(join("gfx", "restart_button.png")) img3 = image.load(join("gfx", "time_out_button.png")) img4 = image.load(join("gfx", "arrow_button.png")) img5 = image.load(join("gfx", "arrow_button2.png")) ring_sound = media.load(join("sounds", "sound.wav"), streaming=False) font.add_file(join("fonts", "open-sans", "OpenSans-Regular.ttf")) # del join, image, media, font
def load_animation(imgage): #加載動畫窗格的規範 seq = ImageGrid(load(imgage), 2, 1) return Animation.from_image_sequence(seq, 0.5)
def save_and_load_depth_buffer(self): stream = BytesIO() image.get_buffer_manager().get_depth_buffer().save( 'buffer.png', stream) stream.seek(0) self.right_texture = image.load('buffer.png', stream)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # 窗口是否捕获鼠标 self.exclusive = False # 玩家 self.player = Player(self) # 拓展功能 self.debug = {} self.debug['debug'] = False self.debug['enable'] = False self.debug['running'] = False # 天气(现在天气, 持续时间) self.weather = {'now': 'clear', 'duration': 0} # 游戏世界(秒) self.time = 0 # rotation = (水平角 x, 俯仰角 y) self.player['rotation'] = (0, 0) # 玩家所处的区域 self.sector = None # 这个十字在屏幕中央 self.reticle = None # 显示在 debug 区域的 info self._info_ext = [] self._info_ext.append('pyglet' + pyglet.version) # 玩家可以放置的方块, 使用数字键切换 self.inventory = [ 'grass', 'dirt', 'log', 'brick', 'leaf', 'plank', 'craft_table', 'glass' ] # 数字键列表 self.num_keys = [ key._1, key._2, key._3, key._4, key._5, key._6, key._7, key._8, key._9, key._0 ] # 这个标签在画布的上方显示 self.label = {} self.label['top'] = ColorLabel('', x=2, y=self.height - 5, width=self.width // 2, multiline=True, anchor_x='left', anchor_y='top', font_size=12, font_name='minecraftia') self.is_init = True # 设置图标 self.set_icon(image.load(os.path.join(path['texture'], 'icon.png'))) # 这个标签在画布正中偏上显示 self.label['center'] = ColorLabel('', x=self.width // 2, y=self.height // 2 + 50, anchor_x='center', anchor_y='center', font_name='minecraftia') # 死亡信息 self.die_info = ColorLabel('', color='white', x=self.width // 2, y=self.height // 2, anchor_x='center', anchor_y='center', font_size=24, font_name='minecraftia') # 这个标签在画布正中偏下显示 self.label['actionbar'] = ColorLabel('', x=self.width // 2, y=self.height // 2 - 100, anchor_x='center', anchor_y='center', font_name='minecraftia') # 加载窗口 self.loading = Loading() # 覆盖屏幕的矩形 self.full_screen = Rectangle(0, 0, self.width, self.height) # 聊天区 self.dialogue = Dialogue() # 将 self.upgrade() 方法每 1.0 / TICKS_PER_SEC 调用一次, 它是游戏的主事件循环 pyglet.clock.schedule_interval(self.update, 1.0 / TICKS_PER_SEC) # 检测玩家是否应该死亡 pyglet.clock.schedule_interval(self.check_die, 1.0 / TICKS_PER_SEC) # 每10秒更新一次方块数据 pyglet.clock.schedule_interval(self.update_status, 0.1) # 每30秒保存一次进度 pyglet.clock.schedule_interval(self.save, 30.0) # 天空颜色变换 pyglet.clock.schedule_interval(change_sky_color, 7.5) log_info('welcome %s' % player['name']) for lib in libs: if hasattr(lib, 'init'): lib.init()
and self.texture.id == other.texture.id and self.texture.target == other.texture.target and self.parent == other.parent) def __hash__(self): return hash((self.texture.id, self.texture.target)) scene_init() ball = pyglet.graphics.Batch() delta = [0, 0, 0] position = [0, 0, 0] mouse_orig_pos = [0, 0] rx, ry = 0, 0 window.push_handlers(GameEventHandler()) pyglet.app.event_loop.clock.schedule(update) text_image = image.load('paperbag.png') for m in scene.meshes: # 导入模型数据 text_bind_group = TextureBindGroup(text_image.get_texture(), TextureEnableGroup()) ball.add(m.vertices.shape[0], GL_TRIANGLES, text_bind_group, ('v3f/static', m.vertices.reshape(-1).tolist()), ('t3f/static', m.texturecoords.reshape(-1).tolist())) pass pyglet.app.run()
def loadSprites(path): collection = Collection() collection.exception = SpriteNotFound for name, file, in path.get().items(): collection[file.name] = load(str(file.path)) return collection
def __init__(self, drone_3d_model, horizon_view_size=8, init_drone_z=5, task='no_collision'): self.task = task # When increase this, show more blocks in current view window self.horizon_view_size = horizon_view_size # A Batch is a collection of vertex lists for batched rendering self.batch = Batch() # Manages an OpenGL texture self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture()) # A mapping from position to the texture for whole, global map self.whole_map = dict() # Same as `whole_map` but only contains the positions to show self.partial_map = dict() # A mapping from position to a pyglet `VertextList` in `partial_map` self._partial_map = dict() # A mapping from sector to a list of positions (contiguous sub-region) # using sectors for fast rendering self.sectors = dict() # Use deque to populate calling of `_show_block` and `_hide_block` self.queue = deque() # A graphics batch to draw drone 3D model self.drone_batch = pyglet.graphics.Batch() # Load drone triangular mesh and scene self.drone_name = os.path.basename(drone_3d_model) self.drone_mesh = trimesh.load(drone_3d_model) self.drone_scene = self.drone_mesh.scene() # Drawer stores drone scene geometry as vertex list in its model space self.drone_drawer = None # Store drone geometry hashes for easy retrival self.drone_vertex_list_hash = '' # Store drone geometry rendering mode, default gl.GL_TRIANGLES self.drone_vertex_list_mode = gl.GL_TRIANGLES # Store drone geometry texture self.drone_texture = None black = np.array([0, 0, 0, 255], dtype=np.uint8) red = np.array([255, 0, 0, 255], dtype=np.uint8) green = np.array([0, 255, 0, 255], dtype=np.uint8) blue = np.array([0, 0, 255, 255], dtype=np.uint8) for i, facet in enumerate(self.drone_mesh.facets): if i < 30: self.drone_mesh.visual.face_colors[facet] = black elif i < 42: self.drone_mesh.visual.face_colors[facet] = red elif i < 54: self.drone_mesh.visual.face_colors[facet] = green elif i < 66: self.drone_mesh.visual.face_colors[facet] = blue else: self.drone_mesh.visual.face_colors[facet] = black # Mark positions of bounding wall and obstacles in the map self._initialize(init_drone_z)