def animateTileChange(tilesToFlip, tileColor, additionalTile):
	# Draw the additional tile that was just laid down. (Otherwise we'd
	# have to completely redraw the board & the board info.)
	if tileColor == WHITE_TILE:
		additionalTileColor = WHITE
	else:
		additionalTileColor = BLACK
	additionalTileX, additionalTileY = translateBoardToPixelCoord(additionalTile[0], additionalTile[1])
	sdlgfx.filledCircleRGBA(REN.renderer, additionalTileX, additionalTileY, SPACESIZE//2 - 4, *additionalTileColor)
	REN.present()

	for rgbValues in range(0, 255, int(ANIMATIONSPEED * 2.55)):
		for event in ext.get_events():
			if event.type == SDL_QUIT:
				shutdown()
			elif event.type == SDL_KEYUP:
				sc = event.key.keysym.scancode
				if sc == SDL_SCANCODE_ESCAPE:
					shutdown()

		if rgbValues > 255:
			rgbValues = 255
		elif rgbValues < 0:
			rgbValues = 0

		if tileColor == WHITE_TILE:
			color = (rgbValues, rgbValues, rgbValues, 255) # rgbValues goes from 0 to 255
		elif tileColor == BLACK_TILE:
			color = (255 - rgbValues, 255 - rgbValues, 255 - rgbValues, 255) # rgbValues goes from 255 to 0

		for x, y in tilesToFlip:
			centerx, centery = translateBoardToPixelCoord(x, y)
			sdlgfx.filledCircleRGBA(REN.renderer, centerx, centery, SPACESIZE//2 - 4, *color)
		REN.present()
		SDL_Delay(1000//FPS)
Exemplo n.º 2
0
def run():
    WIDTH = 1600
    HEIGHT = 1200
    THICKNESS = 10
    LENGTH = 100
    RADIUS = 20
    sdlext.init()
    window = sdlext.Window("the PG", size=(WIDTH, HEIGHT))
    window.show()
    world = sdlext.World()

    spriterenderer = SoftwareRenderer(window)
    world.add_system(spriterenderer)
    factory = sdlext.SpriteFactory(sdlext.SOFTWARE)
    sp_paddle1 = factory.from_color(WHITE, (THICKNESS, LENGTH))
    sp_paddle2 = factory.from_color(WHITE, (THICKNESS, LENGTH))
    player1 = Player(world, sp_paddle1, 0, HEIGHT//2 - LENGTH//2)
    player2 = Player(world, sp_paddle2, WIDTH - THICKNESS, HEIGHT//2 - LENGTH//2)
    sp_ball = factory.from_color(WHITE, size=(RADIUS, RADIUS))
    movement = MovementSystem(0, 0, WIDTH, HEIGHT)
    world.add_system(movement)
    ball = Ball(world, sp_ball, WIDTH//2 - THICKNESS//2, HEIGHT//2 - RADIUS//2)
    ball.velocity.vx = 3

    running = True
    while running:
        events = sdlext.get_events()
        for event in events:
            if event.type == sdl2.SDL_QUIT:
                running = False
                break
        world.process()
    return 0
Exemplo n.º 3
0
def run(linefile):
	sdl2ext.init()
	for line in linefile:
		l = line.split()
		if len(l) == 0:
			pass
		elif l[0] == "pixels":
			xpix = int(l[1])
			ypix = int(l[2])
	window = sdl2ext.Window("Pixel Access", size=(xpix, ypix))
	window.show()
	renderer = sdl2ext.Renderer(window)
	running = True
	while running:
		events = sdl2ext.get_events()
		for event in events:
			if event.type == SDL_QUIT:
				running = False
				break
		with Timer() as t:
			grid = draw.dofile(linefile)
		print "=> elasped grid: %s s" % t.secs
		with Timer() as t:
			draw_pixels(renderer, xpix, ypix, grid)
		print "=> elasped render: %s s" % t.secs
		window.refresh()
	sdl2ext.quit()
	return 0
Exemplo n.º 4
0
    def checkEvents(self):
        for event in sdle.get_events():
            if event.type == sdl.SDL_QUIT:
                self.running = False
                break
            if event.type == sdl.SDL_KEYDOWN:
                self.keys[event.key.keysym.sym] = True

            if event.type == sdl.SDL_KEYUP:
                self.keys[event.key.keysym.sym] = False

        if self.keyDown(sdl.SDLK_DOWN):
            s = self.entities['test'].sprite()
            self.entities['test'].yspeed = self.entities['test'].yspeed + 0.5

        if self.keyDown(sdl.SDLK_UP):
            s = self.entities['test'].sprite()
            self.entities['test'].yspeed = self.entities['test'].yspeed - 0.5

        if self.keyDown(sdl.SDLK_RIGHT):
            s = self.entities['test'].sprite()
            self.entities['test'].xspeed = self.entities['test'].xspeed + 0.5

        if self.keyDown(sdl.SDLK_LEFT):
            s = self.entities['test'].sprite()
            self.entities['test'].xspeed = self.entities['test'].xspeed - 0.5
Exemplo n.º 5
0
    def __init__(self, naki_pattern, textbox_manager, world):
        self.naki_pattern = naki_pattern
        self.textbox_manager = textbox_manager
        self.world = world
        self.button_names = list()
        self.buttons = list()

        for pattern in naki_pattern:
            self.textbox_manager.make_button(pattern)
            self.button_names.append(pattern)
            self.buttons.append(self.textbox_manager.entity_dict[pattern])
        self.world.process()

        while True:
            events = sdl2ext.get_events()
            for event in events:
                if event.type == SDL_QUIT:
                    running = False
                    break
                elif event.type == SDL_MOUSEBUTTONDOWN:
                    for i, button in enumerate(self.buttons):
                        if sprite_mouse_overlap(button.sprite, event.button):
                            self.command = button.textbox.name
                            break
                    else:
                        self.command = None
                    for button_name in self.button_names:
                        self.textbox_manager.del_button(button_name)
                    world.process()

                    return

            SDL_Delay(10)
            world.process()
Exemplo n.º 6
0
    def process_input(self):
        """Process buffered input and dispatch resulting events."""
        events = sdl_ext.get_events()
        for evt in events:
            if evt.type in {sdl.SDL_KEYUP}:
                key_event = evt.key
                send_event(KeyPressEvent(key_event.keysym.sym))

            elif evt.type in {sdl.SDL_MOUSEMOTION}:
                mouse_motion = evt.motion
                send_event(MouseMoveEvent(mouse_motion.x, mouse_motion.y))

            elif evt.type in {sdl.SDL_MOUSEBUTTONDOWN, sdl.SDL_MOUSEBUTTONUP}:
                mouse_event = evt.button

                if mouse_event.button == sdl.SDL_BUTTON_LEFT:
                    button = MouseClickEvent.Button.left
                elif mouse_event.button == sdl.SDL_BUTTON_RIGHT:
                    button = MouseClickEvent.Button.right
                else:
                    button = MouseClickEvent.Button.unknown

                if evt.type == sdl.SDL_MOUSEBUTTONDOWN:
                    state = MouseClickEvent.State.down
                else:
                    state = MouseClickEvent.State.up

                send_event(
                    MouseClickEvent(mouse_event.x, mouse_event.y, button,
                                    state))
Exemplo n.º 7
0
    def process_input(self):
        """Process buffered input and dispatch resulting events."""
        events = sdl_ext.get_events()
        for evt in events:
            if evt.type in {sdl.SDL_KEYUP}:
                key_event = evt.key
                send_event(KeyPressEvent(key_event.keysym.sym))

            elif evt.type in {sdl.SDL_MOUSEMOTION}:
                mouse_motion = evt.motion
                send_event(MouseMoveEvent(mouse_motion.x, mouse_motion.y))

            elif evt.type in {sdl.SDL_MOUSEBUTTONDOWN, sdl.SDL_MOUSEBUTTONUP}:
                mouse_event = evt.button

                if mouse_event.button == sdl.SDL_BUTTON_LEFT:
                    button = MouseClickEvent.Button.left
                elif mouse_event.button == sdl.SDL_BUTTON_RIGHT:
                    button = MouseClickEvent.Button.right
                else:
                    button = MouseClickEvent.Button.unknown

                if evt.type == sdl.SDL_MOUSEBUTTONDOWN:
                    state = MouseClickEvent.State.down
                else:
                    state = MouseClickEvent.State.up

                send_event(MouseClickEvent(
                    mouse_event.x,
                    mouse_event.y,
                    button,
                    state))
Exemplo n.º 8
0
def run(linefile):
	sdl2ext.init()
	for line in linefile:
		l = line.split()
		if len(l) == 0:
			pass
		elif l[0] == "pixels":
			xpix = int(l[1])
			ypix = int(l[2])
	window = sdl2ext.Window("Pixel Access", size=(xpix, ypix))
	window.show()
	windowsurface = window.get_surface()
	running = True
	while running:
		events = sdl2ext.get_events()
		for event in events:
			if event.type == SDL_QUIT:
				running = False
				break
		grid = draw.dofile(linefile)
		draw_pixels(windowsurface, xpix, ypix, grid)
		window.refresh()
	sdl2ext.quit()
	return 0
	'''		
Exemplo n.º 9
0
def pump(return_events=False):
    """Pumps the SDL2 event queue and appends its contents to the EventManager log.
	The SDL2 event queue contains SDL_Event objects representing keypresses, mouse
	movements, mouse clicks, and other input events that have occured since last
	check.

	Pumping the SDL2 event queue clears its contents, so be careful of calling it
	(or functions that call it implicitly) multiple times in the same loop, as it
	may result in unexpected problems watching for input (e.g if you have two
	functions checking for mouse clicks within two different boundaries and both
	call pump(), the second one will only return True if a click within that boundary
	occurred within the sub-millisecond interval between the first and second functions.)
	To avoid these problems, you can manually fetch the queue once per loop and pass its
	contents to each of the functions in the loop inspecting user input.

	Args:
		return_events (bool): If true, returns the contents of the SDL2 event queue.

	Returns:
		A list of SDL_Event objects, if return_events=True. Otherwise, the return 
		value is None.

	"""
    SDL_PumpEvents()

    if return_events:
        return get_events()
Exemplo n.º 10
0
    def poll(self):
        key_get = self._key_conversions.get
        mouse_button_get = self._mouse_conversions.get
        window_height = conf.get_resolution()[1]

        for event in sdl2_ext.get_events():
            if event.type == sdl2.SDL_QUIT:
                raise SystemExit
            elif event.type == sdl2.SDL_KEYDOWN:
                self.process_key_down(key_get(event.key.keysym.sym))
            elif event.type == sdl2.SDL_KEYUP:
                self.process_key_up(key_get(event.key.keysym.sym))
            elif event.type == sdl2.SDL_MOUSEMOTION:
                event = event.motion
                x = event.x
                y = window_height - event.y
                self.process_mouse_motion((x, y))
            elif event.type == sdl2.SDL_MOUSEBUTTONUP:
                event = event.button
                x = event.x
                y = window_height - event.y
                button = mouse_button_get(event.button)
                self.process_mouse_button_up(button, (x, y))
            elif event.type == sdl2.SDL_MOUSEBUTTONDOWN:
                event = event.button
                x = event.x
                y = window_height - event.y
                button = mouse_button_get(event.button)
                self.process_mouse_button_down(button, (x, y))

        self.process_long_press()
        self.process_mouse_longpress()
Exemplo n.º 11
0
    def poll(self):
        key_get = self._key_conversions.get
        mouse_button_get = self._mouse_conversions.get
        window_height = conf.get_resolution()[1]

        for event in sdl2_ext.get_events():
            if event.type == sdl2.SDL_QUIT:
                raise SystemExit
            elif event.type == sdl2.SDL_KEYDOWN:
                self.process_key_down(key_get(event.key.keysym.sym))
            elif event.type == sdl2.SDL_KEYUP:
                self.process_key_up(key_get(event.key.keysym.sym))
            elif event.type == sdl2.SDL_MOUSEMOTION:
                event = event.motion
                x = event.x
                y = window_height - event.y
                self.process_mouse_motion((x, y))
            elif event.type == sdl2.SDL_MOUSEBUTTONUP:
                event = event.button
                x = event.x
                y = window_height - event.y
                button = mouse_button_get(event.button)
                self.process_mouse_button_up(button, (x, y))
            elif event.type == sdl2.SDL_MOUSEBUTTONDOWN:
                event = event.button
                x = event.x
                y = window_height - event.y
                button = mouse_button_get(event.button)
                self.process_mouse_button_down(button, (x, y))

        self.process_long_press()
        self.process_mouse_longpress()
Exemplo n.º 12
0
        def hora_check_phase(player):

            if player.hand.hora_flag(
                    player.hand.contents,
                    player.hand.hand[-1],
                    False
                    ) and \
                    player.naki_status in [None,'kan']:
                print("You Tsumo?")
                self.textbox_manager.make_button('tsumo')
                while True:

                    events = sdl2ext.get_events()
                    for event in events:
                        if event.type == SDL_QUIT:
                            running = False
                            return
                        elif event.type == SDL_MOUSEBUTTONDOWN:
                            if sprite_mouse_overlap(self.textbox_manager.entity_dict['tsumo'].sprite, event.button):

                                player.hand.agarihai = player.hand.tsumohai
                                #TODO:上がりはいが-1の時はこれでいいのか。いつ起こる。とりあえずここで止める
                                if player.hand.agarihai == -1:
                                    input()
                                    player.hand.agarihai = player.hand.hand[0]
                                hora_process(player)
                                self.textbox_manager.del_button('tsumo')
                                return True
                            else:
                                self.textbox_manager.del_button('tsumo')
                                return False


            else:
                return False
Exemplo n.º 13
0
def run():
    # init sdl and get window up
    sdl2ext.init()
    window = sdl2ext.Window("Traction Edge RL", size=(800, 600))
    window.show()

    #create hardware accelerated context for drawing on
    context = sdl2ext.RenderContext(window, index=-1, flags=SDL_RENDERER_ACCELERATED)
    #create our custom renderer with the context
    renderer = systems.Renderer(context)

    # init world
    world = sdl2ext.World()
    world.add_system(renderer)

    # create our sprites
    factory = sdl2ext.SpriteFactory(sprite_type=sdl2ext.TEXTURE, renderer=context)
    sp_player = factory.from_color(WHITE, size=(32,32))

    #create player
    player = entities.Creature(world, sp_player, 100, 400)


    #main loop
    running = True
    while running:
        events = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
        SDL_Delay(10)
        world.process()
    return 
Exemplo n.º 14
0
def run():
    # You know those from the helloworld.py example.
    # Initialize the video subsystem, create a window and make it visible.
    sdl2ext.init()
    TTF_Init()
    window = sdl2ext.Window("2D drawing primitives", size=(800, 600))
    window.show()

    # As in colorpalettes.py, explicitly acquire the window's surface to
    # draw on.
    windowsurface = window.get_surface()

    fps = FPS(windowsurface)

    # We implement the functionality as it was done in colorpalettes.py and
    # utilise a mapping table to look up the function to be executed, together
    # with the arguments they should receive
    functions = ((draw_lines, (windowsurface, 800, 600)),
                 (draw_rects, (windowsurface, 800, 600)))

    # A storage variable for the function we are currently on, so that we know
    # which function to execute next.
    curindex = 0
    draw_lines(windowsurface, 800, 600)

    textSurface = TTF_RenderText_Shaded(font,
                                        repr(SDL_GetPerformanceFrequency()),
                                        SDL_Color(255, 255, 255),
                                        SDL_Color(40, 90, 120))

    # The event loop is nearly the same as we used in colorpalettes.py. If you
    # do not know, what happens here, take a look at colorpalettes.py for a
    # detailled description.
    running = True
    while running:
        events = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
            if event.type == SDL_MOUSEBUTTONDOWN:
                curindex += 1
                if curindex >= len(functions):
                    curindex = 0
                # In contrast to colorpalettes.py, our mapping table consists
                # of functions and their arguments. Thus, we get the currently
                # requested function and argument tuple and execute the
                # function with the arguments.
                func, args = functions[curindex]
                func(*args)
                break
        textSurface = TTF_RenderText_Shaded(
            font, "FPS: " + str(SDL_GetPerformanceFrequency()),
            SDL_Color(255, 255, 255), SDL_Color(40, 90, 120))
        SDL_BlitSurface(textSurface, None, windowsurface, None)
        window.refresh()
    TTF_Quit()
    sdl2ext.quit()
    return 0
Exemplo n.º 15
0
def run():
    sdl2ext.init()
    window = sdl2ext.Window("The Pong Game", size=(800, 600))
    window.show()

    if "-hardware" in sys.argv:
        print("Using hardware acceleration")
        renderer = sdl2ext.RenderContext(window)
        factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer)
    else:
        print("Using software rendering")
        factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)

    # Create the paddles - we want white ones. To keep it easy enough for us,
    # we create a set of surfaces that can be used for Texture- and
    # Software-based sprites.
    sp_paddle1 = factory.from_color(WHITE, size=(20, 100))
    sp_paddle2 = factory.from_color(WHITE, size=(20, 100))
    sp_ball = factory.from_color(WHITE, size=(20, 20))

    world = World()

    movement = MovementSystem(0, 0, 800, 600)
    collision = CollisionSystem(0, 0, 800, 600)
    aicontroller = TrackingAIController(0, 600)
    if factory.sprite_type == sdl2ext.SOFTWARE:
        spriterenderer = SoftwareRenderer(window)
    else:
        spriterenderer = TextureRenderer(renderer)

    world.add_system(aicontroller)
    world.add_system(movement)
    world.add_system(collision)
    world.add_system(spriterenderer)

    player1 = Player(world, sp_paddle1, 0, 250)
    player2 = Player(world, sp_paddle2, 780, 250, True)
    ball = Ball(world, sp_ball, 390, 290)
    ball.velocity.vx = -BALL_SPEED
    collision.ball = ball
    aicontroller.ball = ball

    running = True
    while running:
        for event in sdl2ext.get_events():
            if event.type == sdlevents.SDL_QUIT:
                running = False
                break
            if event.type == sdlevents.SDL_KEYDOWN:
                if event.key.keysym.sym == sdlkc.SDLK_UP:
                    player1.velocity.vy = -PADDLE_SPEED
                elif event.key.keysym.sym == sdlkc.SDLK_DOWN:
                    player1.velocity.vy = PADDLE_SPEED
            elif event.type == sdlevents.SDL_KEYUP:
                if event.key.keysym.sym in (sdlkc.SDLK_UP, sdlkc.SDLK_DOWN):
                    player1.velocity.vy = 0
        sdltimer.SDL_Delay(10)
        world.process()
Exemplo n.º 16
0
def run():
	# You know those from the helloworld.py example.
	# Initialize the video subsystem, create a window and make it visible.
	sdl2ext.init()
	TTF_Init()
	window = sdl2ext.Window("2D drawing primitives", size=(800, 600))
	window.show()
	

	# As in colorpalettes.py, explicitly acquire the window's surface to
	# draw on.
	windowsurface = window.get_surface()
	
	fps = FPS(windowsurface)

	# We implement the functionality as it was done in colorpalettes.py and
	# utilise a mapping table to look up the function to be executed, together
	# with the arguments they should receive
	functions = ((draw_lines, (windowsurface, 800, 600)),
				 (draw_rects, (windowsurface, 800, 600))
				 )

	# A storage variable for the function we are currently on, so that we know
	# which function to execute next.
	curindex = 0
	draw_lines(windowsurface, 800, 600)
	

	textSurface = TTF_RenderText_Shaded(font, repr(SDL_GetPerformanceFrequency()), SDL_Color(255, 255, 255), SDL_Color(40, 90, 120))
			
	# The event loop is nearly the same as we used in colorpalettes.py. If you
	# do not know, what happens here, take a look at colorpalettes.py for a
	# detailled description.
	running = True
	while running:
		events = sdl2ext.get_events()
		for event in events:
			if event.type == SDL_QUIT:
				running = False
				break
			if event.type == SDL_MOUSEBUTTONDOWN:
				curindex += 1
				if curindex >= len(functions):
					curindex = 0
				# In contrast to colorpalettes.py, our mapping table consists
				# of functions and their arguments. Thus, we get the currently
				# requested function and argument tuple and execute the
				# function with the arguments.
				func, args = functions[curindex]
				func(*args)
				break
		textSurface = TTF_RenderText_Shaded(font,"FPS: " + str(SDL_GetPerformanceFrequency()), SDL_Color(255, 255, 255), SDL_Color(40, 90, 120))
		SDL_BlitSurface(textSurface, None, windowsurface, None)
		window.refresh()
	TTF_Quit()
	sdl2ext.quit()
	return 0
Exemplo n.º 17
0
 def handle_input(self) -> None:
     events = get_events()
     for event in events:
         if event.type == SDL_QUIT:
             self.inputs[Input.QUIT] = True
         elif event.type == SDL_KEYDOWN:
             self.inputs[to_input(event.key.keysym.sym)] = True
         elif event.type == SDL_KEYUP:
             self.inputs[to_input(event.key.keysym.sym)] = False
Exemplo n.º 18
0
def checkForKeyPress():
    for event in ext.get_events():
        if event.type == SDL_QUIT:
            shutdown()
        elif event.type == SDL_KEYUP:
            sc = event.key.keysym.scancode
            if sc == SDL_SCANCODE_ESCAPE:
                shutdown()
            return event.key.keysym.scancode
Exemplo n.º 19
0
 def loop(self, id):
     # processa eventos
     events = sdlx.get_events()
     for ev in events:
         if ev.type == sdl.SDL_QUIT:
             self.close(id)
             return
     # atualiza os fps e tela
     self.conexões[id].update()
def checkForKeyPress():
	for event in ext.get_events():
		if event.type == SDL_QUIT:
			shutdown()
		elif event.type == SDL_KEYUP:
			sc = event.key.keysym.scancode
			if sc == SDL_SCANCODE_ESCAPE:
				shutdown()
			return event.key.keysym.scancode
Exemplo n.º 21
0
 def process_input(self):
     events = get_events()
     for evt in events:
         if evt.type == sdl.SDL_KEYDOWN:
             self.events.append(KeyEvent(
                 evt.key.keysym.sym, KeyEvent.State.down))
         elif evt.type == sdl.SDL_KEYUP:
             self.events.append(KeyEvent(
                 evt.key.keysym.sym, KeyEvent.State.up))
Exemplo n.º 22
0
 def run(self):
     """Main loop of the state."""
     delta = self.clock.tick()
     while self.running:
         delta = self.clock.tick()
         for event in ext.get_events():
             self.handle_event(event)
         self.update(delta)
         self.draw()
Exemplo n.º 23
0
def run():
    # print sdl2ext.get_image_formats()
    # return
    sdl2ext.init()
    window = sdl2ext.Window("The Pong Game", size=(800, 600))
    window.show()

    world = sdl2ext.World()

    factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)
    sp_ball = factory.from_color(WHITE, size=(20, 20))
    sp_paddle1 = factory.from_color(WHITE, size=(20, 100))
    sp_paddle2 = factory.from_color(WHITE, size=(20, 100))


    movement = MovementSystem(0, 0, 800, 600)
    collision = CollisionSystem(0, 0, 800, 600, 390, 290)
    aicontroller = TrackingAIController(0, 600)

    spriterenderer = SoftwareRenderer(window)

    world.add_system(aicontroller)
    world.add_system(movement)
    world.add_system(collision)
    world.add_system(spriterenderer)

    player1 = Player(world, sp_paddle1, 0, 250)
    player2 = Player(world, sp_paddle2, 780, 250, True)

    ball = Ball(world, sp_ball, 390, 290)
    ball.velocity.vx = -3

    collision.ball = ball
    aicontroller.ball = ball

    collision.player1 = player1
    collision.player2 = player2

    running = True
    while running:
        events = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
            if event.type == SDL_KEYDOWN:
                if event.key.keysym.sym == SDLK_UP:
                    player1.velocity.vy = -3
                elif event.key.keysym.sym == SDLK_DOWN:
                    player1.velocity.vy = 3
            elif event.type == SDL_KEYUP:
                if event.key.keysym.sym in (SDLK_UP, SDLK_DOWN):
                    player1.velocity.vy = 0
        SDL_Delay(10)
        world.process()
    return 0
Exemplo n.º 24
0
 def start(self):
     if not self.initialize():
         sys.exit(-1)
     while self.running:
         events = sdlx.get_events()
         for event in events:
             self.process_event(event)
         self.render()
     self.cleanup()
     sys.exit(0)
Exemplo n.º 25
0
 def start(self):
     if not self.initialize():
         sys.exit(-1)
     while self.running:
         events = sdlx.get_events()
         for event in events:
             self.process_event(event)
         self.render()
     self.cleanup()
     sys.exit(0)
Exemplo n.º 26
0
def run():
    # print sdl2ext.get_image_formats()
    # return
    sdl2ext.init()
    window = sdl2ext.Window("The Pong Game", size=(800, 600))
    window.show()

    world = sdl2ext.World()

    factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)
    sp_ball = factory.from_color(WHITE, size=(20, 20))
    sp_paddle1 = factory.from_color(WHITE, size=(20, 100))
    sp_paddle2 = factory.from_color(WHITE, size=(20, 100))

    movement = MovementSystem(0, 0, 800, 600)
    collision = CollisionSystem(0, 0, 800, 600, 390, 290)
    aicontroller = TrackingAIController(0, 600)

    spriterenderer = SoftwareRenderer(window)

    world.add_system(aicontroller)
    world.add_system(movement)
    world.add_system(collision)
    world.add_system(spriterenderer)

    player1 = Player(world, sp_paddle1, 0, 250)
    player2 = Player(world, sp_paddle2, 780, 250, True)

    ball = Ball(world, sp_ball, 390, 290)
    ball.velocity.vx = -3

    collision.ball = ball
    aicontroller.ball = ball

    collision.player1 = player1
    collision.player2 = player2

    running = True
    while running:
        events = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
            if event.type == SDL_KEYDOWN:
                if event.key.keysym.sym == SDLK_UP:
                    player1.velocity.vy = -3
                elif event.key.keysym.sym == SDLK_DOWN:
                    player1.velocity.vy = 3
            elif event.type == SDL_KEYUP:
                if event.key.keysym.sym in (SDLK_UP, SDLK_DOWN):
                    player1.velocity.vy = 0
        SDL_Delay(10)
        world.process()
    return 0
Exemplo n.º 27
0
    def run(self):
        menu_input = Input()

        last_update_time = SDL_GetTicks()  # units.MS

        while self.running:
            start_time = SDL_GetTicks()  # units.MS

            menu_input.begin_new_frame()
            menu_events = get_events()

            for event in menu_events:
                if event.type == SDL_KEYDOWN:
                    menu_input.key_down_event(event)

                elif event.type == SDL_KEYUP:
                    menu_input.key_up_event(event)

                elif event.type == SDL_QUIT:
                    self.running = False
                    break

            # Exit
            if menu_input.was_key_pressed(SDLK_ESCAPE):
                self.running = False

            # Move the cursor
            elif menu_input.was_key_pressed(SDLK_UP):
                if self.cursor_position != 0:
                    self.cursor_position -= 1
            elif menu_input.was_key_pressed(SDLK_DOWN):
                if self.cursor_position != 4:
                    self.cursor_position += 1

            # Select option
            elif menu_input.was_key_pressed(SDLK_RETURN):
                self.running = False
                if self.cursor_position == 0:
                    self.launch_game()

            current_time = SDL_GetTicks()  # units.MS
            elapsed_time = current_time - last_update_time  # units.MS

            self.update(min(elapsed_time, MAX_FRAME_TIME))

            last_update_time = current_time

            self.renderer.process(self.world, self.sprites)

            # This loop lasts 1/60th of a second, or 1000/60th ms
            ms_per_frame = 1000 // FPS  # units.MS
            elapsed_time = SDL_GetTicks() - start_time  # units.MS
            if elapsed_time < ms_per_frame:
                SDL_Delay(ms_per_frame - elapsed_time)
Exemplo n.º 28
0
    def gui_trash_parse(self, player):
        self.reach = False
        self.kan = False
        self.state = True
        self.button_names = []
        if not player.reach and \
                player.hand.mensen:
            self.textbox_manager.make_button('reach')
            self.button_names.append('reach')

        if 4 in player.hand.contents:
            self.textbox_manager.make_button('kan')
            self.button_names.append('kan')
        self.world.process()
        while True:
            events = sdl2ext.get_events()
            if (player.reach and\
                    self.hai == player.hand.tsumohai) or \
                    ((not player.reach)and\
                    self.number != None):
                for button_name in self.button_names:
                    self.textbox_manager.del_button(button_name)
                self.world.process()
                break

            for event in events:
                if event.type == SDL_QUIT:
                    running = False
                    break
                elif event.type == SDL_MOUSEMOTION:
                    for hai in player.hand.entities:
                        if hai.sprite.y < player.hand_pos[1] - 30:
                            continue
                        elif sprite_mouse_overlap(hai.sprite, event.motion):
                            hai.velocity.vy = -1
                        else:
                            hai.velocity.vy = 1
                elif event.type == SDL_MOUSEBUTTONDOWN:
                    for i, hai in enumerate(player.hand.entities):
                        if sprite_mouse_overlap(hai.sprite, event.button):
                            self.hai = hai.hai
                            self.hai_entity = hai
                            self.number = self.hai.number

#TODO:カンとリーチどっちもできてしまう
                    for button_name in self.button_names:
                        if sprite_mouse_overlap(self.textbox_manager.entity_dict[button_name].sprite, event.button):
                            if button_name == 'reach':
                                self.reach = not self.reach
                            elif button_name == 'kan':
                                self.kan = not self.kan

            SDL_Delay(10)
            self.world.process()
Exemplo n.º 29
0
 def test_get_events_issue_6(self):
     sdl2ext.init()
     SDL_FlushEvent(SDL_FIRSTEVENT, SDL_LASTEVENT)
     for x in range(12):
         event = SDL_Event()
         event.type = SDL_USEREVENT + x
         event.user = SDL_UserEvent(type=event.type, timestamp=0,
                                    windowID=0, code=0)
         SDL_PushEvent(event)
     results = sdl2ext.get_events()
     for idx, r in enumerate(results):
         self.assertEqual(idx, r.type - SDL_USEREVENT)
Exemplo n.º 30
0
    def update(self) -> None:
        self.events.clear()
        for event in get_events():
            if event.type == SDL_MOUSEBUTTONDOWN:
                self.events.append((event.button.x, event.button.y))
            elif event.type == SDL_QUIT:
                quit()

        self.renderer.present()  # Presenting renderer
        self.renderer.clear(color=(0, 0, 0, 255))  # Clearing renderer

        self.refresh()  # Refreshing window
Exemplo n.º 31
0
 def test_get_events(self):
     sdl2ext.init()
     SDL_FlushEvent(SDL_FIRSTEVENT, SDL_LASTEVENT)
     for x in range(10):
         event = SDL_Event()
         event.type = SDL_USEREVENT + 1
         event.user = SDL_UserEvent(type=event.type, timestamp=0,
                                    windowID=0, code=0)
         SDL_PushEvent(event)
     results = sdl2ext.get_events()
     self.assertEqual(len(results), 10)
     for ev in results:
         self.assertEqual(ev.type, (SDL_USEREVENT + 1))
Exemplo n.º 32
0
def run():
    # You know those from the helloworld.py example.
    # Initialize the video subsystem, create a window and make it visible.
    sdl2ext.init()
    window = sdl2ext.Window("sdlgfx drawing examples", size=(800, 600))
    window.show()

    # Create a rendering context for the window. The sdlgfx module requires it.
    context = sdl2ext.RenderContext(window)

    # We implement the functionality as it was done in colorpalettes.py and
    # utilise a mapping table to look up the function to be executed, together
    # with the arguments they should receive
    functions = ((draw_lines, (context, 800, 600)),
                 (draw_circles, (context, 800, 600)),
                 (draw_ellipsis, (context, 800, 600)),
                 (draw_rects, (context, 800, 600)),
                 (draw_trigons, (context, 800, 600)),
                 (draw_polygons, (context, 800, 600)),
                 (draw_mixed, (context, 800, 600))
                 )

    # A storage variable for the function we are currently on, so that we know
    # which function to execute next.
    curindex = 0
    draw_lines(context, 800, 600)

    # The event loop is nearly the same as we used in colorpalettes.py. If you
    # do not know, what happens here, take a look at colorpalettes.py for a
    # detailed description.
    running = True
    while running:
        events = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
            if event.type == SDL_MOUSEBUTTONDOWN:
                curindex += 1
                if curindex >= len(functions):
                    curindex = 0
                # In contrast to colorpalettes.py, our mapping table consists
                # of functions and their arguments. Thus, we get the currently
                # requested function and argument tuple and execute the
                # function with the arguments.
                func, args = functions[curindex]
                func(*args)
                break
        context.present()
    sdl2ext.quit()
    return 0
Exemplo n.º 33
0
def run():
    sdl2ext.init()
    sdlttf.TTF_Init(SDL_INIT_EVERYTHING)

    font = sdlttf.TTF_OpenFont(str.encode("himalaya.ttf"), 300)
    flags = SDL_WINDOW_SHOWN
    color = sdlttf.SDL_Color(255, 255, 255, 255)
    tibstring = 'བསྐྱོངས་'
    sdlstr = (ctypes.c_uint16 * len(tibstring))(*map(ord, tibstring))

    window = SDL_CreateWindow(b'TTF TEST',
                              SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED,
                              800,
                              600,
                              flags)

    renderer = SDL_CreateRenderer(window,
                                  -1,
                                  SDL_RENDERER_ACCELERATED |
                                  SDL_RENDERER_PRESENTVSYNC)

    # message = sdlttf.TTF_RenderUTF8_Blended(font,
    #                                         str.encode(tibstring),
    #                                         color)

    message = sdlttf.TTF_RenderUNICODE_Blended(
        font,
        sdlstr,
        color)

    tex = SDL_CreateTextureFromSurface(renderer, message)
    dst = SDL_Rect(0, 0, 640, 480)

    SDL_RenderCopy(renderer, tex, None, dst)
    SDL_ShowWindow(window)

    running = True

    while running:
        events = sdl2ext.get_events()

        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break

        SDL_RenderPresent(renderer)

    return 0
Exemplo n.º 34
0
    def start(self):
        """ Main application loop
        """
        if sdl.SDL_Init(sdl.SDL_INIT_EVERYTHING) < 0:
            return False

        sdl.SDL_GL_SetAttribute(sdl.SDL_GL_DOUBLEBUFFER, 1)
        self.window = sdl.SDL_CreateWindow(self.cfg.window.title,
                                           sdl.SDL_WINDOWPOS_CENTERED,
                                           sdl.SDL_WINDOWPOS_CENTERED,
                                           self.cfg.window.width,
                                           self.cfg.window.height,
                                           WND_FLAGS
        )
        if not self.window: return False


        if not self.initialize():
            # Log error instead
#            sys.stderr.write(msg.viz_gl_init_fail+msg.newline)
            sys.exit(1)
        while self.running:
            frameStart = sdl.SDL_GetTicks()
            events = sdlx.get_events()
            for event in events:
                self.process_event(event)
            eventsEnd = sdl.SDL_GetTicks()
            self.frameStats.inputSum += eventsEnd - frameStart
            # Simulate
            if self.runSimulation: self.sim.step()
            simEnd = sdl.SDL_GetTicks()
            self.frameStats.simulationSum += simEnd - eventsEnd
            self.renderer.render(self.window, self.userController)
            renderEnd = sdl.SDL_GetTicks()
            self.frameStats.renderSum += renderEnd - simEnd
            # Agents calculations
            # (a1, a2, ...)
            agentsEnd = sdl.SDL_GetTicks()
            self.frameStats.agentSum += agentsEnd - renderEnd
            # Calculate compensation for the frame rate
            self.frameStats.count += 1
            frameDuration = agentsEnd - frameStart
            self.frameStats.totalSum += frameDuration
            delay = int(self.targetFrameDuration - frameDuration)
            self.frameStats.delaySum += delay
            if frameDuration < self.targetFrameDuration:
                sdl.SDL_Delay(delay)
        self.cleanup()
        sys.exit(0)
Exemplo n.º 35
0
def run():
    # You know those from the helloworld.py example.
    # Initialize the video subsystem, create a window and make it visible.
    sdl2ext.init()
    window = sdl2ext.Window("Pixel Access", size=(800, 600))
    window.show()

    # As in colorpalettes.py, explicitly acquire the window's surface to
    # draw on.
    windowsurface = window.get_surface()

    # We implement the functionality as it was done in colorpalettes.py and
    # utilise a mapping table to look up the function to be executed, together
    # with the arguments they should receive
    functions = (
        (draw_horizontal_stripes, (windowsurface, 300, 500, 200, 400)),
        (draw_vertical_stripes, (windowsurface, 300, 500, 200, 400)),
    )

    # A storage variable for the function we are currently on, so that we know
    # which function to execute next.
    curindex = 0
    draw_horizontal_stripes(windowsurface, 300, 500, 200, 400)

    # The event loop is nearly the same as we used in colorpalettes.py. If you
    # do not know, what happens here, take a look at colorpalettes.py for a
    # detailled description.
    running = True
    while running:
        events = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
            if event.type == SDL_MOUSEBUTTONDOWN:
                curindex += 1
                if curindex >= len(functions):
                    curindex = 0
                # In contrast to colorpalettes.py, our mapping table consists
                # of functions and their arguments. Thus, we get the currently
                # requested function and argument tuple and execute the
                # function with the arguments.
                func, args = functions[curindex]
                func(*args)
                break
        window.refresh()
    sdl2ext.quit()
    return 0
Exemplo n.º 36
0
def process_frame(joystick, tx, get_ship, args):
    for event in SDLE.get_events():
        if event.type == SDL.SDL_QUIT:
            exit(0)
    process_yaw(joystick, tx, get_ship)
    if args.enable_pitch:
        process_pitch(joystick, tx, get_ship)
    if args.enable_warp:
        process_warp(joystick, tx, get_ship)
    process_thrust(joystick, tx, get_ship)
    process_main_screen(joystick, tx, get_ship)
    process_shields(joystick, tx, get_ship)
    process_red_alert(joystick, tx, get_ship)
    process_reverse(joystick, tx, get_ship)
    process_dock_rq(joystick, tx, get_ship)
    time.sleep(1 / 15)
Exemplo n.º 37
0
def process_frame(joystick, tx, get_ship, args):
    for event in SDLE.get_events():
        if event.type == SDL.SDL_QUIT:
            exit(0)
    process_yaw(joystick, tx, get_ship)
    if args.enable_pitch:
        process_pitch(joystick, tx, get_ship)
    if args.enable_warp:
        process_warp(joystick, tx, get_ship)
    process_thrust(joystick, tx, get_ship)
    process_main_screen(joystick, tx, get_ship)
    process_shields(joystick, tx, get_ship)
    process_red_alert(joystick, tx, get_ship)
    process_reverse(joystick, tx, get_ship)
    process_dock_rq(joystick, tx, get_ship)
    time.sleep(1 / 15)
Exemplo n.º 38
0
 def fullfun(self):
     self.__clear()
     for _ in fun(self):
         i = sdl2.SDL_GetTicks()
         self.build_maze()
         self.__rendersprite()
         events = sdl.get_events()
         for e in events:
             if e.type == sdl2.SDL_QUIT:
                 return False
         self.__present()
         self.__clear()
         i = sdl2.SDL_GetTicks() - i
         if i < (1000 // 500):
             sdl2.SDL_Delay(1000 // 500 - i)
     return True
Exemplo n.º 39
0
    def __update_sdl(cls):
        events = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_WINDOWEVENT:
                for key, window in list(cls.windows.items()):
                    if SDL_GetWindowID(
                            window.sdl_window.window) == event.window.windowID:
                        if event.window.event == SDL_WINDOWEVENT_CLOSE:
                            SDL_HideWindow(window.sdl_window.window)
                            del cls.windows[key]
                            cls.closed_windows.add(key)

                        if event.window.event == SDL_WINDOWEVENT_RESIZED:
                            window._resize(event.window.data1,
                                           event.window.data2)
                            window.update(window.last_data)
                        break
Exemplo n.º 40
0
 def test_get_events_issue_6(self):
     try:
         sdl2ext.init()
     except sdl2ext.SDLError:
         raise unittest.SkipTest('Video subsystem not supported')
     SDL_FlushEvent(SDL_FIRSTEVENT, SDL_LASTEVENT)
     for x in range(12):
         event = SDL_Event()
         event.type = SDL_USEREVENT + x
         event.user = SDL_UserEvent(type=event.type,
                                    timestamp=0,
                                    windowID=0,
                                    code=0)
         SDL_PushEvent(event)
     results = sdl2ext.get_events()
     for idx, r in enumerate(results):
         self.assertEqual(idx, r.type - SDL_USEREVENT)
Exemplo n.º 41
0
 def test_get_events(self):
     try:
         sdl2ext.init()
     except sdl2ext.SDLError:
         raise unittest.SkipTest('Video subsystem not supported')
     SDL_FlushEvent(SDL_FIRSTEVENT, SDL_LASTEVENT)
     for x in range(10):
         event = SDL_Event()
         event.type = SDL_USEREVENT + 1
         event.user = SDL_UserEvent(type=event.type,
                                    timestamp=0,
                                    windowID=0,
                                    code=0)
         SDL_PushEvent(event)
     results = sdl2ext.get_events()
     self.assertEqual(len(results), 10)
     for ev in results:
         self.assertEqual(ev.type, (SDL_USEREVENT + 1))
Exemplo n.º 42
0
def main():
    global state
    newstate = np.copy(state)
    width = 600
    height = 600
    sdl2ext.init()
    window = sdl2ext.Window('GRIDLEARN', size=(width, height))
    window.show()
    surface = window.get_surface()
    running = True
    begin_tick = begin_time = time.monotonic()
    mousedown = False
    while running:
        now = time.monotonic()
        elapsed = now - begin_time
        events = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
            elif event.type == SDL_KEYDOWN:
                if event.key.keysym.sym == 27:
                    running = False
                    break
                elif event.key.keysym.sym == 113:
                    state[:] = 0
            elif event.type == SDL_MOUSEBUTTONDOWN:
                mousedown = True
            elif event.type == SDL_MOUSEBUTTONUP:
                mousedown = False
            elif mousedown and event.type == SDL_MOUSEMOTION:
                print(dir(event.button))
                x, y = event.button.x, event.button.y
                idx = int(x / width * W)
                idy = int(y / height * H)
                state[idy, idx] = 1
                break
        if now - begin_tick > 0.1:
            begin_tick = now
            newstate = update(state, newstate, weights, 0.1)
            newstate, state = state, newstate
            draw(surface, width, height)
            window.refresh()
    sdl2ext.quit()
Exemplo n.º 43
0
def make_score_board(window = None, yaku_list = ['rinshan', 'pinfu'], fusu = 20, hansu = 2 , tensu = 2000):

    if window == None:
        sdl2ext.init()
        window = sdl2ext.Window("The Pong Game", size=(800, 600))
        window.show()

    img = print_yaku_list(yaku_list)

    window_surface = window.get_surface()
    surface = pilSurface(img)
    sdl2ext.fill(window_surface, sdl2ext.Color(0, 0, 0 ))
    rect_tes1 = rect.SDL_Rect(0, 0, 320, 500)
    rect_tes2 = rect.SDL_Rect(25, 0, 800, 600)
    SDL_BlitSurface(surface,rect_tes1,window_surface,rect_tes2)
    SDL_UpdateWindowSurface(window.window)

    rect_tes1 = rect.SDL_Rect(0, 0, 800, 600)
    rect_tes2 = rect.SDL_Rect(25, 550, 800, 600)
    img = PIL.Image.new("RGBA", (500, 35))

    if hansu >= 0:
        text_hansu = str(hansu) + '飜 '
    if hansu >= 13:
        text_hansu = '数え役満 '
    if hansu >= 100:
        text_hansu = '役満 '
    text = str(fusu) + '符 ' + text_hansu + str(tensu) + '点'
    draw_text(img, text, 0, 0)
    surface = pilSurface(img)
    SDL_BlitSurface(surface,
            rect_tes1,
            window_surface,
            rect_tes2)
    SDL_UpdateWindowSurface(window.window)
    while True:

        events = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
            elif event.type == SDL_MOUSEBUTTONDOWN:
                return
Exemplo n.º 44
0
Arquivo: pong.py Projeto: 2M1R/Pong
def run():
    sdl2ext.init()
    window = sdl2ext.Window("Pong Game", size=(1280, 720))
    window.show()

    world = sdl2ext.World()

    collision = CollisionSystem(0, 0, 1280, 720)
    movement = MovementSystem(0, 0, 1280, 720)
    spriterenderer = SoftwareRenderer(window)

    world.add_system(movement)
    world.add_system(collision)
    world.add_system(spriterenderer)

    factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)
    sp_paddle1 = factory.from_color(WHITE, size=(20, 100))
    sp_paddle2 = factory.from_color(WHITE, size=(20, 100))
    sp_ball = factory.from_color(WHITE, size=(20, 20))

    player1 = Player(world, sp_paddle1, 0, 250)
    player2 = Player(world, sp_paddle2, 1255, 250)
    ball = Ball(world, sp_ball, 300, 290)
    collision.ball = ball
    ball.velocity.vx = -3

    running = True
    while running:
        events = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
            if event.type == SDL_KEYDOWN:
                if event.key.keysym.sym == SDLK_UP:
                    player1.velocity.vy = -3
                elif event.key.keysym.sym == SDLK_DOWN:
                    player1.velocity.vy = 3
            elif event.type == SDL_KEYUP:
                if event.key.keysym.sym in (SDLK_UP, SDLK_DOWN):
                    player1.velocity.vy = 0
        SDL_Delay(10)
        world.process()
    return 0
Exemplo n.º 45
0
	def run(self):
		sdl2ext.init()
		window = sdl2ext.Window("Robot Sandbox", size=(640, 480))
		window.show()
		
		spriteRender = SoftwareRenderer(window)
		self.world.add_system(spriteRender)
		
		running = True
		while running:
			events = sdl2ext.get_events()
			for event in events:
				#pdb.set_trace()
				if event.type == SDL_QUIT:
					runnig = False
					break
			self.world.process()
			window.refresh()
		return 0
Exemplo n.º 46
0
def draw(window, robot):
    events = sdl.get_events()
    for event in events:
        if event.type == sdl2.SDL_QUIT:
            running = False
            break

    surface = window.get_surface()
    sdl.fill(surface, sdl.Color(0, 0, 0))

    #Drawing the walls
    sdl.line(surface, sdl.Color(255, 255, 255),
             (-meters_to_pixels(0.4) + WINDOW_SIZE[0] // 2, 0,
              -meters_to_pixels(0.4) + WINDOW_SIZE[0] // 2, WINDOW_SIZE[1],
              meters_to_pixels(0.4) + WINDOW_SIZE[0] // 2, 0,
              meters_to_pixels(0.4) + WINDOW_SIZE[0] // 2, WINDOW_SIZE[1]))

    draw_robot(surface, robot)

    window.refresh()
Exemplo n.º 47
0
    def run(self):
        """Perform startup procedures and enter the mainloop.
        """
        # Only run if not already running.
        if not self.running:
            self.running = True

            # Execute the init function of the init script if present.
            if not self.path["init.py"]:
                self.log.msg("WARNING", "Driftwood", "init.py missing, nothing will happen")
            else:
                self.script.call("init.py", "init")

            # Escape key pauses the engine.
            self.input.register(self.keycode.SDLK_ESCAPE, self.__handle_pause)

            # This is the mainloop.
            while self.running:
                # Process SDL events.
                sdlevents = sdl2ext.get_events()
                for event in sdlevents:
                    if event.type == SDL_QUIT:
                        # Stop running.
                        self.running = False

                    elif event.type == SDL_KEYDOWN:
                        # Pass a keydown to the Input Manager.
                        self.input._key_down(event.key.keysym.sym)

                    elif event.type == SDL_KEYUP:
                        # Pass a keyup to the Input Manager.
                        self.input._key_up(event.key.keysym.sym)

                    elif event.type == SDL_WINDOWEVENT and event.window.event == SDL_WINDOWEVENT_EXPOSED:
                        self.window.refresh()

                # Process tick callbacks.
                self.tick.tick()

            print("Shutting down...")
            return 0
Exemplo n.º 48
0
def run_simulation(name, path, maze, continuous=False):
    '''run a simulation of sprite going through the maze 
    parameters:
    name :          name of the algorithm to be displayed on window
    path :          the path returned by the algorithm
    startstate :    the starting state of the maze
    data :          the maze matrix (containing 0s and 1s)
    continuos :     True if click is not necessary for next move else False'''
    startstate, data = maze.startstate, maze.data
    w, r = initiation(name, data)
    run = True
    way = iter(path)
    w.show()
    s = Simulation(r, *startstate, data)
    nextitem = True
    while True:
        events = sdl.get_events()
        for e in events:
            if e.type == sdl2.SDL_QUIT:
                run = False
                break
            elif e.type == sdl2.SDL_MOUSEBUTTONDOWN or e.type == sdl2.SDL_KEYDOWN:
                nextitem = True
        if not run:
            break
        if nextitem:
            try:
                direction = next(way)
            except StopIteration:
                run = False
                break
            if direction == "end":
                nextitem = False
            elif direction == "start":
                pass
            else:
                run = ACTION[direction](s)
        if not continuous:
            nextitem = False
    w.hide()
Exemplo n.º 49
0
Arquivo: tri.py Projeto: revmischa/tri
def run():
    sdl2ext.init()

    # init window
    window = sdl2ext.Window("tri", size=(screenwidth, screenheight), flags=SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN_DESKTOP)
    window.show()

    # init renderer and generator
    worldrenderer = WorldRenderer(window)
    trigen = TriGenerator()

    # init world
    world = TriWorld()
    world.add_system(worldrenderer)
    world.add_system(trigen)

    # hide cursor
    SDL_ShowCursor(SDL_DISABLE)

    running = True
    while running:
        start = SDL_GetTicks()
        # main loop party time
        events = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
        world.process()

        # try and do 60fps
        elapsed = (SDL_GetTicks() - start) / 1000.0
        delay = 16.6 - elapsed
        if delay > 0:
            SDL_Delay(int(delay))

    SDL_ShowCursor(SDL_ENABLE)
    return 0
def enterPlayerTile():
	# Draws the text and handles the mouse click events for letting
	# the player choose which color they want to be.  Returns
	# [WHITE_TILE, BLACK_TILE] if the player chooses to be White,
	# [BLACK_TILE, WHITE_TILE] if Black.

	# Create the text.
	text_spr = SPRITE_FACTORY.from_text('Do you want to be white or black?', color=TEXTCOLOR, bg_color=TEXTBGCOLOR1)
	center_sprite(text_spr, WINDOWWIDTH//2, WINDOWHEIGHT//2)

	white_spr = SPRITE_FACTORY.from_text('White', color=TEXTCOLOR, bg_color=TEXTBGCOLOR1)
	center_sprite(white_spr, WINDOWWIDTH//2 - 60, WINDOWHEIGHT//2 + 40)

	black_spr = SPRITE_FACTORY.from_text('Black', color=TEXTCOLOR, bg_color=TEXTBGCOLOR1)
	center_sprite(black_spr, WINDOWWIDTH//2 + 60, WINDOWHEIGHT//2 + 40)

	while True:
		# Keep looping until the player has clicked on a color.
		for event in ext.get_events(): # event handling loop
			if event.type == SDL_QUIT:
				shutdown()
			elif event.type == SDL_KEYUP:
				sc = event.key.keysym.scancode
				if sc == SDL_SCANCODE_ESCAPE:
					shutdown()
			elif event.type == SDL_MOUSEBUTTONUP:
				pt = SDL_Point(event.button.x, event.button.y)
				print(pt)
				if rect.SDL_PointInRect(pt, get_spr_rect(white_spr)):
					return [WHITE_TILE, BLACK_TILE]
				elif rect.SDL_PointInRect(pt, get_spr_rect(black_spr)):
					return [BLACK_TILE, WHITE_TILE]

		# Draw the screen.
		SPRITE_RENDERER.render([text_spr, white_spr, black_spr])
		REN.present()
		SDL_Delay(1000//FPS)
Exemplo n.º 51
0
def main():
    sdl2ext.init()
    TTF_Init()

    window = sdl2ext.Window("Text display", size=(800, 600))
    window.show()

    renderer = sdl2ext.RenderContext(window)
    factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer)
    world = sdl2ext.World()

    fps = FPSCounter(world, renderer=renderer)

    spriteRenderer = factory.create_sprite_renderer()
    fpsController = FPSController()

    world.add_system(fpsController)
    world.add_system(spriteRenderer)

    running = True

    while running:
        for event in sdl2ext.get_events():
            if event.type == sdlevents.SDL_QUIT:
                running = False
                break
            elif event.type == sdlevents.SDL_USEREVENT:
                entity = cast(event.user.data1,
                              POINTER(py_object)).contents.value
                entity.textsprite.text = "FPS: " + str(entity.fps.counter)
                entity.fps.counter = 0
        renderer.clear()
        world.process()

    TTF_Quit()
    sdl2ext.quit()
    return 0
Exemplo n.º 52
0
def main():
	sdl2ext.init()
	TTF_Init()
	
	window = sdl2ext.Window("Text display", size=(800, 600))
	window.show()
	
	renderer = sdl2ext.RenderContext(window)
	factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer)
	world = sdl2ext.World()

	fps = FPSCounter(world, renderer=renderer)
	
	spriteRenderer = factory.create_sprite_renderer()
	fpsController = FPSController()
	
	world.add_system(fpsController)
	world.add_system(spriteRenderer)
	
	running = True
	
	while running:
		for event in sdl2ext.get_events():
			if event.type == sdlevents.SDL_QUIT:
				running = False
				break
			elif event.type == sdlevents.SDL_USEREVENT:
				entity = cast(event.user.data1, POINTER(py_object)).contents.value
				entity.textsprite.text = "FPS: " + str(entity.fps.counter)
				entity.fps.counter = 0
		renderer.clear()
		world.process()
		
	TTF_Quit()
	sdl2ext.quit()
	return 0
def runGame():
	# Plays a single game of reversi each time this function is called.

	# Reset the board and game.
	mainBoard = getNewBoard()
	resetBoard(mainBoard)
	showHints = False
	turn = random.choice(['computer', 'player'])

	# Draw the starting board and ask the player what color they want.
	drawBoard(mainBoard)
	playerTile, computerTile = enterPlayerTile()

	# Make the sprite and Rect objects for the "New Game" and "Hints" buttons
	newGame = SPRITE_FACTORY.from_text("New Game", color=TEXTCOLOR, bg_color=TEXTBGCOLOR2)
	newGame.position = (WINDOWWIDTH - 8 - newGame.size[0], 10)
	newGameRect = get_spr_rect(newGame)
	
	hints = SPRITE_FACTORY.from_text("Hints", color= TEXTCOLOR, bg_color=TEXTBGCOLOR2)
	hints.position = (WINDOWWIDTH - 8 - hints.size[0], 40)
	hintsRect = get_spr_rect(hints)

	while True: # main game loop
		# Keep looping for player and computer's turns.
		if turn == 'player':
			# Player's turn:
			if getValidMoves(mainBoard, playerTile) == []:
				# If it's the player's turn but they
				# can't move, then end the game.
				break
			movexy = None
			while movexy == None:
				# Keep looping until the player clicks on a valid space.

				# Determine which board data structure to use for display.
				if showHints:
					boardToDraw = getBoardWithValidMoves(mainBoard, playerTile)
				else:
					boardToDraw = mainBoard

				for event in ext.get_events():
					if event.type == SDL_QUIT:
						shutdown()
					elif event.type == SDL_KEYUP:
						sc = event.key.keysym.scancode
						if sc == SDL_SCANCODE_ESCAPE:
							shutdown()
					elif event.type == SDL_MOUSEBUTTONUP:
						# Handle mouse click events
						mousex, mousey = event.button.x, event.button.y
						if rect.SDL_PointInRect(SDL_Point(mousex, mousey), newGameRect):
							# Start a new game
							return True
						elif rect.SDL_PointInRect(SDL_Point(mousex, mousey), hintsRect):
							# Toggle hints mode
							showHints = not showHints
						# movexy is set to a two-item tuple XY coordinate, or None value
						movexy = getSpaceClicked(mousex, mousey)
						if movexy != None and not isValidMove(mainBoard, playerTile, movexy[0], movexy[1]):
							movexy = None

				# Draw the game board.
				drawBoard(boardToDraw)
				drawInfo(boardToDraw, playerTile, computerTile, turn)

				# Draw the "New Game" and "Hints" buttons.
				SPRITE_RENDERER.render([newGame, hints])

				SDL_Delay(1000//FPS) #TODO
				REN.present()

			# Make the move and end the turn.
			makeMove(mainBoard, playerTile, movexy[0], movexy[1], True)
			if getValidMoves(mainBoard, computerTile) != []:
				# Only set for the computer's turn if it can make a move.
				turn = 'computer'

		else:
			# Computer's turn:
			if getValidMoves(mainBoard, computerTile) == []:
				# If it was set to be the computer's turn but
				# they can't move, then end the game.
				break

			# Draw the board.
			drawBoard(mainBoard)
			drawInfo(mainBoard, playerTile, computerTile, turn)

			# Draw the "New Game" and "Hints" buttons.
			SPRITE_RENDERER.render([newGame, hints])

			# Make it look like the computer is thinking by pausing a bit.
			pauseUntil = SDL_GetTicks() + random.randint(5, 15) * 100
			while SDL_GetTicks() < pauseUntil:
				REN.present()

			# Make the move and end the turn.
			x, y = getComputerMove(mainBoard, computerTile)
			makeMove(mainBoard, computerTile, x, y, True)
			if getValidMoves(mainBoard, playerTile) != []:
				# Only set for the player's turn if they can make a move.
				turn = 'player'

	# Display the final score.
	drawBoard(mainBoard)
	scores = getScoreOfBoard(mainBoard)

	# Determine the text of the message to display.
	if scores[playerTile] > scores[computerTile]:
		text = 'You beat the computer by %s points! Congratulations!' % \
			   (scores[playerTile] - scores[computerTile])
	elif scores[playerTile] < scores[computerTile]:
		text = 'You lost. The computer beat you by %s points.' % \
			   (scores[computerTile] - scores[playerTile])
	else:
		text = 'The game was a tie!'

	result_spr = SPRITE_FACTORY.from_text(text, color=TEXTCOLOR, bg_color=TEXTBGCOLOR1)
	center_sprite(result_spr, WINDOWWIDTH//2, WINDOWHEIGHT//2)

	# Display the "Play again?" text with Yes and No buttons.
	play_again_spr = SPRITE_FACTORY.from_text('Play again?', color=TEXTCOLOR, bg_color=TEXTBGCOLOR1)
	center_sprite(play_again_spr, WINDOWWIDTH//2, WINDOWHEIGHT//2 + 50)

	# Make "Yes" button.
	yes_spr = SPRITE_FACTORY.from_text('Yes', color=TEXTCOLOR, bg_color=TEXTBGCOLOR1)
	center_sprite(yespr, WINDOWWIDTH//2 - 60, WINDOWHEIGHT//2 + 90)
	yes_rect = get_spr_rect(yes_spr)

	# Make "No" button.
	no_spr = SPRITE_FACTORY.from_text('No', color=TEXTCOLOR, bg_color=TEXTBGCOLOR1)
	center_sprite(no_spr, WINDOWWIDTH//2 + 60, WINDOWHEIGHT//2 + 90)
	no_rect = get_spr_rect(no_spr)

	while True:
		# Process events until the user clicks on Yes or No.
		for event in ext.get_events(): # event handling loop
			if event.type == SDL_QUIT:
				shutdown()
			elif event.type == SDL_KEYUP:
				sc = event.key.keysym.scancode
				if sc == SDL_SCANCODE_ESCAPE:
					shutdown()
			elif event.type == MOUSEBUTTONUP:
				pt = SDL_Point(event.button.x, event.button.y)
				if rect.SDL_PointInRect(pt, yes_rect):
					return True
				elif rect.SDL_PointInRect(pt, no_rect):
					return False
		SPRITE_RENDERER.render([result_spr, play_again_spr, yes_spr, nospr])
		REN.present()
		SDL_Delay(1000//FPS)
Exemplo n.º 54
0
 def queueSDLEvents(self):
     events = sdl2ext.get_events()
     newEvents = dict()
     for event in events:
         self.evtMngr.queueEvent(E_SDL_EVENT, event.type, event)
def runGame():
	#setup variables for start of game
	board = getBlankBoard()
	lastMoveDownTime = SDL_GetTicks()
	lastMoveSidewaysTime = lastMoveDownTime
	lastFallTime = lastMoveDownTime
	score = 0
	level, fallFreq = calculateLevelAndFallFreq(score)

	fallingPiece = None
	nextPiece = getNewPiece()

	keylen = ctypes.c_int()
	kybd_st = SDL_GetKeyboardState(ctypes.byref(keylen))

	while True:
		starttime = SDL_GetTicks()
		if fallingPiece == None:
			fallingPiece = nextPiece
			nextPiece = getNewPiece()
			lastFallTime = SDL_GetTicks()

			if not isValidPos(board, fallingPiece):
				return

		for event in ext.get_events():
			if event.type == SDL_QUIT:
				shutdown()
			elif event.type == SDL_KEYUP:
				sc = event.key.keysym.scancode
				if sc == SDL_SCANCODE_ESCAPE:
					shutdown()
				elif sc == SDL_SCANCODE_P:
					#Pausing the game
					REN.clear(BGCOLOR)
					sdlmixer.Mix_PauseMusic()
					showTextScreen("Paused") # pause till keypress
					sdlmixer.Mix_ResumeMusic()
					tmp = SDL_GetTicks()
					#reseting these is necessary though lastFallTime might help them a bit
					starttime = tmp
					lastMoveDownTime = tmp
					lastMoveSidewaysTime = tmp
					lastFallTime = tmp

				#rotate
				elif sc == SDL_SCANCODE_UP or sc == SDL_SCANCODE_W:
					fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']])
					if not isValidPos(board, fallingPiece):
						fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(PIECES[fallingPiece['shape']])
				#rotate other way
				elif sc == SDL_SCANCODE_Q:
					fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(PIECES[fallingPiece['shape']])
					if not isValidPos(board, fallingPiece):
						fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']])

				# move piece all the way down
				elif sc == SDL_SCANCODE_SPACE:
					for i in range(1, BOARDHEIGHT):
						if not isValidPos(board, fallingPiece, adj_y=i):
							break
					fallingPiece['y'] += i-1

			
		if is_moving_left(kybd_st) or is_moving_right(kybd_st) and SDL_GetTicks() - lastMoveSidewaysTime > MOVESIDEWAYSFREQ:
			if is_moving_left(kybd_st) and isValidPos(board, fallingPiece, adj_x=-1):
				fallingPiece['x'] -= 1
			elif is_moving_right(kybd_st) and isValidPos(board, fallingPiece, adj_x=1):
				fallingPiece['x'] += 1
			lastMoveSidewaysTime = SDL_GetTicks()

		if is_moving_down(kybd_st) and SDL_GetTicks() - lastMoveDownTime > MOVEDOWNFREQ and isValidPos(board, fallingPiece, adj_y=1):
			fallingPiece['y'] += 1
			lastMoveDownTime = SDL_GetTicks()


		# let piece fall if it's time to fall
		if SDL_GetTicks() - lastFallTime > fallFreq:
			# see if piece has landed
			if not isValidPos(board, fallingPiece, adj_y=1):
				print(fallingPiece)
				addToBoard(board, fallingPiece)
				score += removeCompleteLines(board)
				level, fallFreq = calculateLevelAndFallFreq(score)
				fallingPiece = None
			else:
				fallingPiece['y'] += 1
				lastFallTime = SDL_GetTicks() #replace all these calls with variable set at top of loop?

		#draw everything
		REN.clear(BGCOLOR)
		#REN.fill((0,0,WINDOWWIDTH,WINDOWHEIGHT), BGCOLOR)
		#REN.fill((XMARGIN - 3, 0, (BOARDWIDTH * BOXSIZE) + 8, WINDOWHEIGHT), BGCOLOR)

		drawBoard(board)
		if fallingPiece:
			drawPiece(fallingPiece)
		drawStatus(score, level, nextPiece)
		REN.present()

		SDL_Delay(1000//FPS - ((SDL_GetTicks()-starttime)))
Exemplo n.º 56
0
with open("figure.json", "r") as ff:
    figure = json.loads(ff.read())

figure["points"] = np.array(figure["points"])
print(figure["points"])
figure["points"] -= np.mean(figure["points"], axis=0)
print(figure["points"])
figure["points"] = np.hstack(
    (figure["points"], np.ones((figure["points"].shape[0], 1))))
print(figure["points"])
figure["AB"] = np.array(figure["AB"])

sdl2e.init()
window = sdl2e.Window("...", size=(WIDTH, HEIGHT))
window.show()
draw(window, transform(world, figure["points"]), figure["polygons"])

running = True
while running:
    events = sdl2e.get_events()
    for event in events:
        if event.type == sdl2.SDL_QUIT:
            running = False
            break
        if event.type == sdl2.SDL_KEYDOWN:
            if handle_key(window, event.key.keysym.sym):
                draw(window, transform(world, figure["points"]),
                     figure["polygons"])

sdl2e.quit()
Exemplo n.º 57
0
def runGame():
    #setup variables for start of game
    board = getBlankBoard()
    lastMoveDownTime = SDL_GetTicks()
    lastMoveSidewaysTime = lastMoveDownTime
    lastFallTime = lastMoveDownTime
    score = 0
    level, fallFreq = calculateLevelAndFallFreq(score)

    fallingPiece = None
    nextPiece = getNewPiece()

    keylen = ctypes.c_int()
    kybd_st = SDL_GetKeyboardState(ctypes.byref(keylen))

    while True:
        starttime = SDL_GetTicks()
        if fallingPiece == None:
            fallingPiece = nextPiece
            nextPiece = getNewPiece()
            lastFallTime = SDL_GetTicks()

            if not isValidPos(board, fallingPiece):
                return

        for event in ext.get_events():
            if event.type == SDL_QUIT:
                shutdown()
            elif event.type == SDL_KEYUP:
                sc = event.key.keysym.scancode
                if sc == SDL_SCANCODE_ESCAPE:
                    shutdown()
                elif sc == SDL_SCANCODE_P:
                    #Pausing the game
                    REN.clear(BGCOLOR)
                    sdlmixer.Mix_PauseMusic()
                    showTextScreen("Paused")  # pause till keypress
                    sdlmixer.Mix_ResumeMusic()
                    tmp = SDL_GetTicks()
                    #reseting these is necessary though lastFallTime might help them a bit
                    starttime = tmp
                    lastMoveDownTime = tmp
                    lastMoveSidewaysTime = tmp
                    lastFallTime = tmp

                #rotate
                elif sc == SDL_SCANCODE_UP or sc == SDL_SCANCODE_W:
                    fallingPiece['rotation'] = (
                        fallingPiece['rotation'] + 1) % len(
                            PIECES[fallingPiece['shape']])
                    if not isValidPos(board, fallingPiece):
                        fallingPiece['rotation'] = (
                            fallingPiece['rotation'] - 1) % len(
                                PIECES[fallingPiece['shape']])
                #rotate other way
                elif sc == SDL_SCANCODE_Q:
                    fallingPiece['rotation'] = (
                        fallingPiece['rotation'] - 1) % len(
                            PIECES[fallingPiece['shape']])
                    if not isValidPos(board, fallingPiece):
                        fallingPiece['rotation'] = (
                            fallingPiece['rotation'] + 1) % len(
                                PIECES[fallingPiece['shape']])

                # move piece all the way down
                elif sc == SDL_SCANCODE_SPACE:
                    for i in range(1, BOARDHEIGHT):
                        if not isValidPos(board, fallingPiece, adj_y=i):
                            break
                    fallingPiece['y'] += i - 1

        if is_moving_left(kybd_st) or is_moving_right(
                kybd_st
        ) and SDL_GetTicks() - lastMoveSidewaysTime > MOVESIDEWAYSFREQ:
            if is_moving_left(kybd_st) and isValidPos(
                    board, fallingPiece, adj_x=-1):
                fallingPiece['x'] -= 1
            elif is_moving_right(kybd_st) and isValidPos(
                    board, fallingPiece, adj_x=1):
                fallingPiece['x'] += 1
            lastMoveSidewaysTime = SDL_GetTicks()

        if is_moving_down(kybd_st) and SDL_GetTicks(
        ) - lastMoveDownTime > MOVEDOWNFREQ and isValidPos(
                board, fallingPiece, adj_y=1):
            fallingPiece['y'] += 1
            lastMoveDownTime = SDL_GetTicks()

        # let piece fall if it's time to fall
        if SDL_GetTicks() - lastFallTime > fallFreq:
            # see if piece has landed
            if not isValidPos(board, fallingPiece, adj_y=1):
                print(fallingPiece)
                addToBoard(board, fallingPiece)
                score += removeCompleteLines(board)
                level, fallFreq = calculateLevelAndFallFreq(score)
                fallingPiece = None
            else:
                fallingPiece['y'] += 1
                lastFallTime = SDL_GetTicks(
                )  #replace all these calls with variable set at top of loop?

        #draw everything
        REN.clear(BGCOLOR)
        #REN.fill((0,0,WINDOWWIDTH,WINDOWHEIGHT), BGCOLOR)
        #REN.fill((XMARGIN - 3, 0, (BOARDWIDTH * BOXSIZE) + 8, WINDOWHEIGHT), BGCOLOR)

        drawBoard(board)
        if fallingPiece:
            drawPiece(fallingPiece)
        drawStatus(score, level, nextPiece)
        REN.present()

        SDL_Delay(1000 // FPS - ((SDL_GetTicks() - starttime)))
Exemplo n.º 58
0
    def game_board(self, board, player_one, player_two, player_types, ai_difficulty=None):

        from player_data import PlayerData

        pd=PlayerData()

        if 'AI' in player_types:
            from ai import AI
            ai=AI()
            if 'AI: Easy' in [player_one,player_two]:
                ai.difficulty=0
            elif 'AI: Medium' in [player_one,player_two]:
                ai.difficulty=1
            elif 'AI: Hard' in [player_one,player_two]:
                ai.difficulty=2

        sdl2ext.init()

        window = sdl2ext.Window("c4o5x5", size=(320, 420))

        window.show()

        factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)

        spriterenderer = factory.create_sprite_render_system(window)

        moves = 0
        running = True
        updated_p1 = False
        updated_p2 = False

        while running:
            if moves % 2 == 0:
                this_player = player_one
                that_player = player_two
                if player_types[0]=='AI':
                    mode='AI'
                    player_graphic="ai.bmp"
                else:
                    mode='Human'
                    player_graphic = "player_one.bmp"
            if moves % 2 == 1:
                this_player = player_two
                that_player = player_one
                if player_types[1]=='AI':
                    mode='AI'
                    player_graphic="ai.bmp"
                else:
                    mode='Human'
                    player_graphic = "player_two.bmp"
            for x in range(5):
                for y in range(5):
                    if board.marks[x][y] is None:
                        spriterenderer.render(factory.from_image(self.RESOURCES.get_path("tile.bmp")),x*64,y*64)
                    if board.marks[x][y] == player_one:
                        spriterenderer.render(factory.from_image(self.RESOURCES.get_path("tile_o.bmp")),x*64,y*64)
                    if board.marks[x][y] == player_two:
                        spriterenderer.render(factory.from_image(self.RESOURCES.get_path("tile_x.bmp")),x*64,y*64)
            if board.check_winning_positions() != (False,False):
                winning_player = board.check_winning_positions()[0]
                if winning_player == player_one:
                    winning_graphic = 'player_one_wins.bmp'
                    if player_one != 'Guest' and not updated_p1:
                        player=pd.load_player(player_one)
                        pd.update_player(player_one,player.wins+1,player.losses)
                        updated_p1 = True
                    if player_two != 'Guest' and not updated_p2:
                        player=pd.load_player(player_two)
                        pd.update_player(player_two,player.wins,player.losses+1)
                        updated_p2=True
                elif winning_player == player_two:
                    winning_graphic = 'player_two_wins.bmp'
                    if player_one != 'Guest' and not updated_p2:
                        player=pd.load_player(player_two)
                        pd.update_player(player_two,player.wins+1,player.losses)
                        updated_p2=True
                    if player_two != 'Guest' and not updated_p1:
                        player=pd.load_player(player_one)
                        pd.update_player(player_one,player.wins,player.losses+1)
                        updated_p1=True
                spriterenderer.render(factory.from_image(self.RESOURCES.get_path(winning_graphic)),0,(x+1)*64)
                events = sdl2ext.get_events()
                for event in events:
                    if event.type == SDL_MOUSEBUTTONDOWN:
                        running = False
                        SDL_Delay(1000)
                        break
            elif moves == 25:
                winning_graphic = "tie_game.bmp"
                spriterenderer.render(factory.from_image(self.RESOURCES.get_path(winning_graphic)),0,(x+1)*64)
                events = sdl2ext.get_events()
                for event in events:
                    if event.type == SDL_MOUSEBUTTONDOWN:
                        running = False
                        break
            elif mode == 'Human':
                spriterenderer.render(factory.from_image(self.RESOURCES.get_path(player_graphic)),0,(x+1)*64)
                events = sdl2ext.get_events()
                for event in events:
                    if event.type == SDL_QUIT:
                        running = False
                        break
                    elif event.type == SDL_MOUSEBUTTONDOWN:
                        x_pos = int(event.button.x/64)
                        y_pos = int(event.button.y/64)
                        if x_pos <= 4 and y_pos <= 4 and board.marks[x_pos][y_pos] is None:
                            board.marks[x_pos][y_pos]=this_player
                            moves = moves + 1
            elif mode=='AI':
                move = ai.make_move(board,this_player,that_player)
                moves = moves + 1
                board.update_position(move[0],move[1],this_player)
                for x in range(5):
                    for y in range(5):
                        if board.marks[x][y] is None:
                            spriterenderer.render(factory.from_image(self.RESOURCES.get_path("tile.bmp")),x*64,y*64)
                        if board.marks[x][y] == player_one:
                            spriterenderer.render(factory.from_image(self.RESOURCES.get_path("tile_o.bmp")),x*64,y*64)
                        if board.marks[x][y] == player_two:
                            spriterenderer.render(factory.from_image(self.RESOURCES.get_path("tile_x.bmp")),x*64,y*64)
                spriterenderer.render(factory.from_image(self.RESOURCES.get_path(player_graphic)),0,(x+1)*64)
                SDL_Delay(500)
                events = sdl2ext.get_events()
                for event in events:
                    if event.type == SDL_QUIT:
                        running = False
                        break
                    else:
                        pass
            else:
                raise Exception
            SDL_Delay(10)

        sdl2ext.quit()
Exemplo n.º 59
0
def run():
    # Initialize PySDL2 stuff
    ext.init()
    window = ext.Window(title="Esper PySDL2 example", size=RESOLUTION)
    renderer = ext.Renderer(target=window)
    window.show()

    # Initialize Esper world, and create a "player" Entity with a few Components.
    world = esper.World()
    player = world.create_entity()
    world.add_component(player, Velocity(x=0, y=0))
    world.add_component(player, Renderable(texture=texture_from_image(renderer, "redsquare.png"),
                                           width=64, height=64, posx=100, posy=100))
    # Another motionless Entity:
    enemy = world.create_entity()
    world.add_component(enemy, Renderable(texture=texture_from_image(renderer, "bluesquare.png"),
                                          width=64, height=64, posx=400, posy=250))

    # Create some Processor instances, and asign them to be processed.
    render_processor = RenderProcessor(renderer=renderer)
    movement_processor = MovementProcessor(minx=0, maxx=RESOLUTION[0], miny=0, maxy=RESOLUTION[1])
    world.add_processor(render_processor)
    world.add_processor(movement_processor)

    # A simple main loop
    running = True
    while running:
        start_time = SDL_GetTicks()

        for event in ext.get_events():
            if event.type == SDL_QUIT:
                running = False
                break
            if event.type == SDL_KEYDOWN:
                if event.key.keysym.sym == SDLK_UP:
                    # Here is a way to directly access a specific Entity's Velocity
                    # Component's attribute (y) without making a temporary variable.
                    world.component_for_entity(player, Velocity).y = -3
                elif event.key.keysym.sym == SDLK_DOWN:
                    # For clarity, here is an alternate way in which a temporary variable
                    # is created and modified. The previous way above is recommended instead.
                    player_velocity_component = world.component_for_entity(player, Velocity)
                    player_velocity_component.y = 3
                elif event.key.keysym.sym == SDLK_LEFT:
                    world.component_for_entity(player, Velocity).x = -3
                elif event.key.keysym.sym == SDLK_RIGHT:
                    world.component_for_entity(player, Velocity).x = 3
                elif event.key.keysym.sym == SDLK_ESCAPE:
                    running = False
                    break
            elif event.type == SDL_KEYUP:
                if event.key.keysym.sym in (SDLK_UP, SDLK_DOWN):
                    world.component_for_entity(player, Velocity).y = 0
                if event.key.keysym.sym in (SDLK_LEFT, SDLK_RIGHT):
                    world.component_for_entity(player, Velocity).x = 0

        # A single call to world.process() will update all Processors:
        world.process()

        # A crude FPS limiter for about 60fps
        current_time = SDL_GetTicks()
        sleep_time = int(start_time + 16.667 - current_time)
        if sleep_time > 0:
            SDL_Delay(sleep_time)
Exemplo n.º 60
0
    def run(self):

        game_input = Input()

        speed_x, speed_y = 2, 1
        player_pos = [-100, -100]

        # motion_type = self.player_motion_type
        # facing = self.player_facing

        self.running = True
        last_update_time = SDL_GetTicks()  # units.MS

        while self.running:
            start_time = SDL_GetTicks()  # units.MS

            game_input.begin_new_frame()
            game_events = get_events()

            for event in game_events:
                if event.type == SDL_KEYDOWN:
                    game_input.key_down_event(event)

                elif event.type == SDL_KEYUP:
                    game_input.key_up_event(event)

                elif event.type == SDL_QUIT:
                    self.running = False
                    break

            if not self.running:
                self.clear()
                break

            # Exit
            if game_input.was_key_pressed(SDLK_ESCAPE):
                self.clear()
                self.running = False
                break

            # Player movement
            if game_input.is_key_held(SDLK_RIGHT) and game_input.is_key_held(
                    SDLK_UP):
                player_pos[0] -= speed_x
                player_pos[1] += speed_y
                self.player.velocity.vx = speed_x
                self.player.velocity.vy = -speed_y
                self.player.facing.set("right_up")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_RIGHT) and game_input.is_key_held(
                    SDLK_DOWN):
                player_pos[0] -= speed_x
                player_pos[1] -= speed_y
                self.player.velocity.vx = speed_x
                self.player.velocity.vy = speed_y
                self.player.facing.set("right_down")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_LEFT) and game_input.is_key_held(
                    SDLK_UP):
                player_pos[0] += speed_x
                player_pos[1] += speed_y
                self.player.velocity.vx = -speed_x
                self.player.velocity.vy = -speed_y
                self.player.facing.set("left_up")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_LEFT) and game_input.is_key_held(
                    SDLK_DOWN):
                player_pos[0] += speed_x
                player_pos[1] -= speed_y
                self.player.velocity.vx = -speed_x
                self.player.velocity.vy = speed_y
                self.player.facing.set("left_down")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_LEFT):
                player_pos[0] += speed_x
                self.player.velocity.vx = -speed_x
                self.player.facing.set("left")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_RIGHT):
                player_pos[0] -= speed_x
                self.player.velocity.vx = speed_x
                self.player.facing.set("right")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_UP):
                player_pos[1] += speed_y
                self.player.velocity.vy = -speed_y
                self.player.facing.set("up")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_DOWN):
                player_pos[1] -= speed_y
                self.player.velocity.vy = speed_y
                self.player.facing.set("down")
                self.player.motiontype.set("walking")

            # elif game_input.was_key_pressed(SDLK_i):
            #    self.player.toggle_inventory()

            # Player Attack
            elif game_input.is_key_held(SDLK_SPACE):
                pass
                # motion_type = MotionType.CASTING

            # Nothing
            else:
                self.player.velocity.vx = 0
                self.player.velocity.vy = 0
                self.player.motiontype.set("standing")

            current_time = SDL_GetTicks()  # units.MS
            elapsed_time = current_time - last_update_time  # units.MS

            last_update_time = current_time

            self.world.process()

            # This loop lasts 1/60th of a second, or 1000/60th ms
            ms_per_frame = 1000 // FPS  # units.MS
            elapsed_time = SDL_GetTicks() - start_time  # units.MS
            if elapsed_time < ms_per_frame:
                SDL_Delay(ms_per_frame - elapsed_time)