示例#1
0
def main():
    moons = [Moon(pos) for pos in d12_input]
    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
    glutInitWindowSize(800, 800)
    glutInitWindowPosition(350, 200)
    glutCreateWindow('name')
    glClearColor(0., 0., 0., 1.)
    glShadeModel(GL_SMOOTH)
    glEnable(GL_CULL_FACE)
    glEnable(GL_DEPTH_TEST)
    glEnable(GL_LIGHTING)
    lightZeroPosition = [10., 4., 10., 1.]
    lightZeroColor = [0.8, 1.0, 0.8, 1.0]
    glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition)
    glLightfv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor)
    glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1)
    glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05)
    glEnable(GL_LIGHT0)
    glutDisplayFunc(lambda: display_scene(moons))
    glutTimerFunc(0, timer, 0)
    glMatrixMode(GL_PROJECTION)
    gluPerspective(40., 1., 1., 40.)
    glMatrixMode(GL_MODELVIEW)
    gluLookAt(0, -10, 10, 0, 0, 0, 0, 1, 0)
    glPushMatrix()
    glutMainLoop()
    def __init__(self, engine):
	"""
	The game determines what is happening on screen
	based on what state the GameEngine instance has.
	"""
	# the game engine that owns this state
	self.engine = engine # TRYING TO DEPRECATE
	self.screen = Screen()
	self.res = self.engine.setsMgr.screenRes
	res = self.res

	# get/load the font
	self.font = FontManager().loadFont( 'JohnDoe' )
	self.str_paused = UIText( "Paused", [res[0]*0.5, res[1]*0.5]
				, self.font, 35 )
	self.str_paused.setVisible(False)

	
	gameWorld = self.engine.gameWorld
	#gameWorld.setPlayerType( 'Cop' )
	gameWorld.setPlayerType( 'Robber' )
	#gameWorld.getPlayer().setName( "Alfonso" )

	# This is an optimization...
	# If using the Cop player type, use the smaller tiles
	if gameWorld.getPlayer().getType() == "Cop":
	    gameWorld.setLevelByName( 'Level1XS' )
	else:
	    gameWorld.setLevelByName( 'Level1L' )

	glutTimerFunc(50, self.engine.on_update, 50)
示例#3
0
    def calc_movement_all_shapes(self, _):
        #Snake logic, best logic
        self.snake_instance.game_tick()

        #Reset our timer
        glutTimerFunc(TICKRATE_MS, self.calc_movement_all_shapes, 0)

        #Tell glut to rerun our display function
        glutPostRedisplay()
示例#4
0
def main():
    #Load up the local settings
    game_settings = load_settings()
    #Network starts first since it gives us many of the parameters we need to initialize our game grid.
    network = MasterNetworkMode(game_settings)
    network.startNetwork()

    #Client-side game related stuffs below
    #This function will wait until the network thread either connects or times out
    #This really shouldn't take more than a few hundred milliseconds at worst on a local connection

    game_grid_params = network.getParameters()
    if game_grid_params is None:  #YOU DUN GOOFED UP NOW
        print "Failed to initialize network thread. Quitting..."
        exit(1)
    '''
    if game_settings["net_mode"] == "ClientMode":
        print "Client recv params:"
        print game_grid_params
    '''

    #Update our globals
    update_params(game_grid_params)
    #Get our player init data from the client thread.
    init_player_data = network.getInitPlayerData()
    client_connection_id = network.getConnectionID()
    #initilize our game grid and SnakeManager objects using the data gathered above.
    snakepit = SnakeManager(client_connection_id, init_player_data)
    Game_Grid = Grid(snakepit, game_grid_params["GRID_SIDE_SIZE_PX"],
                     game_grid_params["WINDOW_SIZE"])

    #Update our network side with the SnakeManager and Grid references
    network.setSnakeReference(snakepit)
    network.setGridReference(Game_Grid)

    #class to handle the drawing of our various elements
    #This has turned into more of a driver class for everything.
    renderman = RenderManager(Game_Grid)

    #Gl/Glut stuffs below
    glinit("PyGLSnake-Multiplayer :: Connection ID: %s" % client_connection_id)
    glutSpecialFunc(snakepit.keypressCallbackGLUT)
    #glutDisplayFunc is the main callback function opengl calls when GLUT determines that the display must be redrawn
    glutDisplayFunc(renderman.render_all_shapes)

    glutTimerFunc(TICKRATE_MS, renderman.calc_movement_all_shapes, 0)

    #Might want to get rid of this unless we plan to run it through the komodo profiler
    glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION)
    #Start everything up
    glutMainLoop()
示例#5
0
    def connect(self):
	# Make a socket and set it up to look for the display wall
	self.channel = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

	if not self.connected:# or not self.gameStarted :
	    try:
		self.channel.connect((self.host, self.port))
		self.connected = True
	    except (socket.error, socket.herror):
		print "client - Connection attempt to server failed."
		self.connected = False
		return False

	    #time.sleep(2)

	    if self.serverOwner:
		# send some initialization data to the server
		packet = {  'type' : 'message'
			, 'SetOwner' : None
			, 'MaxPlayers' : 5
			, 'ServerName' : self.serverName }
		
		sendData( self.channel, packet )
	    else:
		print 'client - not the server owner'

	    if self.connected:
		# start the socket event
		glutTimerFunc(20, self.on_socket, 20)
		print 'client - connected'

	if not self.gameWorld.getLevel(): 
	    ready_to_read, ready_to_write, in_error = select.select(
		    [self.channel], [self.channel], [self.channel], 0)

	    if self.channel in in_error:
		self.disconnect()

	    # create a request for the current level
	    packet = { 'type':'message', 'GetLevel':None }

	    if self.channel in ready_to_write:
		sendData( self.channel, packet )
		#print 'client - sent a packet'

	return True
示例#6
0
    def animate(self, FPS=30):

        currentTime = time()

        #key movement for omnicontrol
        try:
            if self.keys["x"]: self.cam_focus.x += 1
            if self.keys["z"]: self.cam_focus.x -= 1
            if self.keys["d"]: self.cam_focus.y += 1
            if self.keys["c"]: self.cam_focus.y -= 1
            if self.keys["f"]: self.cam_focus.z += 1
            if self.keys["v"]: self.cam_focus.z -= 1
        except:
            pass

        # run calculations for level inc collision etc
        if not self.level == None:
            self.level.evaluate(self.joystick, self.keys)

        glutPostRedisplay()

        glutTimerFunc(int(1000 / FPS), self.animate, FPS)

        drawTime = currentTime - self.lastFrameTime

        self.topFPS = int(1000 / drawTime)

        # set camera target focus points
        self.cam_focus_target = XYZ(
            self.level.solomon.x + 0.2 * self.level.solomon.facing,
            self.level.solomon.y - 0.5, 3.0)

        # set camera target position
        self.cam_pos_target = XYZ(
            self.level.solomon.x + 1 * self.level.solomon.facing,
            self.level.solomon.y - 0.2, float(self.level.target_z))

        # calculate current focal point and camera position
        # self.camera_sweep is the "speed" at which transitions are being made
        self.cam_pos = self.cam_pos.add(
            self.cam_pos_target.sub(self.cam_pos).mult(1 / self.camera_sweep))
        self.cam_focus = self.cam_focus.add(
            self.cam_focus_target.sub(self.cam_focus).mult(1 /
                                                           self.camera_sweep))
        self.lastFrameTime = time()
示例#7
0
    def checkQueue(self, unused_timer_id):
        glutTimerFunc(20, self.checkQueue, 0)

        # if True: # spinning
        #     w_whole_window = glutGet(GLUT_WINDOW_WIDTH)
        #     h_whole_window = glutGet(GLUT_WINDOW_HEIGHT)
        #     center_x = w_whole_window/2
        #     center_y = h_whole_window/2
        #     self.on_click(GLUT_LEFT_BUTTON, GLUT_DOWN, center_x, center_y)
        #     self.on_drag(center_x+2, center_y)

        try:
            request = self.server.recv_pyobj(zmq.NOBLOCK)
        except zmq.ZMQError as e:
            if e.errno != zmq.EAGAIN:
                raise  # something wrong besides empty queue
            return  # empty queue, no problem

        if not request:
            return

        while (request):
            task_completion_time = time.time()
            if not self.handle_request(request):
                raise Exception('Unknown command string: %s' %
                                (request['label']))
            task_completion_time = time.time() - task_completion_time

            if 'port' in request:  # caller wants confirmation
                port = request['port']
                client = zmq.Context.instance().socket(zmq.PUSH)
                client.connect('tcp://127.0.0.1:%d' % (port))
                client.send_pyobj(task_completion_time)
            try:
                request = self.server.recv_pyobj(zmq.NOBLOCK)
            except zmq.ZMQError as e:
                if e.errno != zmq.EAGAIN:
                    raise
                request = None

        if self.need_redraw:
            glutPostRedisplay()
示例#8
0
    def activate(self, width, height):
        glutInit(['mesh_viewer'])
        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH)
        glutInitWindowSize(width, height)
        glutInitWindowPosition(0, 0)
        self.root_window_id = glutCreateWindow(self.titlebar)
        glutDisplayFunc(self.on_draw)

        glutTimerFunc(100, self.checkQueue, 0)
        glutReshapeFunc(self.on_resize_window)

        glutKeyboardFunc(self.on_keypress)
        glutMouseFunc(self.on_click)
        glutMotionFunc(self.on_drag)

        # for r, lst in enumerate(self.mesh_viewers):
        #     for c, mv in enumerate(lst):
        #         mv.glut_window_id = glutCreateSubWindow(self.root_window_id, c*width/len(lst), r*height/len(self.mesh_viewers), width/len(lst), height/len(self.mesh_viewers))

        glutDisplayFunc(self.on_draw)
        self.init_opengl()

        glutMainLoop()  # won't return until process is killed
示例#9
0
def main():
    init()

    Game_Grid = Grid()

    snake = Snake(Game_Grid)

    #I didnt really want to use GLUT much but eh, I will work this out with standard libraries  later
    glutSpecialFunc(snake.keypress_callback_GLUT)

    renderman = RenderManager(Game_Grid, snake)
    glutDisplayFunc(renderman.render_all_shapes)

    glutTimerFunc(TICKRATE_MS, renderman.calc_movement_all_shapes, 0)

    #Tell Glut to continue execution after we exit the main loop
    #Komodo's code profiler will not return any results unless you shut down just right
    glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION)

    #set vsync
    swap_control.wglSwapIntervalEXT(VSYNC)

    #Start everything up
    glutMainLoop()
    def update( self, elapsed ):
	"""
	Call the update function of all objects in the gameworld.
	"""

	# don't update if the gameworld is inactive
	if not self.active:
	    # either the game is paused or the game hasn't started yet
	    return

	# update the controller
	#   (as it might be necessary depending on the type)
	self.controller.update(elapsed)

	# Update collisions first(to hopefully achieve greater accuracy)
	for coll in self.collisions.values():
	    coll.update(elapsed)

	# send the elapsed time to the player (for whatever it needs to do)
	if self.player:
	    # update the player animation
	    self.player.update(elapsed)

	self.ensureWithinLevel()

	# update the screen pos based on the character 
	#   pos and facing direction
	self.scrollScreen()

	if self.level:
	    # update the level
	    self.level.update(elapsed)

	# update the peer avatars
	for peer in self.peers.values():
	    peer.update(elapsed)

	# all world objects
	for obj in self.objects:
	    obj.update(elapsed)

	#/\/\/\# Collision #/\/\/\#
	# copy the old collisions to another list
	self.prevCols = dict(self.collisions)
	self.collisions = {}
	## Player-to-Level
	if self.player.getType() == "Robber":

	    tileType, offset = self.level.getTileAtPoint(self.player.pos)

	    if not tileType:
		pass

	    elif tileType == 'base':
		self.addCollision(Collision.ROBBER, Collision.BASE)

	    elif tileType == 'building':
		posAdjust = [0,0]

		if offset[0] < self.level.tileHalfSize[0]:
		    posAdjust[0] = offset[0] * -1
		elif offset[0] >= self.level.tileHalfSize[0]:
		    posAdjust[0] = (self.level.tileScrSize[0]-offset[0])
		    
		if offset[1] < self.level.tileHalfSize[1]:
		    posAdjust[1] = offset[1] * -1
		elif offset[1] >= self.level.tileHalfSize[1]:
		    posAdjust[1] = (self.level.tileScrSize[1]-offset[1])

		self.player.pos[0] += posAdjust[0]
		self.player.pos[1] += posAdjust[1]

	    elif tileType == 'drop-point':
		self.addCollision(Collision.ROBBER, Collision.DROP_POINT)

	
	for peer in self.peers.values():
	    # player's of the same type do not collide (for now)
	    if peer.getType() != self.player.getType():
		if self.player.getType() == "Cop":
		    # collide the peer(a robber) with the player's spotlight
		    if self.player.collidePoint( peer.pos  ):
			self.addCollision( Collision.ROBBER, Collision.COP )

		elif self.player.getType() == "Robber":
		    # collide the peer's spotlight with the player(a robber)
		    if peer.collidePoint( self.player.pos ):
			self.addCollision( Collision.ROBBER, Collision.COP )
		    
	# This is not in use for now #	
	## Player-to-Objects
	#for obj in self.objects:
	#    #collide the object box with the robber pos only
	#    if self.player.getType() == "Robber":
	#	print 'object'

	
	#/\/\/\# Collision Response #/\/\/\#

	cop_robber_coll = False
	try:
	    # First, determine if there is a cop-to-robber collision as
	    #   this will be relevant to the effect of other collisions
	    # This collision depends on the player type
	    if self.collisions[(Collision.ROBBER, Collision.COP)].getTime() > 3000:
		if self.player.getType() == "Robber":
		    #self.cops_got_ya.setPos(\
		    #	    ( self.player.pos[0], self.player.pos[1]+10 ) )
		    self.cops_got_ya.setVisible(True)
		    glutTimerFunc( 2000, self.cops_got_ya.toggleVisible, 0 )
		    self.gameStatus = "loser"

		elif self.player.getType() == "Cop":
		    #self.robber_detained.setPos(\
		    #	    ( self.player.pos[0], self.player.pos[1]+10 ))
		    self.robber_detained.setVisible(True)
		    glutTimerFunc( 2000, self.robber_detained.toggleVisible, 0 )
		    self.gameStatus = "winner"
		self.active = True
	except KeyError:
	    # the collision is not present (saved myself a few 'if'-stmts, above)
	    pass

	try:
	    # We can assume the next two can only occur when the player is a "Robber"
	    if (Collision.ROBBER, Collision.DROP_POINT) in self.collisions:
		if cop_robber_coll == True:
		    #self.lose_the_cops.setPos(\
		    #	    (self.player.pos[0], self.player.pos[1]+10) )
		    self.lose_the_cops.setVisible(True)
		    glutTimerFunc( 2000, self.lose_the_cops.toggleVisible, 0 )
		#elif self.drop_point_hit == True:
		#    #self.go_to_base.centerAround( self.player.pos )
		#    self.go_to_base.setVisible(True)
		#    glutTimerFunc( 2000, self.go_to_base.toggleVisible, 0 )

		elif self.collisions[(Collision.ROBBER, Collision.DROP_POINT)].getTime() > 3000:
		    self.drop_point_hit = True
		    #self.dropped_loot.setPos(\
		    #	    ( self.player.pos[0], self.player.pos[1]+10 ))
		    self.dropped_loot.setVisible(True)
		    glutTimerFunc( 2000, self.dropped_loot.toggleVisible, 0 )

	except KeyError:
	    # the collision is not present (saved myself a few 'if'-stmts, above)
	    pass

	try:
	    if (Collision.ROBBER, Collision.BASE) in self.collisions:
		if cop_robber_coll == True:
		    #self.lose_the_cops.setPos(\
		    #	    ( self.player.pos[0], self.player.pos[1]+10 ))
		    self.lose_the_cops.setVisible(True)
		    glutTimerFunc( 2000, self.lose_the_cops.toggleVisible, 0 )
		elif self.drop_point_hit == False:
		    self.go_to_drop.setVisible(True)
		    glutTimerFunc( 2000, self.go_to_drop.toggleVisible, 0 )

		elif self.collisions[(Collision.ROBBER, Collision.BASE)].getTime() > 3000:
		    self.gameStatus = "winner"
		    self.active = False
		    #self.safe_at_base.setPos(\
		    #	    ( self.player.pos[0], self.player.pos[1]+10 ))
		    self.safe_at_base.setVisible(True)
		    glutTimerFunc( 2000, self.safe_at_base.toggleVisible, 0 )
	except KeyError:
	    # the collision is not present (saved myself a few 'if'-stmts, above)
	    pass
示例#11
0
 def playback(value=1):
     global v
     v.loadNextModel()
     glutTimerFunc(100, KeyboardInteractor.playback, value + 1)
示例#12
0
def timer(extra):
    glutPostRedisplay()
    glutTimerFunc(120, timer, 0)
示例#13
0
 def _update(self, value):
     self.func(self.window, self, None) # TODO: timers reference
     glutTimerFunc(self.interval_in_ms, self._update, 0)