Ejemplo n.º 1
1
def my_slideshow(new_img, img, screen, file, num_imgs, rect):
    if not gl.TOGGLE_FULLSCREEN_SET:
        screen = set_mode(screen.get_size())
    set_caption("Slideshow Options - imgv")
    speed = get_speed(screen, new_img, rect, gl.files[file], file, num_imgs)
    if not speed == -1: # didn't hit Esc from get_speed:
        gl.SLIDE_SHOW_RUNNING = 1
        disable_screensaver()
        dont_call = 0
        pygame.event.set_blocked(MOUSEMOTION)
        while 1:
            event = pygame.event.poll()
            pygame.time.wait(1)
            check_quit(event)
            if event.type == KEYDOWN and event.key not in (K_LALT, K_RALT, K_LCTRL, K_RCTRL, K_p, K_PAUSE, K_TAB, K_SPACE, K_BACKSPACE):
                stopped_msg(screen)
                my_update_screen(new_img, screen, rect, file, len(gl.files))
                file = file - 1
                break
            if hit_key(event, K_p) or hit_key(event, K_PAUSE):
                pause(screen)
                my_update_screen(new_img, screen, rect, file, len(gl.files))
            if dont_call == 1:
                break
            if not gl.WRAP_SLIDESHOW:
                if file < num_imgs:
                    (new_img, file, rect, dont_call) = show_slideshow_img(screen, new_img, file, num_imgs, speed)
            if gl.WRAP_SLIDESHOW:
                if file >= num_imgs:
                    file = 0
                (new_img, file, rect, dont_call) = show_slideshow_img(screen, new_img, file, num_imgs, speed)
            pygame.time.delay(5) # don't hog CPU
    if not gl.TOGGLE_FULLSCREEN_SET:
        screen = set_mode(screen.get_size(), RESIZABLE)
    return (new_img, new_img, new_img, file, rect)
Ejemplo n.º 2
1
def admin_menu():
    from pygame.display import set_mode, list_modes, set_caption
    from pygame import init, quit

    init()
    screen = set_mode(list_modes()[0])
    set_caption("Hero Misadventures")
    menu = Menu(("Debug", "Release"), screen, text_color=color("White"), surface=color("Black"),
                selection_color=color("Slate Gray"))
    while True:
        choose = menu.update()
        if choose == -1:
            continue
        else:
            if choose == 0:
                from cProfile import runctx
                from pstats import Stats

                runctx("from bin.Interaction import debug_menu; debug_menu(screen)", {"screen": screen}, {}, "test/profiling.prof")
                file = open("test/profiling.txt", "w")
                info = Stats("test/profiling.prof", stream=file)
                info.strip_dirs().sort_stats("cumulative").print_stats()
            elif choose == 1:
                quit()
                start_menu()
            return
Ejemplo n.º 3
0
    def handle_input(self, events):
        """
        Handles incoming input events
        :param events: input events from the main app
        :return:
        """
        for event in events:
            if event.type == QUIT:
                sys.exit(0)

            elif event.type == KEYUP:
                if event.key == K_UP:
                    if self.menu_option <= 0:
                        self.menu_option = len(self.menu_options) - 1
                    else:
                        self.menu_option -= 1
                elif event.key == K_DOWN:
                    if self.menu_option >= len(self.menu_options) - 1:
                        self.menu_option = 0
                    else:
                        self.menu_option += 1
                elif event.key == K_RETURN:
                    if self.menu_option == 0:
                        self.context["gamestate"] = self.prev_state
                    elif self.menu_option == 1:
                        self.prev_state.restart_level()
                        self.context["gamestate"] = self.prev_state
                    elif self.menu_option == 2:
                        set_mode((LEVEL_WIDTH, LEVEL_HEIGHT))
                        self.context["gamestate"] = self.prev_state.prev_state

            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    self.context["gamestate"] = self.prev_state
Ejemplo n.º 4
0
Archivo: thumb.py Proyecto: rkulla/imgv
def command_thumbs(screen, new_img, file):
    normal_cursor()
    gl.THUMBING = 1

    screen_width = screen.get_width()
    if gl.THUMB_VAL.upper() == "AUTO" or gl.USING_THUMB_DEFAULT:
        gl.USING_THUMB_DEFAULT = 1
        if screen_width == 640:
            gl.THUMB_VAL = "85x90"
        elif screen_width == 800:
            gl.THUMB_VAL = "108x114"
        elif screen_width == 1024:
            gl.THUMB_VAL = "108x104"
        else:
            gl.THUMB_VAL = "100x100"

    if not gl.TOGGLE_FULLSCREEN_SET:
        screen = set_mode(screen.get_size())  # take away resize priviledges
    paint_screen(gl.IMGV_COLOR)
    set_caption("imgv")
    (new_img, new_img, new_img, file) = thumbs_engine(screen, new_img, file)
    if not gl.TOGGLE_FULLSCREEN_SET:
        screen = set_mode(screen.get_size(), RESIZABLE)  # restore resize priviledges
    rect = get_center(screen, new_img)
    my_update_screen(new_img, rect, file)
    normal_cursor()
    gl.THUMBING = 0
    return (new_img, new_img, new_img, file, rect)
Ejemplo n.º 5
0
Archivo: res.py Proyecto: rkulla/imgv
def command_fullscreen():
    "Toggle between full screen and last screen resolution"
    screen = get_surface()
    wait_cursor()
    if not toggle_fullscreen():
        try:
            if gl.FULLSCREEN_SPECIAL:
                screen_res = screen.get_size()
            else:
                screen_res = screen.get_size()
                gl.MAX_SCREEN_FILES = gl.MAX_SF["%sx%s" % (
                    screen_res[0], screen_res[1])]

            if not gl.TOGGLE_FULLSCREEN_SET:  # go into fullscreen mode
                gl.BEFORE_WINSIZE = screen.get_size()
                screen = set_mode(screen_res, screen.get_flags(
                ) ^ FULLSCREEN, screen.get_bitsize())
            else:  # returning from fullscreen. Go back to last screen size:
                set_mode(gl.BEFORE_WINSIZE, screen.get_flags(
                ) ^ FULLSCREEN, screen.get_bitsize())
                screen = set_mode(
                    gl.BEFORE_WINSIZE, RESIZABLE)  # make resizeable
            my_toggle_fullscreen()
        except:
            print "Couldn't toggle fullscreen. Resolution probably not supported by your video card."
    return screen
Ejemplo n.º 6
0
def build(settings):  
	pygame.init()
	fullscreen = True
	  
	if fullscreen:
		depth = 0
		flags = FULLSCREEN | HWSURFACE | DOUBLEBUF
	else:
		depth = 16
		flags = SWSURFACE | DOUBLEBUF
	  
	modes = display.list_modes(depth, flags)
	if fullscreen:
		if modes == -1:  # Welcome to exceptionlessland
			raise SystemExit("Failed to initialize display")
		else:
			mode = max(modes)
	else:
		mode = (settings.screen_width,settings.screen_height)
	  
	display.set_mode(mode, flags)
	#print(modes)
	#print(mode[0])
	#print(mode[1])
	return (display.get_surface(),mode[0],mode[1])
Ejemplo n.º 7
0
def main():
    pygame.init()
    display.set_mode((1280, 720), pygame.RESIZABLE)
    display.set_caption("Ethos")
    display.set_gamma_ramp
    game = EthosMain()
    game.run()
Ejemplo n.º 8
0
def main():
    print "#"*31
    print "### Welcome to MindMixer ###"
    print "####### Version 0.1beta #######"
    print """Have a look at the sourcecode!
Change stuff to suit your needs!
The program will hopefully be
self explaining. Hafe fun!"""
    print "#"*31
    selftests()
    global N
    while 1:
        print "(Hint: while training, you can hit SPACE to abort)"
        print "Hit '"+KEYLEFT+"' if the",str(N)+". previous image is identical to the one shown"
        print "Hit '"+KEYRIGHT+"' if the",str(N)+". previous sound is identical to the one heard"
        while 1:
            print "Ready to train with N=%i?" %(N),
            if ask():
                break
            else:
                print "Do you wish to train with N set to a different value? Choosing 'No' exits the program.",
                if ask():
                    n = int(raw_input("Ok, enter the desired value here: "))
                    while n < 1:
                        print "N must be 1 or higher!"
                        n = int(raw_input("Enter a value higher than 1: "))
                    N = n
                else:
                    print "bye"
                    sys.exit(1)
                
        display.init()
        display.set_mode(RESOLUTION, FULLSCREEN)
        font.init()
        mixer.init(44100)
        event.set_grab(True)
        mouse.set_visible(False)
        trials = gentrials()
        for trial in trials:
            if not trial.runtrial():
                break
        display.quit()
        vis = 0.0
        acu = 0.0
        for trial in trials:
            if trial.result[0]:
                vis+=1
            if trial.result[1]:
                acu+=1
        vp = (vis/(MINTRIALS+N))*100
        ap = (acu/(MINTRIALS+N))*100
        message = "percentage in visual modality:%i\npercentage in acoustic modality:%i\n" %(int(vp),int(ap))
        print message
        if vp >= UPPERTH and ap >= UPPERTH:
            N+=1
        elif (vp < LOWERTH or ap < LOWERTH) and N > 1:
            N-=1
Ejemplo n.º 9
0
def main():
    n = 200000
    m = 200
    
    print 'How fast can a world with {0} items and {1} creatures run.'.format(n, m)

    pygame.init()
    
    game = Game((256,256,128))
    user = Player(game.world)

    for i in range(n):
        game.world.additem(Pickax((randint(0,255),randint(0,255),64),
                                  choice(Metal.__subclasses__()),
                                  choice(Wood.__subclasses__())))

    for i in range(m):
        game.schedule(Dwarf(user, (randint(0,255),randint(0,255),64)))

    display.set_mode((1400,800), HWSURFACE | RESIZABLE)

    renderers = [Renderer(game, user, DisplayOptions('FreeMono.ttf', False, 16, 18))]
    
    game_acc = 0
    render_acc = 0

    last = time()

    while renderers:
        current = time()
        delta = min(0.125, max(0, current - last))

        renderer = renderers[-1]   
        
        if renderer.game:
            game_acc += delta
            while game_acc > renderer.game.dt:
                renderer.game.step()
                game_acc -= renderer.game.dt
            rest = renderer.game.dt - game_acc
        else:
            rest = float('inf')
        
        render_acc += delta
        if render_acc > renderer.dt:
            child = renderer.step()
            if child != renderer:
                if child:
                    renderers.append(child)
                else:
                    renderers = renderers[:-1]
            render_acc = 0

        last = current

        sleep(min(rest, renderers[-1].dt if renderers else 0))
Ejemplo n.º 10
0
	def __init__(self):
		print '%s here' % self.__name__()
		if android:
			android.init()
			android.map_key(android.KEYCODE_MENU, K_ESCAPE)

		init()
		display.set_mode((X_MAX, Y_MAX))

		font.init()

		self.location = Location(self.location_index)
def pattern():
    display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
    display.set_caption('TOUCH-FREE FLAPPY')
    myfont = font.Font(FONT, FONT_SIZE)
    screen = display.get_surface()
    pt = 1
    while 1:
        i = cam.getImage()
        (r,g,b)=i[640,350]
        if r>rrm and r<rrx and g>rgm and g<rgx and b>rbm and b<rbx and pt==1:
            pt=2
        if r>grm and r<grx and g>ggm and g<ggx and b>gbm and b<gbx and pt==2:
            pt=3
        if r>yrm and r<yrx and g>ygm and g<ygx and b>ybm and b<ybx and pt==3:
            main()
Ejemplo n.º 12
0
    def resize( self, width, height):
        """
        """
        self.size = (width, height)

        # This is painfully hacky, basically just remake the entire screen
        self.screen = display.set_mode((width, height), self.DISPLAY_MODE)
        # And reinitialize the GL context, ... ouch
        self.setup()

        # This is pretty normal
        if height == 0: height = 1

        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        if (width <= height):
            glOrtho(-5.0, 5.0, -5.0*height/width, 
               5.0*height/width, -5.0, 5.0)
        else:
            glOrtho(-5.0*width/height, 
                     5.0*width/height, -5.0, 5.0, -5.0, 5.0)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        return
Ejemplo n.º 13
0
def init(size, fullscreen = False):
	global width, height, ratio
        width, height = size
	ratio = float(width)/float(height)
        flags = OPENGL | DOUBLEBUF
        if fullscreen:
                flags = flags | FULLSCREEN
        surface = display.set_mode(size, flags)

        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0, ratio*3, 3, 0, -10, 10)
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()

        glClearColor(0.0, 0.0, 0.0, 1.0)
        glEnable(GL_DEPTH_TEST)
        glDisable(GL_CULL_FACE)

	glLineWidth(3)

        return (ratio*3, 3)
Ejemplo n.º 14
0
    def __init__(self, size, tilesize=100, message_font=None, glyph_font=None, margin=50, circle=False, tile_cls=None):
        Board.__init__(self, size, tile_cls)

        font.init()
        message_font      = message_font or (None, 60)
        glyph_font        = glyph_font or (None, 70)
        self.message_font = font.Font(message_font[0], message_font[1])
        self.glyph_font   = font.Font(glyph_font[0], glyph_font[1])
        n                 = tilesize + 1
        self.margin       = margin
        self.scr          = display.set_mode((size[0]*n + margin*2, size[1]*n + margin*2))
        self.scr.fill(white)
        self.sfc = Surface(self.scr.get_size())
        self.sfc = self.sfc.convert()
        self.sfc.fill(white)

        self.scr.blit(self.sfc, (0,0))
        self.tilesize  = tilesize
        self.circle    = circle
        self.tile_locs = [[ (iround(margin+x+tilesize/2) , iround(margin+y+tilesize/2))
                              for x in range(0, size[0]*n, n)]
                              for y in range(0, size[1]*n, n)]
        for tile in self:
            self.mkgui_tile(tile.loc)

        self.scr.blit(self.sfc, (0,0))
        display.flip()
Ejemplo n.º 15
0
 def __init__(self, name='demo'):
     init()
     State.events = EventManager()
     State.game = util.load_cfg(name)
     State.clock = Clock(10, State.game['frame_rate'])
     State.window = display.set_mode(State.game['screen_size'])
     self.create_screens()
Ejemplo n.º 16
0
	def __init__(self, resolution, world, viewport=None):
		pgdisplay.init()
		self.screen = pgdisplay.set_mode(resolution, pg.DOUBLEBUF)
		# self.screen = pgdisplay.set_mode(resolution, pg.DOUBLEBUF|pg.FULLSCREEN)
		pgdisplay.set_caption('PyAudioEffect')
		self.world = world
		self.viewport = viewport
Ejemplo n.º 17
0
	def __init__(self, width, height, images, settings):
		"""
		- Initialise the screen
		- Fill screen with "Cells"
		- Convert images to pygame format
		- Spawn ants, food sources, obstacles, ant home, etc
		"""
		self.settings = settings
		self.width = width
		self.height = height
		self.cell_size = settings["cell_size"]
		self.images = images

		self.canvas = display.set_mode((self.width*self.cell_size, self.height*self.cell_size))
		self.convert_images()

		self.cells = [[Cell(self, i, j) for j in xrange(height)] for i in xrange(width)]

		self.counter = 0

		self.ants = {}
		self.nests = {}
		# self.spawn_worker_ants()
		# self.spawn_soldier_ants()
		self.create_walls()
		for i in xrange(4):
			self.spawn_foodsource()
		# self.create_home()
		self.spawn_colonies(2)
Ejemplo n.º 18
0
def main(argv=sys.argv[1:]):

    pygame.init()
    screen = display.set_mode(DISPLAY_SIZE)

    ball = image.load('samples/4-2/ball.png')

    # 描画座標を保持する変数
    x, y = 0, 0

    while True:
        event_dispatch()
        screen.fill((0, 0, 0))

        # 右矢印キーの入力状態と左矢印キーの入力状態を見て 1, 0, -1 の値を生成する
        dx = get_key_state('right') - get_key_state('left')

        # 下矢印キーの入力状態と上矢印キーの入力状態を見て 1, 0, -1 の値を生成する
        dy = get_key_state('down') - get_key_state('up')

        # キー入力状態から座標を変化させる
        x += dx * 5
        y += dy * 5

        # 変化させた座標に描画する
        screen.blit(ball, (x, y))

        display.flip()
        time.delay(100)
Ejemplo n.º 19
0
 def refootprint(self, ev):
     # Clear the window
     # display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 1)
     # display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 4)
     self.screen = display.set_mode((ev.w, ev.h),
                                    pygame.OPENGL | pygame.RESIZABLE | pygame.DOUBLEBUF)
     global gl
     from . import opengl as gl
     gl.viewport(0, 0, ev.w, ev.h)
     gl.clear(gl.color_buffer_bit)
     # Compute a 4:3 viewport
     sz = min(ev.w*3, ev.h*4)
     self.w = sz // 3
     self.h = sz // 4
     offx = (ev.w - self.w) // 2
     offy = (ev.h - self.h) // 2
     gl.viewport(offx, offy, self.w, self.h)
     self.basic_shader = build_shader(basic_shader, self.w, self.h)
     self.sunlight = gl.sunlightTextures(128, 128, 512)
     self.sunlight_dl = self.sunlight[0].displayList(-1, 1, -1, 1)
     global shader
     shader = self.basic_shader
     shader.attach()
     shader.seti("tex", 0)
     self.backlog_dirty = True
Ejemplo n.º 20
0
def bootstrap_game():
    pygame.display.init()
    pygame.mixer.init(frequency=config.getint('sound', 'frequency'),
                      buffer=config.getint('sound', 'buffer'))
    pygame.font.init()
    pygame.init()

    main_surface = set_mode((config.getint('display', 'width'),
                             config.getint('display', 'height')))

    main_surface.fill((0, 0, 0))
    gui.draw_text(main_surface, "loading, please wait...", (255, 255, 255),
                  main_surface.get_rect())
    pygame.display.flip()

    for path, thing in resources.load():
        logger.info('loaded %s', path)
        pygame.event.pump()

    game = Game(config.getint('display', 'target-fps'), main_surface)
    game.register_scene(TitleScene(game))
    level_scene = LevelScene(game)
    game.register_scene(level_scene)
    level_scene.init()
    game.push_scene('level')
    return game
Ejemplo n.º 21
0
def start_menu():
    from pygame.display import set_mode, list_modes, set_caption
    from pygame import init, quit
    from pygame.constants import FULLSCREEN
    from bin.Controller import process
    from obj.Field import Field

    init()
    screen = set_mode(list_modes()[0], FULLSCREEN)
    set_caption("Hero Misadventures")
    menu = Menu(("Previous Field", "New Field", "Load Field", "Quit"), screen, surface=color("Lawn Green"),
                selection_color=color("Lime Green"), text_color=color("Medium Blue"))
    while True:
        choose = menu.update()
        if choose == 0:
            field = Field(screen)
            process(screen, field)
        elif choose == 1:
            from ctypes import cdll
            cdll.LoadLibrary("Generator.so").main_generator("res/GENERATOR.HMinf", "res/FIELD.HMmap")
            field = Field(screen)
            process(screen, field)
        elif choose == 2:
            from pickle import load

            field = load(open("res/SAVE.HMsave", "rb"))
            field.screen = screen
            process(screen, field)
        elif choose == 3:
            quit()
            return
Ejemplo n.º 22
0
 def __init__(self, fps=60):
     self.fps = fps
     self.screen = display.set_mode((0, 0), pygame.FULLSCREEN |
                                    pygame.HWSURFACE | pygame.DOUBLEBUF)
     self.width = display.Info().current_w
     self.height = display.Info().current_h
     self.on = True
Ejemplo n.º 23
0
 def main():
     display.init()
     maxX,maxY = display.list_modes()[0] 
     screen = display.set_mode( (maxX/3, maxY/3 ) )
     
     display.flip()
     
     pgw = PygameWidget( )
     p = Player( pgw, pipe_desc=Player.test_pipe_desc )
     p.play()
     
     clock = pygame.time.Clock()
     
     running = True
     while running:
         clock.tick( 60 )
         for evt in [pygame.event.wait()] + pygame.event.get():
             if evt.type == pygame.KEYDOWN:
                 if p._playing:
                     p.pause()
                 else:
                     p.play()
             elif evt.type == pygame.QUIT:
                 p.stop()
                 running = False
Ejemplo n.º 24
0
def main():
	terminou = False
	term.cout (defaultMessageColor, 'Application Started!')
	init ()
	screen = display.set_mode (windowSize)
	snake= Snake(windowSize[0]/2, windowSize[0]/2)
	snake.generateFood (1, 1, screen.get_width(), screen.get_height())
	core = GameCore (screen)
	core.setMainDelay (0.2)
	
	while not terminou:
		for ev in event.get ():
			if ev.type == QUIT:
				terminou = True
				break;
				
			elif ev.type == KEYDOWN:
				term.cout ('warning', 'Keypressed: ' + str (ev.key))
				
				if ev.key == LEFT or ev.key == RIGHT or ev.key == DOWN or ev.key == UP:
					snake.move (ev.key)
		
		core.blitWalls ()
		snake.blit (screen)
		snake.blitFood (screen)
		snake.move (snake.getDirection())
		core.flipDisplay ()
Ejemplo n.º 25
0
 def __initPython(self, windowSize):
    self.__windowSize = windowSize
    
    self.__window = display.set_mode(self.__windowSize)
    display.set_caption("Atlas Chronicle Game Engine")
    self.__screen = display.get_surface()
    
    self.__canvas = Surface(self.__windowSize)
Ejemplo n.º 26
0
 def _resize(self, size):
     old_size = self.display.get_size()
     scale_x = float(size[0])/float(old_size[0])
     scale_y = float(size[1])/float(old_size[1])
     for point in self.objects.values():
         point.x *= scale_x
         point.y *= scale_y
     self.display = pdis.set_mode(size, pygame.RESIZABLE)
Ejemplo n.º 27
0
    def set_mode(self):
        #modes = display.list_modes()
        #self.display_surface = display.set_mode(modes[0], self.get_flags())
        self.display_surface = display.set_mode((800,600), self.get_flags())

        self.width = self.display_surface.get_width()
        self.height = self.display_surface.get_height()
        display.set_caption("Woger the Wibbly Wobbly Wombat")
Ejemplo n.º 28
0
def restore_screen(screen, before_winsize, not_accepted, new_img, file, num_imgs, rect):
    if gl.TOGGLE_FULLSCREEN_SET and not_accepted: 
        # we were fullscreen with gl.FULLSCREEN_SPECIAL on a non-accepted window size
        screen = command_fullscreen(screen, new_img, file, num_imgs, rect)
    else:
        if not gl.TOGGLE_FULLSCREEN_SET:
            screen = set_mode(before_winsize, RESIZABLE)
    return screen
Ejemplo n.º 29
0
def initialize():
    passed, failed = PG.init()
    print passed
    Globals.SCREEN = PDI.set_mode((800, 600), PG.DOUBLEBUF | PG.HWSURFACE)
    Globals.WIDTH = Globals.SCREEN.get_width()
    Globals.HEIGHT = Globals.SCREEN.get_height()
    Globals.FONT = PF.Font(None, 48)
    Globals.STATE = Title.Title_Screen()
Ejemplo n.º 30
0
Archivo: view.py Proyecto: MGralka/pyz
 def __init__(self):
     self.__actorSpriteList = {}
     self._screen = display.set_mode((800, 600))
     self._eventHandler = ViewEventHandler(self)
     application.Application.eventManager.addListener(
         self._eventHandler, EventIds.ACTOR_CREATED_ID)
     application.Application.eventManager.addListener(
         self._eventHandler, EventIds.MOVE_ACTOR_ID)
Ejemplo n.º 31
0
from pygame import init, display, mixer, font, draw, event, QUIT, KEYUP, KEYDOWN, K_UP, K_DOWN, K_LEFT, K_RIGHT, K_SPACE
from pygame_test_game import collision, config, game_object
from random import randint

# Initialize pygame
init()

screen = display.set_mode((config.screen_width, config.screen_height))

# Background
# background = pygame.image.load('background.png')

# Title and Icon
display.set_caption("Test Game")
# icon = pygame.image.load('icon.png')
# pygame.display.set_icon(icon)


# Text
text_font = font.Font('freesansbold.ttf', 32)
end_text = font.Font('freesansbold.ttf', 64)

# Sound
# mixer.music.load('FILENEEDED.wav')
# mixer.music.play(-1)

# Game Loop
running = True
game_over = False
win = False
Ejemplo n.º 32
0
def window_resize(size):
    return display.set_mode(size)
Ejemplo n.º 33
0
from pygame.locals import QUIT, KEYDOWN
from Grid import *
from pygame import init, display, event
from pygame import K_a, K_b, K_h, K_d, K_v, K_n, K_g, K_s, K_e, K_BACKSPACE
import sys
from random import randint

# Pygame window attributes
WINDOW_SIZE = (610, 410)
FPS = 60

# init Pygame
init()
screen = display.set_mode(WINDOW_SIZE)
# Learning about pathfinding / search algorithms

g = Grid(screen, dimensions=WINDOW_SIZE)

def BreadthFS(start=(0, 0), end=(g.x_elems - 1, g.y_elems - 1)):
    g.reset(False)
    end = g.grid[end[1]][end[0]]
    # Paths to extend
    agenda = [[g.grid[start[1]][start[0]]]]
    # already visited / checked / extended
    extendedList = []

    while agenda:
        path = agenda.pop(0)
        if path[-1] == end:
            for node in path:  # For Drawing the final path
                node.isPath = True
Ejemplo n.º 34
0
    inc2 = 1
    shots = 0
    badlistpos = []
    buildx, buildy = 0, 0
    num = 0
    buildtimer = 1
    delay = 0
    baddelay = 0
    num2 = 0
    suckedup = 0
    buildlist = []
    timer = 60
    valid = False


screen = display.set_mode((800, 600))
UFO = image.load("images/UFO.png").convert_alpha()
background = image.load("images/background.png").convert_alpha()
crosshair = image.load("images/crosshair.png").convert_alpha()
building = transform.scale(
    image.load("images/m.jpg").convert_alpha(), (60, 120))
bucket = transform.scale(
    image.load("images/paintbucket.png").convert_alpha(), (200, 206))
rightarrow = transform.scale(
    image.load("images/rightarrow.png").convert_alpha(), (817 / 5, 223 / 5))
leftarrow = transform.scale(
    image.load("images/leftarrow.png").convert_alpha(), (817 / 5, 223 / 5))
titlescreen = transform.scale(
    image.load("images/ufotitle.jpg").convert_alpha(), (485, 364))
fullmap = Rect(-415, 0, 600, 9575)
Ejemplo n.º 35
0
    def reset(self, splash=None, caption=("", "")):
        pygame.key.set_repeat(500, 100)

        try:
            display.gl_set_attribute(pygame.GL_SWAP_CONTROL,
                                     config.settings.vsync.get())
        except Exception as e:
            logging.warning('Unable to set vertical sync: {0!r}'.format(e))

        display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8)

        if DEBUG_WM:
            print "config.settings.windowMaximized.get()", config.settings.windowMaximized.get(
            )
        wwh = self.getWindowSize()
        if DEBUG_WM:
            print "wwh 1", wwh
        d = display.set_mode(wwh, self.displayMode())

        # Let initialize OpenGL stuff after the splash.
        GL.glEnableClientState(GL.GL_VERTEX_ARRAY)
        GL.glAlphaFunc(GL.GL_NOTEQUAL, 0)
        GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)

        # textures are 256x256, so with this we can specify pixel coordinates
        #        GL.glMatrixMode(GL.GL_TEXTURE)
        #        GL.glScale(1 / 256., 1 / 256., 1 / 256.)

        display.set_caption(*caption)

        if mcplatform.WindowHandler:
            self.win = mcplatform.WindowHandler(mode=self.displayMode())

        # The following Windows specific code won't be executed if we're using '--debug-wm' switch.
        if not USE_WM and sys.platform == 'win32' and config.settings.setWindowPlacement.get(
        ):
            config.settings.setWindowPlacement.set(False)
            config.save()
            X, Y = config.settings.windowX.get(), config.settings.windowY.get()

            if X:
                hwndOwner = display.get_wm_info()['window']

                flags, showCmd, ptMin, ptMax, rect = mcplatform.win32gui.GetWindowPlacement(
                    hwndOwner)
                realW = rect[2] - rect[0]
                realH = rect[3] - rect[1]

                showCmd = config.settings.windowShowCmd.get()
                rect = (X, Y, X + realW, Y + realH)

                mcplatform.win32gui.SetWindowPlacement(
                    hwndOwner, (0, showCmd, ptMin, ptMax, rect))

            config.settings.setWindowPlacement.set(True)
            config.save()
        elif self.win:
            maximized = config.settings.windowMaximized.get()
            if DEBUG_WM:
                print "maximized", maximized
            if maximized:
                geom = self.win.get_root_rect()
                in_w, in_h = self.win.get_size()
                x, y = int((geom[2] - in_w) / 2), int((geom[3] - in_h) / 2)
                os.environ['SDL_VIDEO_CENTERED'] = '1'
            else:
                os.environ['SDL_VIDEO_CENTERED'] = '0'
                x, y = config.settings.windowX.get(
                ), config.settings.windowY.get()
                wwh = self.win.get_size()
            if DEBUG_WM:
                print "x", x, "y", y
                print "wwh 2", wwh

        if splash:
            # Setup the OGL display
            GL.glLoadIdentity()
            GLU.gluOrtho2D(0, wwh[0], 0, wwh[1])
            GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT
                       | GL.GL_ACCUM_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT)

            swh = splash.get_size()
            _x, _y = (wwh[0] / 2 - swh[0] / 2, wwh[1] / 2 - swh[1] / 2)
            w, h = swh

            try:
                data = image.tostring(splash, 'RGBA_PREMULT', 1)
            except ValueError:
                data = image.tostring(splash, 'RGBA', 1)
            except ValueError:
                data = image.tostring(splash, 'RGB', 1)

            # Set the raster position
            GL.glRasterPos(_x, _y)

            GL.glDrawPixels(w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE,
                            numpy.fromstring(data, dtype='uint8'))

        if splash:
            display.flip()

        if self.win:
            if not maximized:
                wwh = self.getWindowSize()
            if DEBUG_WM:
                print "wwh 3", wwh
            self.win.set_position((x, y), update=True)
            if DEBUG_WM:
                print "* self.win.get_position()", self.win.get_position()

        try:
            iconpath = os.path.join(directories.getDataDir(), 'favicon.png')
            iconfile = file(iconpath, 'rb')
            icon = pygame.image.load(iconfile, 'favicon.png')
            display.set_icon(icon)
        except Exception as e:
            logging.warning('Unable to set icon: {0!r}'.format(e))

        # Let initialize OpenGL stuff after the splash.
#         GL.glEnableClientState(GL.GL_VERTEX_ARRAY)
#         GL.glAlphaFunc(GL.GL_NOTEQUAL, 0)
#         GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)

# textures are 256x256, so with this we can specify pixel coordinates
        GL.glMatrixMode(GL.GL_TEXTURE)
        GL.glScale(1 / 256., 1 / 256., 1 / 256.)

        self.display = d

        self.loadTextures()
Ejemplo n.º 36
0
from pygame import display, draw, time, event
import pygame
from random import randint


class Bubble:
    def __init__(self):
        self.colour = [randint(0, 255), randint(0, 255), randint(0, 255)]
        self.center = [randint(1, 599), randint(1, 799)]
        self.radius = 1

    def expand(self):
        self.radius += 1


screen = display.set_mode([800, 600])


def CreateBubbles(Bubbles):
    if Bubbles.__len__() < 30:
        Bubbles.append(Bubble())
    else:
        Bubbles.pop(0)


def DrawBubbles(Bubbles):
    for bubble in Bubbles:
        draw.circle(screen, bubble.colour, bubble.center, bubble.radius, 1)
        if bubble.radius < 50:
            bubble.expand()
Ejemplo n.º 37
0
    def test_get_caption(self):
        screen = display.set_mode((100, 100))

        self.assertEqual(display.get_caption()[0], self.default_caption)
Ejemplo n.º 38
0
from pygame.display import set_mode
from pygame.constants import RESIZABLE

screen = set_mode((800,600), RESIZABLE)
Ejemplo n.º 39
0
            pellets[data['pellet_index']] = data['new_pellet']
        
        elif msgtype == 'grow':
            players[name].size = tuple(data['size'])  
            
        elif msgtype == 'die':
            left, top, width, height = tuple(data['state'])
            players[name] = Rect(left, top, width, height)
            if name == myname:
                mybox = players[myname]
            
            
client = Client('localhost', 8888)

pygame_init()
screen = set_mode((400, 300))
clock = Clock()
font = Font(None, 15)  # default pygame Font, height in pixels

borders = [Rect(0, 0, 2, 300), Rect(0, 0, 400, 2),
           Rect(398, 0, 2, 300), Rect(0, 298, 400, 2)]
dx, dy = 0, 1  # start direction: down
delay = 0  # start moving right away 

while True:
    
    clock.tick(50)  # frames per second
    poll()  # push and pull network messages

    for event in pygame_event.get():  # inputs
        if event.type == QUIT:
Ejemplo n.º 40
0
import math, timer, button
from pygame import init, font, time, event, key, draw, display, quit
from pygame.event import get
from pygame import K_UP, K_LEFT, K_RIGHT, K_DOWN, K_SPACE, QUIT, KEYDOWN
from sys import exit
init()
font.init()
width = 1200
height = 600
screen = display.set_mode((width, height))

done = False

is_red = True

gameTimer = timer.Timer(100, 550, 100, 50)

restartButton = button.Button('Restart', (178, 34, 34), (255, 0, 0), 550, 275,
                              100, 50)

timerFont = font.SysFont('timesnewroman', 26, False, False, None)

buttonFont = font.SysFont('timesnewroman', 24, False, False, None)

speed = 3

xp = 1100  #Variable for X coordinate of Player Circle
yp = 300  #Variable for Y coordinate of Player Circle

r = 13
Ejemplo n.º 41
0
from pygame import Surface
from pygame import image
from pygame import display
from constants import *

window = display.set_mode((830, 620))
display.set_caption('Svinotest')

start_screen = Surface((810, 600))
background = image.load ('images/back.png')
adventure_screen = Surface ((810, 420))
instrumental_screen = Surface ((810,170))
hero_screen = Surface ((60,170))
monster_screen = Surface ((150,150))
information_screen = Surface ((740,170))

def main_interface ():
	window.blit(start_screen, (10, 10))
	start_screen.fill ((black))
	start_screen.blit (adventure_screen, (0,0))
	adventure_screen.fill ((black))
	start_screen.blit (instrumental_screen, (0,430))
	instrumental_screen.fill ((sea_color))
	instrumental_screen.blit (hero_screen, (0,0))
	hero_screen.fill ((cool_orange))
	instrumental_screen.blit (information_screen, (70,0))
	information_screen.fill ((black))
	#instrumental_screen.blit (monster_screen, (650,0))
	#monster_screen.fill ((sea_color))
Ejemplo n.º 42
0
 def initiate_display(self):
     self.surface = display.set_mode(
         ((self.width * self.scale), (self.height * self.scale)))
     display.set_caption("Vip8")
     self.clear_screen()
     self.update_screen()
Ejemplo n.º 43
0
def graph_loop(mass_lower_limit=0.0,
               mass_upper_limit=0.0,
               radius_lower_limit=0.0,
               radius_upper_limit=0.0,
               is_gas_drwaf=False):
    m_lo_l = mass_lower_limit
    m_hi_l = mass_upper_limit
    r_lo_l = radius_lower_limit
    r_hi_l = radius_upper_limit

    fondo = display.set_mode((witdh, height), SCALED)
    rect = Rect(60, 2, 529, 476)
    lineas = LayeredUpdates()

    linea_h = Linea(rect, rect.x, rect.centery, rect.w, 1, lineas)
    linea_v = Linea(rect, rect.centerx, rect.y, 1, rect.h, lineas)
    punto = Punto(rect, rect.centerx, rect.centery, lineas)

    data = {}

    if any([
            mass_lower_limit < 0, mass_upper_limit < 0, radius_lower_limit < 0,
            radius_upper_limit < 0
    ]):
        raise ValueError()

    lim_mass_a = int(find_and_interpolate(m_lo_l, mass_keys,
                                          exes)) if m_lo_l else 0
    lim_mass_b = int(find_and_interpolate(m_hi_l, mass_keys,
                                          exes)) if m_hi_l else 0
    lim_radius_a = int(find_and_interpolate(r_lo_l, radius_keys,
                                            yes)) if r_lo_l else 0
    lim_radius_b = int(find_and_interpolate(r_hi_l, radius_keys,
                                            yes)) if r_hi_l else 0

    move_x, move_y = True, True
    lockx, locky = False, False

    mass_value = 0
    radius_value = 0

    mass_color = negro
    radius_color = negro

    mouse.set_pos(rect.center)
    event.clear()

    done = False
    composition_text_comp = None
    while not done:
        for e in event.get():
            if e.type == QUIT:
                py_quit()
                if __name__ == '__main__':
                    sys.exit()
            elif e.type == MOUSEBUTTONDOWN:
                if e.button == 1:
                    if (not lockx) or (not locky):
                        if (not lockx) and (not move_x):
                            lockx = True

                        elif (not locky) and (not move_y):
                            locky = True

                        elif not punto.disabled:
                            data['mass'] = round(mass_value, 3)
                            data['radius'] = round(radius_value, 3)
                            data['gravity'] = round(
                                mass_value / (radius_value**2), 3)
                            data['density'] = round(
                                mass_value / (radius_value**3), 3)
                            done = True
                        else:
                            data = {}
                            done = True

                elif e.button == 3:
                    if lockx:
                        lockx = False
                        move_x = not lockx

                    if locky:
                        locky = False
                        move_y = not locky

            elif e.type == MOUSEMOTION:
                px, py = e.pos
                if move_y:
                    linea_h.move_y(py)
                    punto.move_y(py)

                if move_x:
                    linea_v.move_x(px)
                    punto.move_x(px)

                point_x, point_y = punto.rect.center
                if rect.collidepoint(point_x, point_y) and (move_x or move_y):
                    if mascara.get_at((point_x, point_y)):
                        punto.select()
                        for name in _lineas:
                            if [point_x, point_y] in _lineas[name]:
                                composition_text_comp = name
                                break
                    else:
                        punto.deselect()

            elif e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    py_quit()
                    sys.exit()

                if e.key == K_LSHIFT:
                    move_x = False

                elif e.key == K_LCTRL:
                    move_y = False

                elif e.key == K_SPACE:
                    data['mass'] = round(mass_value, 3)
                    data['radius'] = round(radius_value, 3)
                    data['gravity'] = round(mass_value / (radius_value**2), 3)
                    data['density'] = round(mass_value / (radius_value**3), 3)
                    done = True

            elif e.type == KEYUP:
                if e.key == K_LSHIFT:
                    if not lockx:
                        move_x = True

                elif e.key == K_LCTRL:
                    if not locky:
                        move_y = True

        px, py = punto.rect.center
        alto, bajo = 0, 0
        if rect.collidepoint((px, py)):
            for _y in reversed(range(0, py)):
                if mascara.get_at((px, _y)):
                    alto = _y
                    break
            for _y in range(py, 476):
                if mascara.get_at((px, _y)):
                    bajo = _y
                    break

            a, b = 0, 0
            # creo que esto se puede escribir con oneliners.
            for name in _lineas:
                if [px, alto] in _lineas[name]:
                    a = name
                    break
            for name in _lineas:
                if [px, bajo] in _lineas[name]:
                    b = name
                    break
            if a and b:
                c = composiciones
                silicates = interpolate(py, alto, bajo, c[a]['silicates'],
                                        c[b]['silicates'])
                hydrogen = interpolate(py, alto, bajo, c[a]['hydrogen'],
                                       c[b]['hydrogen'])
                helium = interpolate(py, alto, bajo, c[a]['helium'],
                                     c[b]['helium'])
                iron = interpolate(py, alto, bajo, c[a]['iron'], c[b]['iron'])
                water_ice = interpolate(py, alto, bajo, c[a]['water ice'],
                                        c[b]['water ice'])
                values = [
                    i for i in [silicates, hydrogen, helium, iron, water_ice]
                    if i != 0
                ]

                # sólo mostramos los valores mayores a 0%
                keys, compo = [], []
                if silicates:
                    compo.append(str(round(silicates, 2)) + '% silicates')
                    keys.append('silicates')
                if hydrogen:
                    compo.append(str(round(hydrogen, 2)) + '% hydrogen')
                    keys.append('hydrogen')
                if helium:
                    compo.append(str(round(helium, 2)) + '% helium')
                    keys.append('helium')
                if iron:
                    compo.append(str(round(iron, 2)) + '% iron')
                    keys.append('iron')
                if water_ice:
                    compo.append(str(round(water_ice, 2)) + '% water ice')
                    keys.append('water ice')

                composition_text_comp = ', '.join(compo)
                data['composition'] = dict(zip(keys, values))

                if hydrogen or helium:
                    data['clase'] = 'Gas Dwarf'
                    data['albedo'] = 30
                else:
                    data['clase'] = 'Terrestial Planet'
                    data['albedo'] = 25
            else:
                data = {}

        mass_value = find_and_interpolate(linea_v.rect.x, exes, mass_keys)
        radius_value = find_and_interpolate_flipped(linea_h.rect.y, yes,
                                                    radius_keys)

        block = Surface(rect.size, SRCALPHA)
        block_mask = mask.from_surface(block)
        if any([lim_mass_b, lim_mass_a, lim_radius_a, lim_radius_b]):
            block_rect = block.get_rect(topleft=rect.topleft)
            alpha = 150
            if lim_mass_a:
                block.fill([0] * 3 + [alpha],
                           (0, rect.y - 2, lim_mass_a - rect.x, rect.h))
            if lim_mass_b:
                block.fill([0] * 3 + [alpha],
                           (lim_mass_b - rect.x, rect.y - 2, rect.w, rect.h))
            if lim_radius_a:
                block.fill([0] * 3 + [alpha],
                           (0, lim_radius_a, rect.w, rect.h - lim_radius_a))
            if lim_radius_b:
                block.fill([0] * 3 + [alpha],
                           (0, rect.y - 2, rect.w, lim_radius_b))
            if is_gas_drwaf:
                block.blit(gas_drawf, (0, 0))

            block_mask = mask.from_surface(block)
            point_x, point_y = punto.rect.center
            if block_rect.collidepoint((point_x, point_y)):
                if block_mask.get_at((point_x - rect.x, point_y - rect.y)):
                    punto.disable()
                    radius_color = rojo
                    mass_color = rojo
                else:
                    punto.enable()
                    mass_color = negro
                    radius_color = negro

        mass_text = 'Mass:' + str(round(mass_value, 3))
        radius_text = 'Radius:' + str(round(radius_value, 3))
        gravity_text = 'Density:' + str(
            round(mass_value / (radius_value**3), 3))
        density_text = 'Gravity:' + str(
            round(mass_value / (radius_value**2), 3))

        if not done:
            fondo.fill(blanco)
            fondo.blit(graph, (0, 0))
            if block_mask.count() != 0:
                fondo.blit(block, rect)

            if punto.disabled:
                fondo.blit(texto3, rectT3)
            else:
                fondo.blit(fuente1.render(mass_text, True, mass_color),
                           (5, rect.bottom + 43))
                fondo.blit(fuente1.render(radius_text, True, radius_color),
                           (140, rect.bottom + 43))
                fondo.blit(fuente1.render(density_text, True, negro),
                           (130 * 2 - 5, rect.bottom + 43))
                fondo.blit(fuente1.render(gravity_text, True, negro),
                           (140 * 3, rect.bottom + 43))
                if composition_text_comp is not None:
                    composition_text = 'Composition:' + composition_text_comp
                    fondo.blit(
                        fuente1.render(composition_text, True, negro, blanco),
                        (5, rect.bottom + 64))

            fondo.blit(texto1, rectT1)
            fondo.blit(texto2, rectT2)
            punto.update()
            lineas.update()
            lineas.draw(fondo)
            display.update()

    display.quit()
    return data
Ejemplo n.º 44
0
def gameloop(
    playerOrder: bool,
    p1Char: str,
    nick1: str,
    p2Char: str,
    nick2: str,
    udp: UDP_P2P,
) -> str:
    # region DocString
    """
    Function that starts the loop for pygame

    ### Arguments
        `playerOrder {bool}`:
            `summary`: true if this host is the first player, false otherwise
        `p1Char {str}`:
            `summary`: the character chosen by this host
        `nick1 {str}`:
            `summary`: the username of this host
        `p2Char {str}`:
            `summary`: the character chosen by the remote player
        `nick2 {str}`:
            `summary`: the username of the remote player
        `udp {UDP_P2P}`:
            `summary`: the udp object

    ### Returns
        `str`: the exit status. It can be 'Lost' if this host lose, 'Quit' if this host closed the window,\n
        'Win' if the remote host lose, 'Quitted' if the remote host closed the window
    """
    # endregion

    global gamestate
    clock = Clock()
    COORDSYNC = USEREVENT + 1
    set_timer(COORDSYNC, 1000)

    # region Screen setup

    screen = set_mode((Game.SIZE[0] + 400, Game.SIZE[1]))
    set_caption(Game.TITLE)
    set_icon(load(Game.ICON_PATH))
    bg = load(Game.BG_PATH).convert_alpha()
    bg = scale(bg, Game.SIZE)

    manager = UIManager((Game.SIZE[0] + 400, Game.SIZE[1]))
    chat = Chat((400, Game.SIZE[1]), manager, udp, nick1)

    # endregion

    all_sprites = Group()

    # region Players setup

    if p1Char == "Ichigo":
        pl = Ichigo(playerOrder, nick1, all_sprites)
    elif p1Char == "Vegeth":
        pl = Vegeth(playerOrder, nick1, all_sprites)

    if p2Char == "Ichigo":
        pl2 = Ichigo(not playerOrder, nick2, all_sprites)
    elif p2Char == "Vegeth":
        pl2 = Vegeth(not playerOrder, nick2, all_sprites)

    # endregion

    rcvT = udp.receptionThread(
        lambda data, addr, time: rcv(pl2, data, addr, time, chat), rcvErr)
    rcvT.start()

    while True:

        dt = clock.tick(Game.FPS) / 1000

        # region Handle window close

        pressed_keys = get_pressed()

        for event in get():
            if event.type == QUIT:
                snd(nick1, "Quit", udp)
                gamestate = "Quit"

            if event.type == COORDSYNC:
                sndCoords(nick1, (pl.rect.x, pl.rect.y), udp)

            manager.process_events(event)

        # endregion

        manager.update(dt)

        # region Handle key press and update sprites

        all_sprites.update(pressed_keys)
        sndKeys(
            nick1,
            (
                pressed_keys[K_LEFT],
                pressed_keys[K_RIGHT],
                pressed_keys[K_UP],
                pressed_keys[K_z],
            ),
            udp,
        )
        if pl.update(pressed_keys):
            snd(nick1, "Lost", udp)
            gamestate = "Lost"

        # endregion

        # region Sprite drawing

        screen.fill(Color.WHITE)
        screen.blit(bg, (0, 0))
        all_sprites.draw(screen)
        pl.draw(screen)
        pl2.draw(screen)
        pl.health.draw(screen)
        pl2.health.draw(screen)

        # endregion

        manager.draw_ui(screen)
        flip()

        if gamestate:
            udp.stopThread()
            quit()
            return gamestate
Ejemplo n.º 45
0
 def update_display_size(self):
     self.screen = display.set_mode(self.win_size,
                                    pygame.DOUBLEBUF | pygame.RESIZABLE)
     display.flip()
Ejemplo n.º 46
0
    def test_gl_get_attribute(self):

        screen = display.set_mode((0, 0), pygame.OPENGL)

        # We create a list where we store the original values of the
        # flags before setting them with a different value.
        original_values = []

        original_values.append(pygame.display.gl_get_attribute(pygame.GL_ALPHA_SIZE))
        original_values.append(pygame.display.gl_get_attribute(pygame.GL_DEPTH_SIZE))
        original_values.append(pygame.display.gl_get_attribute(pygame.GL_STENCIL_SIZE))
        original_values.append(
            pygame.display.gl_get_attribute(pygame.GL_ACCUM_RED_SIZE)
        )
        original_values.append(
            pygame.display.gl_get_attribute(pygame.GL_ACCUM_GREEN_SIZE)
        )
        original_values.append(
            pygame.display.gl_get_attribute(pygame.GL_ACCUM_BLUE_SIZE)
        )
        original_values.append(
            pygame.display.gl_get_attribute(pygame.GL_ACCUM_ALPHA_SIZE)
        )
        original_values.append(
            pygame.display.gl_get_attribute(pygame.GL_MULTISAMPLEBUFFERS)
        )
        original_values.append(
            pygame.display.gl_get_attribute(pygame.GL_MULTISAMPLESAMPLES)
        )
        original_values.append(pygame.display.gl_get_attribute(pygame.GL_STEREO))

        if SDL2:
            original_values.append(
                pygame.display.gl_get_attribute(pygame.GL_ACCELERATED_VISUAL)
            )
            original_values.append(
                pygame.display.gl_get_attribute(pygame.GL_CONTEXT_MAJOR_VERSION)
            )
            original_values.append(
                pygame.display.gl_get_attribute(pygame.GL_CONTEXT_MINOR_VERSION)
            )
            original_values.append(
                pygame.display.gl_get_attribute(pygame.GL_CONTEXT_FLAGS)
            )
            original_values.append(
                pygame.display.gl_get_attribute(pygame.GL_CONTEXT_PROFILE_MASK)
            )
            original_values.append(
                pygame.display.gl_get_attribute(pygame.GL_SHARE_WITH_CURRENT_CONTEXT)
            )
            original_values.append(
                pygame.display.gl_get_attribute(pygame.GL_FRAMEBUFFER_SRGB_CAPABLE)
            )

        # Setting the flags with values supposedly different from the original values

        # assign SDL1-supported values with gl_set_attribute
        pygame.display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8)
        pygame.display.gl_set_attribute(pygame.GL_DEPTH_SIZE, 24)
        pygame.display.gl_set_attribute(pygame.GL_STENCIL_SIZE, 8)
        pygame.display.gl_set_attribute(pygame.GL_ACCUM_RED_SIZE, 16)
        pygame.display.gl_set_attribute(pygame.GL_ACCUM_GREEN_SIZE, 16)
        pygame.display.gl_set_attribute(pygame.GL_ACCUM_BLUE_SIZE, 16)
        pygame.display.gl_set_attribute(pygame.GL_ACCUM_ALPHA_SIZE, 16)
        pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 1)
        pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 1)
        pygame.display.gl_set_attribute(pygame.GL_STEREO, 0)

        # assign SDL2-supported values with gl_set_attribute (if applicable)
        if SDL2:
            pygame.display.gl_set_attribute(pygame.GL_ACCELERATED_VISUAL, 0)
            pygame.display.gl_set_attribute(pygame.GL_CONTEXT_MAJOR_VERSION, 1)
            pygame.display.gl_set_attribute(pygame.GL_CONTEXT_MINOR_VERSION, 1)
            pygame.display.gl_set_attribute(pygame.GL_CONTEXT_FLAGS, 0)
            pygame.display.gl_set_attribute(pygame.GL_CONTEXT_PROFILE_MASK, 0)
            pygame.display.gl_set_attribute(pygame.GL_SHARE_WITH_CURRENT_CONTEXT, 0)
            pygame.display.gl_set_attribute(pygame.GL_FRAMEBUFFER_SRGB_CAPABLE, 0)

        # We create a list where we store the values that we set each flag to
        set_values = [8, 24, 8, 16, 16, 16, 16, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0]

        # We create a list where we store the values after getting them
        get_values = []

        get_values.append(pygame.display.gl_get_attribute(pygame.GL_ALPHA_SIZE))
        get_values.append(pygame.display.gl_get_attribute(pygame.GL_DEPTH_SIZE))
        get_values.append(pygame.display.gl_get_attribute(pygame.GL_STENCIL_SIZE))
        get_values.append(pygame.display.gl_get_attribute(pygame.GL_ACCUM_RED_SIZE))
        get_values.append(pygame.display.gl_get_attribute(pygame.GL_ACCUM_GREEN_SIZE))
        get_values.append(pygame.display.gl_get_attribute(pygame.GL_ACCUM_BLUE_SIZE))
        get_values.append(pygame.display.gl_get_attribute(pygame.GL_ACCUM_ALPHA_SIZE))
        get_values.append(pygame.display.gl_get_attribute(pygame.GL_MULTISAMPLEBUFFERS))
        get_values.append(pygame.display.gl_get_attribute(pygame.GL_MULTISAMPLESAMPLES))
        get_values.append(pygame.display.gl_get_attribute(pygame.GL_STEREO))

        if SDL2:
            get_values.append(
                pygame.display.gl_get_attribute(pygame.GL_ACCELERATED_VISUAL)
            )
            get_values.append(
                pygame.display.gl_get_attribute(pygame.GL_CONTEXT_MAJOR_VERSION)
            )
            get_values.append(
                pygame.display.gl_get_attribute(pygame.GL_CONTEXT_MINOR_VERSION)
            )
            get_values.append(pygame.display.gl_get_attribute(pygame.GL_CONTEXT_FLAGS))
            get_values.append(
                pygame.display.gl_get_attribute(pygame.GL_CONTEXT_PROFILE_MASK)
            )
            get_values.append(
                pygame.display.gl_get_attribute(pygame.GL_SHARE_WITH_CURRENT_CONTEXT)
            )
            get_values.append(
                pygame.display.gl_get_attribute(pygame.GL_FRAMEBUFFER_SRGB_CAPABLE)
            )

        # We check to see if the values that we get correspond to the values that we set
        # them to or to the original values.
        for i in range(len(original_values)):
            self.assertTrue(
                (get_values[i] == original_values[i])
                or (get_values[i] == set_values[i])
            )

        # test using non-flag argument
        with self.assertRaises(TypeError):
            pygame.display.gl_get_attribute("DUMMY")
Ejemplo n.º 47
0
#!/usr/bin/env python

from pygame import init, display, draw, time, event
from pygame.sprite import *
from pygame.locals import *

from sys import exit

i = init()
if i != (6, 0):
    raise Exception('bad pygame init')

screen = display.set_mode((640, 480))
clock = time.Clock()

############################################################
##  CLASSES
############################################################


class guy(Sprite):
    def __init__(self, x, y):
        Sprite.__init__(self)

        self.x = x
        self.y = y
        self.rect = ((x, y, 30, 30))

    def update(self):
        pass
Ejemplo n.º 48
0
    def create_levels(self):
        for map in self.maps:
            level = self.create_level(map, self.screen)
            self.append(level)

    def create_level(self, mp, screen):
        all_group = sprite.LayeredUpdates()
        level = LevelMap(mp, screen, all_group, imgset_dir=self.resource)
        if self.bg_group is not None:
            level.create_background(self.bg_group)
        level.create_map(**self.groups)
        return all_group


if __name__ == '__main__':
    import os
    from pumpkin import paths
    import pygame
    from pygame.sprite import Group
    from libs import subsprite

    init()
    screen = display.set_mode((150, 150))
    pth_map = os.path.join(paths.maps, 'map1.json')

    mp = MapParser(pth_map)
    lay = mp.level_map['layers'][0]
    prop = lay.get('properties')
    mp.print()
    print()
Ejemplo n.º 49
0
 def reset(cls):
     display.set_icon(
         image.load(os.path.join(os.getcwd(), 'data', 'favicon.png')))
     display.set_caption("WorldBuilding")
     display.set_mode((ANCHO, ALTO), SCALED)
     event.clear()
Ejemplo n.º 50
0
    display.update()  # обновляем экран


def write_record_score(score_in):
    """ Записываем новый рекорд в файл """
    if score_in['record_score'] < score_in['current_score']:
        with open('record_score.txt', 'w', encoding='utf-8') as file_obj:
            file_obj.write(str(score_in['current_score']))
            print(f"Новый рекорд {score_in['current_score']} записан в файл.")
    else:
        print("Новый рекорд не установлен - в файл ничего не записано.")


# настраиваем экран
environ['SDL_VIDEO_CENTERED'] = '1'  # выводим окно программы в центре экрана
window_surf = display.set_mode((SIZE_WINDOW, SIZE_WINDOW))
display.set_caption("Игра 'Полет в небе' © Житников Тарас")

# дополнительные настройки
mouse.set_visible(False)  # отключаем указатель мыши
game_clock = time.Clock()  # будем ограничивать кадры в секундку

# бесконечный цикл для быстрого перезапуска игр
while True:
    # в начале игры считываем рекорд из файла
    score = {
        'record_score': read_record_score(),
        'current_score': 0,
        'lives_player': MAX_LIVES_PLAYER,
        'added_lives': 0,
        'speed_game': 1
Ejemplo n.º 51
0
#from phosphene import cube
from threading import Thread
import numpy
import pyaudio

# Setup devices with their corresponding device files

devs = [
    #Waterfall("/dev/ttyACM5"),
    #DiscoBall("/dev/ttyACM8"),
    LEDWall("/dev/ttyACM0")
]

pygame.init()
surface = display.set_mode((640, 480))

import serial

data = numpy.zeros((0, 2))
sF = 44100
signal = Signal(data, sF)

signal.A = lift((data[:, 0] + data[:, 1]) / 2, True)
signal.beats = lift(lambda s: numpymap(
    lambda (a, b): 1 if a > b * 1.414 else 0, zip(s.avg8, s.longavg8)))


def initRecording(sig):
    p = pyaudio.PyAudio()
Ejemplo n.º 52
0
import pygame

from pygame import display, draw  # import them individualy so pycharm intelisence will pick them up

pygame.init()

screen_size = (600, 600)

screen = display.set_mode(screen_size)

close_game = False

pos = (0, 0)

while not close_game:

    # Event handling
    for e in pygame.event.get():

        # Quit event handling
        if e.type == pygame.QUIT:
            pygame.quit()
            break

        # Key press event handling
        if e.type == pygame.KEYDOWN:
            if e.key == pygame.K_ESCAPE:
                pygame.quit()
                break

        # Mouse moved event handling
Ejemplo n.º 53
0
CENTER = (int(DISPLAY_WIDTH / 2), int(DISPLAY_HEIGHT / 2) )

def createTextObject(font, text):
    """Erstellt ein textObject für drawer.write(x, y, textObject)
    
    Es muss ein Font angegeben werden. siehe drawer.createFont(size)"""
    return font.render(text, False, (0, 0, 0))

def createFont(size):
    return pyfont.SysFont('Arial', size)



# Fenster erstellen
DISPLAY = pydisplay.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pydisplay.set_caption("YouKnowWhat?")




def draw(drawStuff):
    """Alles malen, was in diesem Tick gemalt werden soll"""
    # Hintergrund zurücksetzen
    DISPLAY.fill((255, 240, 200))

    # Zeug malen
    for thing in drawStuff:
        thing.draw()
    
    # Texte malen
Ejemplo n.º 54
0
from pygame import display, time


# Class Coordinates for simplifiing workflow :-)
class Coordinates:
    def __init__(self, x, y):
        self.x = x
        self.y = y

# Define some variables
FPS = 60
WIDTH = int(512 * 1.5)
HEIGHT = int(512 * 1)
START_POS = Coordinates(32, 32)
screen = display.set_mode((WIDTH, HEIGHT))
clock = time.Clock()
Ejemplo n.º 55
0
class FlappyBird(object):
    init()
    fps_clock = time.Clock()
    screen_width = 288
    screen_height = 512
    screen = display.set_mode((screen_width, screen_height))
    display.set_caption('Deep Q-Network Flappy Bird')
    base_image = load('assets/sprites/base.png').convert_alpha()
    background_image = load('assets/sprites/background-black.png').convert()

    pipe_images = [rotate(load('assets/sprites/pipe-green.png').convert_alpha(), 180),
                   load('assets/sprites/pipe-green.png').convert_alpha()]
    bird_images = [load('assets/sprites/redbird-upflap.png').convert_alpha(),
                   load('assets/sprites/redbird-midflap.png').convert_alpha(),
                   load('assets/sprites/redbird-downflap.png').convert_alpha()]
    # number_images = [load('assets/sprites/{}.png'.format(i)).convert_alpha() for i in range(10)]

    bird_hitmask = [pixels_alpha(image).astype(bool) for image in bird_images]
    pipe_hitmask = [pixels_alpha(image).astype(bool) for image in pipe_images]

    fps = 30
    pipe_gap_size = 100
    pipe_velocity_x = -4

    # parameters for bird
    min_velocity_y = -8
    max_velocity_y = 10
    downward_speed = 1
    upward_speed = -9

    bird_index_generator = cycle([0, 1, 2, 1])

    def __init__(self):

        self.iter = self.bird_index = self.score = 0

        self.bird_width = self.bird_images[0].get_width()
        self.bird_height = self.bird_images[0].get_height()
        self.pipe_width = self.pipe_images[0].get_width()
        self.pipe_height = self.pipe_images[0].get_height()

        self.bird_x = int(self.screen_width / 5)
        self.bird_y = int((self.screen_height - self.bird_height) / 2)

        self.base_x = 0
        self.base_y = self.screen_height * 0.79
        self.base_shift = self.base_image.get_width() - self.background_image.get_width()

        pipes = [self.generate_pipe(), self.generate_pipe()]
        pipes[0]["x_upper"] = pipes[0]["x_lower"] = self.screen_width
        pipes[1]["x_upper"] = pipes[1]["x_lower"] = self.screen_width * 1.5
        self.pipes = pipes

        self.current_velocity_y = 0
        self.is_flapped = False

    def generate_pipe(self):
        x = self.screen_width + 10
        gap_y = randint(2, 10) * 10 + int(self.base_y / 5)
        return {"x_upper": x, "y_upper": gap_y - self.pipe_height, "x_lower": x, "y_lower": gap_y + self.pipe_gap_size}

    def is_collided(self):
        # Check if the bird touch ground
        if self.bird_height + self.bird_y + 1 >= self.base_y:
            return True
        bird_bbox = Rect(self.bird_x, self.bird_y, self.bird_width, self.bird_height)
        pipe_boxes = []
        for pipe in self.pipes:
            pipe_boxes.append(Rect(pipe["x_upper"], pipe["y_upper"], self.pipe_width, self.pipe_height))
            pipe_boxes.append(Rect(pipe["x_lower"], pipe["y_lower"], self.pipe_width, self.pipe_height))
            # Check if the bird's bounding box overlaps to the bounding box of any pipe
            if bird_bbox.collidelist(pipe_boxes) == -1:
                return False
            for i in range(2):
                cropped_bbox = bird_bbox.clip(pipe_boxes[i])
                min_x1 = cropped_bbox.x - bird_bbox.x
                min_y1 = cropped_bbox.y - bird_bbox.y
                min_x2 = cropped_bbox.x - pipe_boxes[i].x
                min_y2 = cropped_bbox.y - pipe_boxes[i].y
                if np.any(self.bird_hitmask[self.bird_index][min_x1:min_x1 + cropped_bbox.width,
                       min_y1:min_y1 + cropped_bbox.height] * self.pipe_hitmask[i][min_x2:min_x2 + cropped_bbox.width,
                                                              min_y2:min_y2 + cropped_bbox.height]):
                    return True
        return False

    def next_frame(self, action):
        pump()
        reward = 0.1
        terminal = False
        # Check input action
        if action == 1:
            self.current_velocity_y = self.upward_speed
            self.is_flapped = True

        # Update score
        bird_center_x = self.bird_x + self.bird_width / 2
        for pipe in self.pipes:
            pipe_center_x = pipe["x_upper"] + self.pipe_width / 2
            if pipe_center_x < bird_center_x < pipe_center_x + 5:
                self.score += 1
                reward = 1
                break

        # Update index and iteration
        if (self.iter + 1) % 3 == 0:
            self.bird_index = next(self.bird_index_generator)
            self.iter = 0
        self.base_x = -((-self.base_x + 100) % self.base_shift)

        # Update bird's position
        if self.current_velocity_y < self.max_velocity_y and not self.is_flapped:
            self.current_velocity_y += self.downward_speed
        if self.is_flapped:
            self.is_flapped = False
        self.bird_y += min(self.current_velocity_y, self.bird_y - self.current_velocity_y - self.bird_height)
        if self.bird_y < 0:
            self.bird_y = 0

        # Update pipes' position
        for pipe in self.pipes:
            pipe["x_upper"] += self.pipe_velocity_x
            pipe["x_lower"] += self.pipe_velocity_x
        # Update pipes
        if 0 < self.pipes[0]["x_lower"] < 5:
            self.pipes.append(self.generate_pipe())
        if self.pipes[0]["x_lower"] < -self.pipe_width:
            del self.pipes[0]
        if self.is_collided():
            terminal = True
            reward = -1
            self.__init__()

        # Draw everything
        self.screen.blit(self.background_image, (0, 0))
        self.screen.blit(self.base_image, (self.base_x, self.base_y))
        self.screen.blit(self.bird_images[self.bird_index], (self.bird_x, self.bird_y))
        for pipe in self.pipes:
            self.screen.blit(self.pipe_images[0], (pipe["x_upper"], pipe["y_upper"]))
            self.screen.blit(self.pipe_images[1], (pipe["x_lower"], pipe["y_lower"]))
        image = array3d(display.get_surface())
        display.update()
        self.fps_clock.tick(self.fps)
        return image, reward, terminal
Ejemplo n.º 56
0
"""Globals"""

button_unselected = (255, 255, 255)
not_selected_color = (0, 0, 255)
selected_color = (255, 0, 0)

selected_algorithm = ""  # used for determining which algorithm to use
start = 0  # default starting node
# add_node_mode = 0 --> adding edges
# add_node_mode = 1 --> adding nodes
# add_node_mode = 2 --> deleting nodes <-- this has been removed
# add_node_mode = 3 --> deleting edges
# add_node_mode = 4 --> select starting node
add_node_mode = 1  # differentiate between adding nodes or edges

screen = pydisplay.set_mode((1400, 800))  # display surface for graph creation
graph_screen = pygame.Rect((120, 0, 1400, 800))
font = pygame.font.Font(None, 28)  # font to use

# used to add edges
primary = -1
secondary = -1
node_name = 0  # used to name nodes


class Node:
    """
    Class to represent nodes

    Attributes
    ----------
Ejemplo n.º 57
0
    def __init__(self):
        parser = OptionParser(
            usage="Usage: %prog [OPTIONS] [HOST]",
            version="NATOcubes 0.5",
            epilog=
            "If HOST is not specified, the game will start in local mode. Otherwise it will start in client mode, with HOST as server."
        )
        parser.add_option('-s',
                          '--server',
                          action="store_true",
                          dest="server",
                          default=False,
                          help="server mode")
        parser.add_option(
            '-p',
            '--port',
            type="int",
            dest="port",
            default=12345,
            help="set port (client & server mode) [default: %default]")
        parser.add_option(
            '-x',
            type="int",
            dest="x",
            default=5,
            help="field width (server & local mode) [default: %default]")
        parser.add_option(
            '-y',
            type="int",
            dest="y",
            default=5,
            help="field height (server & local mode) [default: %default]")
        parser.add_option('-z',
                          '--size',
                          type="int",
                          dest="size",
                          default=75,
                          help="size of one field [default: %default]")
        parser.add_option(
            '-l',
            '--player',
            type="int",
            dest="numplayers",
            default=2,
            help="number of players (local mode) [default: %default]")
        options, args = parser.parse_args()

        self.xsize, self.ysize, self.fieldsize = options.x, options.y, options.size

        if options.server:
            self.handler = server('', options.port, options.x, options.y)
        else:
            if len(args) > 0:
                self.handler = client(args[0], options.port)
                self.xsize, self.ysize = self.handler.getsize()
            else:
                self.handler = local(options.numplayers)

        self.player, self.localplayer, self.numplayers = self.handler.getopts()
        self.counts = []

        self.f = Field(self.xsize, self.ysize, self.fieldsize)
        display.set_mode(((self.xsize * (self.fieldsize + 1) - 1),
                          18 + (self.ysize * (self.fieldsize + 1) - 1)))
        display.set_caption('NATOcubes')
        surf = self.f.render()
        self.handler.surface(surf, self.player, self.fieldsize)
        display.get_surface().blit(surf, (0, 0))
        display.update()

        ev = event.wait()
        while ev.type != QUIT:
            event.clear()
            display.update()
            if self.player == self.localplayer or self.localplayer == -1:
                ev = event.wait()
                if ev.type == MOUSEBUTTONDOWN:
                    px, py = ev.pos
                    x = px / (self.fieldsize + 1)
                    y = (py - 18) / (self.fieldsize + 1)
                    if self.f.turn(self.player, x, y):
                        self.handler.onTurn(x, y)
                        surf = self.f.render(x, y)
                        self.handler.surface(surf, self.newplayer(),
                                             self.fieldsize)
                        display.get_surface().blit(surf, (0, 0))
                        display.update()
                        if self.after_turn():
                            return
            else:
                recv = self.handler.recv_data()
                if recv and len(recv) == 2:
                    x = ord(recv[0])
                    y = ord(recv[1])
                    if self.f.turn(self.player, x, y):
                        self.handler.distribute_data(x, y)
                        surf = self.f.render(x, y)
                        self.handler.surface(surf, self.newplayer(),
                                             self.fieldsize)
                        display.get_surface().blit(surf, (0, 0))
                        display.update()
                        if self.after_turn():
                            return
                    else:
                        self.handler.failed_turn()
                elif recv == '\x00':
                    s = smallfont.render('Lost Connection', True,
                                         Color('#FFFFFF'), Color('#000000'))
                    sw, sh = s.get_size()
                    display.get_surface().blit(
                        s, (((self.xsize * self.fieldsize) - sw) / 2,
                            ((self.ysize * self.fieldsize) - sh) / 2 + 18))
                    display.update()
                    while event.wait().type != QUIT:
                        pass
                    return
                else:
                    sleep(0.1)
                ev = event.poll()
 def SetNewResolution(self, resolution):
     self.Resolution = resolution
     self.Window = display.set_mode(self.Resolution)
     return
Ejemplo n.º 59
0
import pygame
import gameConfig as gc

from pygame import display, event, image
from animal import Animal
from time import sleep
pygame.init()

def find_index(x, y):
    row = y // gc.imageSize
    col = x // gc.imageSize
    index = row * gc.numTilesSide + col
    return index

display.set_caption("Card Matcher")
screen= display.set_mode((512,512))
matched = image.load('other_assets/matched.png')
#screen.blit(matched, (0,0))
#display.flip()
running= True
tiles =[Animal(i) for i in range(0, gc.numTilesTotal)]
currentImages = []
while running:
    current_events= event.get()
    for e in current_events:
        if e.type == pygame.QUIT:
            running= False
        if e.type == pygame.KEYDOWN:
            if e.key == pygame.K_ESCAPE:
                running=False
        if e.type == pygame.MOUSEBUTTONDOWN:
Ejemplo n.º 60
0
import pygame
import game_config as gc
from pygame import display, event, image
from time import sleep
from animal import Animal


def find_index_from_xy(x, y):
    row = y // gc.IMAGE_SIZE
    col = x // gc.IMAGE_SIZE
    index = row * gc.NUM_TILES_SIDE + col
    return row, col, index


display.set_caption('My Game')
screen = display.set_mode((gc.SCREEN_SIZE, gc.SCREEN_SIZE))
matched = image.load('other_assets/matched.png')
running = True
tiles = [Animal(i) for i in range(0, gc.NUM_TILES_TOTAL)]
current_images_displayed = []

while running:
    current_events = event.get()

    for e in current_events:
        if e.type == pygame.QUIT:
            running = False

        if e.type == pygame.KEYDOWN:
            if e.key == pygame.K_ESCAPE:
                running = False