Example #1
0
class Game():

    def __init__(self):
        gl.glEnable(gl.GL_TEXTURE_2D)
        gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
        self.window = Window(width=640, height=360, resizable=True)
        self.window.config.alpha_size = 8
        gl.glEnable(gl.GL_BLEND)
        self.window.set_caption('KeysManiac (development build)')
        Grid.set_factor_from_resolution(*self.window.get_size())
        self.window.push_handlers(self)
        self.scene = None

    def load_scene(self, scene_class):
        context = None
        if self.scene:
            context = self.scene.context
            self.scene.unload()
        new_scene = scene_class(game=self, context=context)
        new_scene.load()
        self.scene = new_scene

    def on_draw(self):
        if not self.scene:
            logging.warning('No scene has been loaded')
            return
        self.window.clear()
        self.scene.draw()

    def on_resize(self, width, height):
        Grid.set_factor_from_resolution(width, height)
        if not self.scene:
            return
        self.scene.resize()

    def on_activate(self):
        self.on_draw()

    def on_key_press(self, symbol, modifiers):
        if not self.scene:
            return
        self.scene.on_key_press(symbol, modifiers)

    def on_key_release(self, symbol, modifiers):
        if not self.scene:
            return
        self.scene.on_key_release(symbol, modifiers)
Example #2
0
class ImageViewer:
    def __init__(self, display=None, maxwidth=500):
        self.window = None
        self.isopen = False
        self.display = display

    def __del__(self):
        self.close()

    def imshow(self, arr, caption):
        if self.window is None:
            height, width, _ = arr.shape
            self.window = Window(width=width,
                                 height=height,
                                 display=self.display,
                                 vsync=False,
                                 resizable=True)
            self.width = width
            self.height = height
            self.isopen = True
        assert len(arr.shape) == 3
        height, width, _ = arr.shape
        image = pyglet.image.ImageData(width,
                                       height,
                                       'RGB',
                                       arr.tobytes(),
                                       pitch=-3 * width)
        gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
                           gl.GL_NEAREST)
        texture = image.get_texture()
        texture.width = self.width
        texture.height = self.height
        self.window.clear()
        self.window.switch_to()
        self.window.dispatch_events()
        texture.blit(0, 0)
        self.window.flip()
        self.window.set_caption(caption)

    def close(self):
        if self.isopen:
            self.window.close()
            self.isopen = False
Example #3
0
class NumpyTube:
    def __init__(self):
        self.window = None
        self.isopen = False

    def __del__(self):
        self.close()

    def imshow(self, img, caption=None):
        height, width, _ = img.shape
        pitch = -3 * width

        if self.window is None:
            self.window = Window(width=width, height=height, vsync=False)
            self.width = width
            self.height = height
            self.isopen = True

        data = img.tobytes()
        image = pyglet.image.ImageData(width, height, "RGB", data, pitch=pitch)
        gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
                           gl.GL_NEAREST)

        texture = image.get_texture()
        texture.width = self.width
        texture.height = self.height

        self.window.clear()
        self.window.switch_to()
        self.window.dispatch_events()
        texture.blit(0, 0)
        self.window.flip()

        if caption is not None:
            self.window.set_caption(caption)

    def close(self):
        if self.isopen:
            self.window.close()
            self.window = None
            self.isopen = False
Example #4
0
 def test_caption(self):
     try:
         w1 = Window(400, 200, resizable=True)
         w2 = Window(400, 200, resizable=True)
         count = 1
         w1.set_caption('Window caption %d' % count)
         w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
         last_time = time.time()
         while not (w1.has_exit or w2.has_exit):
             if time.time() - last_time > 1:
                 count += 1
                 w1.set_caption('Window caption %d' % count)
                 last_time = time.time()
             w1.dispatch_events()
             w2.dispatch_events()
     finally:
         w1.close()
         w2.close()
     self.user_verify('Pass test?', take_screenshot=False)
Example #5
0
from pyglet.clock import ClockDisplay
from pyglet.clock import set_fps_limit
from pyglet.clock import schedule_interval
from pyglet.window import Window
from client.gui import Background
from client.gui import Button
from client.gui import QuitButton
from client.gui import TextWidget
from client.gui import UILabel
from client.gui import MyRectangle
from client.manager import GameManager
from client.view_objects import Player
from game.resources import Resources

game_window = Window(Resources.window_width, Resources.window_height)
game_window.set_caption("Push")
game_window.set_location(Resources.center_x,Resources.center_y)
fps = ClockDisplay()

manager = GameManager()
manager.set_window(game_window)

# Object Batches per state #
title_batch = Resources.batches['title']
setup_batch = Resources.batches['setup']
host_batch = Resources.batches['host']
join_batch = Resources.batches['join']
game_batch = Resources.batches['game']
end_batch = Resources.batches['end']
# End of Batches
cell_size = 10
cells_high = window_height / cell_size
cells_wide = window_width / cell_size

grid = [1 for cell in range(cells_high)]
grid = [grid[:] for cell in range(cells_wide)]
working_grid = deepcopy(grid)

born = {3}
survives = {2, 3, 8}

paused = False

window = Window(window_width, window_height)
window.set_caption("Cellular Automaton")


@window.event
def on_draw():
    window.clear()
    color_cells()
    draw_grid()


@window.event
def on_key_press(symbol, modifiers):
    global paused
    if symbol == key.ENTER:
        paused = not paused
    elif paused:
Example #7
0
File: lesson1.py Project: msarch/py
class Client:
    """
    While we aren't networking this game it's better to learn this structure now
    rather than later. Even if you never plan on learning how to network your
    games this is still a very good architecture to use.

    This Client class should be considered completely separate from the Game. It
    is just a way of interacting with the game. The game should not depend on
    anything in this class. Working like this will help you keep your code much
    cleaner and, as stated before, networkable. You could also make multiple
    clients using different technologies. In our case we are using pyglet and
    rabbyt libraries, but it wouldn't be difficult to make a client using pygame
    or even just the consol (for a text mode).
    """
    def __init__(self, game):
        # While the game needs to work independently of the client the client
        # can't work independently of the game. The client will be sending
        # input to the game as well as looking up different elements (such as
        # all the blocks so we can draw them and tell the game when we click on
        # one).
        self.game = game

        # Setup our pyglet window.
        self.window = Window(width=self.game.size_xy[0]*20,
                height=self.game.size_xy[1]*20+50)
        self.window.set_caption("Mines")
        self.window.on_close = sys.exit
        # The default pyglet OpenGL display is setup a bit different than how
        # rabbyt would like, thus rabbyt.set_default_attribs
        rabbyt.set_default_attribs()

        # Using pyglet for input is really easy. When you get further down
        # you'll see GameContorl inherits from EventDispatcher. That's how
        # window.push_handlers does the magic as we'll see further down.
        self.ctrl = GameContorl(self)
        self.window.push_handlers(self.ctrl)


        # Here we have some sprites we are going to use for the client. For
        # bigger games I think it's better to separate stuff like this out;
        # but this is quite small and not an issue.
        self.smile_face = rabbyt.Sprite("data/smile.png")
        self.smile_face.x = self.window.width/2
        self.smile_face.y = self.window.height-25

        self.dead_face = rabbyt.Sprite("data/smile_dead.png")
        self.dead_face.xy = self.smile_face.xy

        self.won_face = rabbyt.Sprite("data/smile_won.png")
        self.won_face.xy = self.smile_face.xy
        # That sprite stuff was pretty self explanatory. It is also very basic.
        # I'm not going to be going into much depth with rabbyt in these
        # tutorials so you may want to check out the rabbyt documentation from
        # http://matthewmarshall.org/projects/rabbyt/
        # Very cool and elegant stuff there. Check it out!

        self.clock = Clock()
        self.clock.set_fps_limit(20)
        self.window.push_handlers(self.clock)
        self.time = 0
        self.clock.schedule(self._add_time)

        self.setup()


    def setup(self):
        """
        Just like the setup in the Game class this one fills out the block data.
        But wait, why do we have to do this again? Remeber how in the GameBlock
        we only had stuff related to the game engine; no display stuff? Well,
        we need display stuff for the client - that's why we have ClientBlock!
        As you'll see soon the ClientBlock sorta wraps the GameBlock to provide
        the graphical stuff we need.
        """
        self.blocks = {}
        for key,b in self.game.blocks.items():
            self.blocks[key] = ClientBlock(self, b)


    def _add_time(self, dt):
        """
        This is kept track of so we can pass it onto rabbyt (so animation works)
        """
        self.time += dt


    def loop(self):
        """
        And here is our main game loop! In case you are new to game programming
        this is what is called every frame. This is where we will handle the
        display and stuff.
        """
        # clock.tick is used for keeping track of time and limiting the frame
        # rate.
        self.clock.tick()
        self.window.dispatch_events()
        # And this is where that mysterious "time" comes in. This way rabbyt
        # knows how much time has passed and can do the awesome animations.
        rabbyt.set_time(self.time)

        # If you are new to this sort of thing rabbyt.clear clears the screen
        # (erases what was drawn last loop). We pass white as the color that we
        # want to clear it with.
        rabbyt.clear((1,1,1,1))

        # And now we draw our blocks and smile face.
        for b in self.blocks.values():
            b.draw()

        if self.game.gameover == True:
            if self.game.won == False:
                self.dead_face.render()
            else:
                self.won_face.render()
        else:
            self.smile_face.render()

        # This draws the buffer onto the screen. Without this we would be
        # staring at a blank screen.
        self.window.flip()


    def press_block(self, block):
        """
        This is called by the Control as we will see later. Pretty simple and
        even unneeded. But this is where you could add cool effects for when
        you click on a block if you wannted to. (That's the reasion I have it)
        """
        self.game.press_block(block.gameblock)


    def retry(self):
        """
        Re-sets up the game.
        """
        self.game.setup()
        self.setup()
Example #8
0
"""Demonstrates creation of a transparent overlay window in pyglet
"""

import pyglet

from pyglet.graphics import Batch
from pyglet.window import Window

batch = Batch()
window = Window(500, 500, style=Window.WINDOW_STYLE_TRANSPARENT)
window.set_caption("Transparent Window")

circle = pyglet.shapes.Circle(250, 250, 100, color=(255, 255, 0), batch=batch)


@window.event
def on_draw():
    window.clear()
    batch.draw()


pyglet.app.run()
Example #9
0
class Client( object ):
    def __init__(self, app):
		self.app = app
		self.window = Window(	width=self.app.size[0],
		        				height=self.app.size[1], 
		        				style='dialog',
		        				resizable=False )

		self.window.set_caption("ASTAR MAZE")
		self.window.on_close = sys.exit
		self.ctrl = InputHandler(self)
		self.window.push_handlers(self.ctrl)

		self.clock = Clock()
		self.clock.set_fps_limit(30)
		self.window.push_handlers(self.clock)

		self.grid = ClientGrid( self.app.grid )

		# S q u a r e s
		self.entities = {}
		self.setup()


    def setup(self):
		glClearColor( .113, .121, .1289, 1 )
		glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA )
		glDisable( GL_LIGHTING )
		glCullFace( GL_BACK )
		glDisable( GL_DEPTH_TEST )

		self.runner = None
		self.goal = None
		self.isSearching = False
		self.found = False
		self.solution = []
		self.prev = None

		self.entitiesBatch = pyglet.graphics.Batch()
		group = ClientGroup()
		for k,v in self.app.squares.iteritems():
			verts = self.entitiesBatch.add( 4, GL_QUADS, group, 'v2i/static', 'c4B/dynamic' )
			verts.vertices 		= v.vertices['positions']
			verts.colors 		= v.vertices['colors']
			self.entities[k] 	= ClientSquare( v, verts )


    def draw(self):
		self.grid.draw()
		self.entitiesBatch.draw()
		if self.found: 
			curr = None
			if self.prev:
				self.setVisited( self.entities[self.prev] )
			if len(self.solution):
				curr = self.solution.pop()
				self.entities[curr].update( SquareType.RUNNER )
				self.prev = curr


    def update(self):
        self.clock.tick()
        self.window.dispatch_events()
        self.window.clear()
        self.draw()
        self.window.flip()


    def reset(self):
    	self.app.setup()
    	self.setup()


    def astar(self):
		startState = ASState( self.runner.pos, self.goal.pos, self )
		nodesGenerated = 1
		frontier = Heap()
		expanded = set()
		frontier.push( 0, ASNode( startState ) )

		while len(frontier):
			n = frontier.pop()

			if n.state.isGoal():
				self.solution = n.execute()
				print "%d node(s) generated.\n" % nodesGenerated
				return True

			successors = n.state.expand()
			for succ in successors:
				if succ['successor'] not in expanded:
					nodesGenerated = nodesGenerated + 1
					nprime = ASNode( succ['successor'], succ['action'], n )
					frontier.push( nprime.hCost, nprime )
					expanded.add( succ['successor'] )
		return False


    def search(self):
    	if not self.runner or not self.goal:
    		print "You must select a start and end position on the grid"
    		print "Press 1 and then click a square for start position (in purple)."
    		print "Press 2 and then click a square for end position (in red)."
    	else:
    		self.isSearching = True
    		print "\nRUNNING A*\n"
    		print "Goal position:   \t",		self.goal.pos
    		print "Start position:  \t",		self.runner.pos
    		print "Using heuristic: \t%s\n" 	% SETTINGS['HEURISTIC']

    		if self.astar():
    			self.found = True
    		else:
    			print "Failed to solve maze."
    		self.isSearching = False


    def pressSquare( self, sqr ):
		sqr.update( SquareType.BLOCKED )


    def resetSquare( self, sqr ):
		sqr.update( SquareType.EMPTY )

    
    def setStart( self, sqr ):
    	if not self.runner:
    		sqr.update( SquareType.START )
    		self.runner = sqr


    def setEnd( self, sqr ):
    	if not self.goal:
    		sqr.update( SquareType.GOAL )
    		self.goal = sqr

    def setVisited( self, sqr ):
    	sqr.update( SquareType.TRAIL )
Example #10
0
window_width = 640
window_height = 480

cell_size = 2
cells_high = window_height // cell_size
cells_wide = window_width // cell_size

grid = [1 for cell in range(cells_high)]
grid = [grid[:] for cell in range(cells_wide)]
working_grid = grid[:]

born = {3}
survives = {2, 3, 8}

window = Window(window_width, window_height)
window.set_caption("Cellular Automaton")


@window.event
def on_draw():
    window.clear()
    color_cells()


@window.event
def on_key_press(symbol, modifiers):
    if symbol == key.I:
        for x in range(cells_wide):
            for y in range(cells_high):
                grid[x][y] = 0
    elif symbol == key.O:
Example #11
0
"""Demonstrates creation of a transparent overlay window in pyglet
"""

import pyglet

from pyglet.graphics import Batch
from pyglet.window import Window

batch = Batch()
window = Window(500, 500, style=Window.WINDOW_STYLE_OVERLAY)
window.set_caption("Overlay Window")

circle = pyglet.shapes.Circle(250, 250, 100, color=(255, 255, 0), batch=batch)


@window.event
def on_draw():
    window.clear()
    batch.draw()


pyglet.app.run()
Example #12
0
File: Game.py Project: varnie/snake
class Game(object):

    INITIAL_UPDATE_INTERVAL = UPDATE_INTERVAL

    def __init__(self):
        impl.funcs.load_resources()
        self.gameInfo = GameInfo()
        self.win = Window(FIELD_WIDTH, FIELD_HEIGHT)
        self.win.set_caption("snake")
        impl.funcs.setup_background_color()
        impl.funcs.setup_opengl_blend_func()
        self.gameField = GameField(self.gameInfo, self.win)
        self.menu = Menu(FIELD_WIDTH//2, FIELD_HEIGHT//2, self.game_start_callback, self.game_exit_callback, self.win)
        self._overlay = None
        self._update_interval = Game.INITIAL_UPDATE_INTERVAL

        @self.gameField.event
        def on_restart_snake():
             unschedule(func=self.update)
             self._setup_overlay("restart")
             schedule_once(func=self.run_snake, delay=DELAY_FOR_NEW_RUN)

        @self.gameField.event
        def on_rerun_menu():
            unschedule(func=self.update)

            #reset current handler
            self.win.pop_handlers()
            #and setup update handler
            self.win.push_handlers(self.menu)
            self.menu.start_bgrn_animation()

        @self.gameField.event
        def on_game_over():
            unschedule(func=self.update)
            self._setup_overlay('game over...')
            schedule_once(func=self.game_exit_callback, delay=DELAY_FOR_EXIT)

        @self.gameField.event
        def on_score_up():
            if self._update_interval > MAX_UPDATE_SPEED_INTERVAL:
                self._update_interval -= UPDATE_INTERVAL_SPEED_DX
                unschedule(func=self.update)
                schedule_interval(func=self.update,interval=self._update_interval)

    def _setup_overlay(self, text):
        self._overlay = BouncingLabel(FIELD_WIDTH//2,FIELD_HEIGHT//2,text,DEFAULT_OVERLAY_COLOR)
        self.win.pop_handlers()
        def on_draw():
            self.win.clear()
            self._overlay.draw()
        self.win.push_handlers(on_draw)

        schedule_interval(func=self._overlay.update, interval=OVERLAY_UPDATE_INTERVAL)

    def game_start_callback(self):
        self._setup_overlay("start")
        schedule_once(func=self.run_snake, delay=DELAY_FOR_NEW_RUN)

    def game_exit_callback(self, *args):
        if self._overlay:
            unschedule(self._overlay.update)
            self._overlay = None

        self.win.pop_handlers()
        self.win.close()

    def start(self):
         self.win.push_handlers(self.menu)
         pyglet.app.run()

    def update(self, dt):
        if not self.gameInfo.pause:
            self.gameField.update(dt)

    def run_snake(self, *args):
        if self._overlay:
            unschedule(self._overlay.update)
            self._overlay = None

        #reset current handlers
        self.win.pop_handlers()

        self.gameInfo.pause = False
        self.gameField.reset()

        #setup new handlers
        self.win.push_handlers(self.gameField)

        #and setup update handler
        self._update_interval = Game.INITIAL_UPDATE_INTERVAL
        schedule_interval(func=self.update,interval=self._update_interval)
Example #13
0
from pyglet.clock import ClockDisplay
from pyglet.clock import set_fps_limit
from pyglet.clock import schedule_interval
from pyglet.window import Window
from client.gui import Background
from client.gui import Button
from client.gui import QuitButton
from client.gui import TextWidget
from client.gui import UILabel
from client.gui import MyRectangle
from client.manager import GameManager
from client.view_objects import Player
from game.resources import Resources

game_window = Window(Resources.window_width, Resources.window_height)
game_window.set_caption("Push")
game_window.set_location(Resources.center_x, Resources.center_y)
fps = ClockDisplay()

manager = GameManager()
manager.set_window(game_window)

# Object Batches per state #
title_batch = Resources.batches["title"]
setup_batch = Resources.batches["setup"]
host_batch = Resources.batches["host"]
join_batch = Resources.batches["join"]
game_batch = Resources.batches["game"]
end_batch = Resources.batches["end"]
# End of Batches
Example #14
0
class DivineOasis:
    def __init__(self, debug: bool = False):
        self.debug = debug

        if self.debug:
            if platform.system() == "Windows":
                # Set larger console
                os.system("mode con: cols=200 lines=9999")

        if platform.system() != "Linux":
            import pyglet_ffmpeg
            pyglet_ffmpeg.load_ffmpeg()

        # Enable Colours using black magic
        os.system("")

        # Setup Logging
        self.game_logger = self.setup_logging(debug)

        # Get basic system information
        self.system_data = {}
        self.system_info()

        # Basic classes
        self.game_config = Config()
        self.game_config.load()

        self.game_assets = Assets(self.game_config.get("language.lang"))

        # setup Pyglet
        pyglet.options['audio'] = ('openal', 'pulse', 'directsound', 'silent')
        vsync_enabled = self.game_config.get("graphics.vsync")

        self.window = Window(1280, 720)
        self.window.set_vsync(vsync_enabled)
        # TODO: Fix fullscreen mode
        # self.window.set_fullscreen(self.game_config.get("fullscreen"))
        self.window.set_caption(self.game_assets.get("lang.title.main_title"))

        fps_limit = self.game_config.get("graphics.fps")

        self.scene_manager = SceneManager(self.game_assets, self.window)
        if vsync_enabled:
            pyglet.clock.schedule(self.scene_manager.update)
        else:
            pyglet.clock.schedule_interval(self.scene_manager.update,
                                           1.0 / fps_limit)

    def start(self):
        self.game_logger.info(
            f"Starting Divine Oasis { divineoasis.__version__ }")

        # Start Pyglet loop
        pyglet.app.run()

    @staticmethod
    def setup_logging(debug: bool):
        if debug:
            level = "DEBUG"
        else:
            level = "INFO"

        logging.config.dictConfig({
            "version": 1,
            "disable_existing_loggers": False,
            "formatters": {
                "standard": {
                    "format":
                    "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
                }
            },
            "handlers": {
                "default": {
                    "class": "logging.StreamHandler",
                    "formatter": "standard"
                }
            },
            "loggers": {
                "": {
                    "handlers": ["default"],
                    "propagate": True,
                    "level": level
                }
            }
        })

        logging.addLevelName(
            logging.DEBUG,
            Colours.BOLD + Colours.BRIGHT_CYAN + "DEBUG" + Colours.RESET)
        logging.addLevelName(
            logging.INFO,
            Colours.BOLD + Colours.BRIGHT_BLUE + "INFO" + Colours.RESET)
        logging.addLevelName(
            logging.WARNING,
            Colours.BOLD + Colours.BRIGHT_YELLOW + "WARNING" + Colours.RESET)
        logging.addLevelName(
            logging.ERROR,
            Colours.BOLD + Colours.BRIGHT_RED + "ERROR" + Colours.RESET)
        logging.addLevelName(
            logging.CRITICAL, Colours.BOLD + Colours.BRIGHT_RED +
            Colours.BLINK + "CRITICAL" + Colours.RESET)

        return logging.getLogger(__name__)

    def system_info(self):
        self.system_data = {
            "arguments": sys.argv,
            "python_version": sys.version,
            "os": platform.system(),
            "os_release": platform.release(),
            "os_version": platform.version(),
            "os_arch": platform.machine(),
            "os_platform": platform.platform()
        }

        self.game_logger.debug(
            "=*=*=*=*=*=*=*=*=*=*=*= Debug Information =*=*=*=*=*=*=*=*=*=*=*="
        )
        self.game_logger.debug(
            f"        Arguments: { self.system_data['arguments'] }")
        self.game_logger.debug(
            f"   Python Version: { self.system_data['python_version'] }")
        self.game_logger.debug(
            f"               OS: { self.system_data['os'] }")
        self.game_logger.debug(
            f"       OS Version: { self.system_data['os_version'] }")
        self.game_logger.debug(
            f"       OS Release: { self.system_data['os_release'] }")
        self.game_logger.debug(
            f"  OS Architecture: { self.system_data['os_arch'] }")
        self.game_logger.debug(
            f"      OS Platform: { self.system_data['os_platform'] }")
        self.game_logger.debug(
            "=*=*=*=*=*=*=*=*=*=*=*=*=* Directories *=*=*=*=*=*=*=*=*=*=*=*=*="
        )
        self.game_logger.debug(
            f" Application Root: { Directories().application_root }")
        self.game_logger.debug(
            f" Assets Directory: { Directories().assets_directory }")
        self.game_logger.debug(
            f"   Data Directory: { Directories().data_directory }")
        self.game_logger.debug(
            f"  Config Location: { Directories().config_location }")
        self.game_logger.debug(
            "=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*="
        )