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)
    def __init__(self, engine):
	"""
	The game determines what is happening on screen
	based on what state the GameEngine instance has.
	"""
	self.engine = engine

	self.screen = Screen()
	self.res = self.engine.setsMgr.screenRes
	res = self.res # saying 'self.res' was making lines too long. :P
	
	# get/load the font
	self.font = FontManager().loadFont( 'Basic' )

	# screen objects
	self.UI = {}
	self.UI['title'] = UIText("Breakin And Poppin"\
		, pos=[res[0]*.01,res[1]*.10], font=self.font, scale=0.05)
	self.UI['start_server'] = UIText("Start a Server"\
		, pos=[res[0]*0.5, res[1]*0.42], font=self.font, scale=0.04)
	self.UI['start_server'].center()
	self.UI['join_server'] = UIText("Join a Server"\
		, pos=[res[0]*0.5, res[1]*0.5], font=self.font, scale=0.04)
	self.UI['join_server'].center()
	self.UI['quit'] = UIText("Quit"\
		, pos=[res[0]*0.5, res[1]*0.58], font=self.font, scale=0.04)
	self.UI['quit'].center()
	self.titleBGImg = UIImage("TitleScreenBG.png"\
		, pos=[0,0], size=res)

	self.selected = 'start_server'
Esempio n. 3
0
def Main():
  """Runs once the user has entered the application."""

  pygame = SystemState.pygame
  while SystemState.application == 'camera':
    Events.CheckEvents()
    if SystemState.screen_mode in (1, 2, 5, 6):
      SystemState.CameraState.camera_stream = True
    else:
      SystemState.CameraState.camera_stream = False

    if SystemState.CameraState.camera_stream == True:
      # Button on RPi.GPIO 8
      if not RPi.GPIO.input(8):
        CallTakePhoto()

      SystemState.CameraState.stream = io.BytesIO() # Capture into in-memory stream
      SystemState.camera.capture(SystemState.CameraState.stream, use_video_port=True, splitter_port=0, format='rgb')
      SystemState.CameraState.stream.seek(0)
      SystemState.CameraState.stream.readinto(SystemState.rgb)  # stream -> YUV buffer
      SystemState.CameraState.stream.close()
      SystemState.img = SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320 * 240 * 3)], (320, 240), 'RGB' )
      xa = (320 - SystemState.img.get_width() ) / 2
      ya = (240 - SystemState.img.get_height()) / 2
      Screen.RefreshScreen(image=SystemState.img, wx=xa, wy=ya)
    def renderFrame(self):
	""" RenderFrame - Base Class """
	if not self.screen:
	    self.screen = Screen()

	self.screen.drawThis( self.str_paused )

	return self
    def scrollScreen(self):
	
	dir = self.player.facingDir
	#playerPos = list(self.player.getCenterPos())
	playerPos = list(self.player.pos)

	if not self.screen:
	    self.screen = Screen()

	screenRes = self.screen.size

	# the extent from the side-buffer(above)
	scrExtent = ( self.scrScroll[0] + screenRes[0]
		    , self.scrScroll[1] + screenRes[1] )

	# The current screen scroll + the side buffer offset
	#   and the size 
	# The order of the "walls" indicated within are
	#   West, North, East, South
	scrEdge = ( self.scrScroll[0] + self.sideBuf[0]
		    , self.scrScroll[1] + self.sideBuf[1]
		    , scrExtent[0] - self.sideBuf[0]
		    , scrExtent[1] - self.sideBuf[1] )

	# the screen movement based on its current position
	offset = [0,0]

	# Horizontal, player is within the area
	if playerPos[0] > scrEdge[0] and dir[0] > 0:
	    if abs(playerPos[0] - scrEdge[0]) >= self.scrSpeed[0]:
		offset[0] = self.scrSpeed[0]
	    else:
		offset[0] = int(playerPos[0] - scrEdge[0])

	if playerPos[0] < scrEdge[2] and dir[0] < 0:
	    if abs(playerPos[0] - scrEdge[2]) >= self.scrSpeed[0]:
		offset[0] = -self.scrSpeed[0]
	    else:
		# ..subtracted in this order, (pos - scrEdge) is already negative..
		offset[0] = int(playerPos[0] - scrEdge[2])

	# Vertical
	if playerPos[1] > scrEdge[1] and dir[1] > 0:
	    if abs(playerPos[1] - scrEdge[1]) >= self.scrSpeed[1]:
		offset[1] = self.scrSpeed[1]
	    else:
		offset[1] = int(playerPos[1] - scrEdge[1])

	if playerPos[1] < scrEdge[3] and dir[1] < 0:
	    if abs(playerPos[1] - scrEdge[3]) >= self.scrSpeed[1]:
		offset[1] = -self.scrSpeed[1]
	    else:
		offset[1] = int(playerPos[1] - scrEdge[3])

	
	# move the screen by the ofset
	self.moveScreen( offset )
    def renderFrame(self):
	""" RenderFrame - Base Class """
	if not self.screen:
	    self.screen = Screen()

	scrSize = self.screen.getSize()
	#self.engine.gameWorld.positionPlayer( [scrSize[0],scrSize[1]] )

	self.screen.drawThis( self.str_paused )
	
	return self
Esempio n. 7
0
def Main():
  """Main loop for the camera application."""
  pygame = SystemState.pygame
  SystemState.camera.resolution = (320, 240)
  
  while SystemState.application == 'video':
    # Check for button presses, messages, and which mode we're in.
    Events.CheckEvents()
    if SystemState.screen_mode in (1, 2, 3):
      SystemState.VideoState.video_stream = True
    else:
      SystemState.VideoState.video_stream = False
    try:
      video_message_queue = SystemState.VideoState.video_message_queue.get(None)
    except Queue.Empty:
      video_message_queue = None
    
    # Checking video message queue for record messages.
    if video_message_queue != None:
      recording_state = video_message_queue.get('recording')
      if recording_state == True:
        timestamp = str(int(time.time()))
        __CallRecordAudio(timestamp)
        __CallRecordVideo(timestamp)
        SystemState.VideoState.video_recording = True
      elif recording_state == False:
        SystemState.VideoState.video_recording = False
        TextWriter.ClearPermatext()
    
    # Checking the gpio button that starts recording.
    if SystemState.VideoState.video_recording == False:
      if not RPi.GPIO.input(8) and SystemState.screen_mode == 1:
        SystemState.VideoState.video_message_queue.put({'recording': True})
        Menu.JumpTo(screen_mode=6)
        TextWriter.Write(
          text='Rec', 
          position=(10, 10), 
          color=(255,0,0), 
          permatext=True,
          state=SystemState, 
          size=20
        ) 
    
    # Check if we are in a streaming mode. If so, throw frames at the screen.
    if SystemState.VideoState.video_stream == True:
      SystemState.VideoState.stream = io.BytesIO() # Capture into in-memory stream
      SystemState.camera.capture(SystemState.VideoState.stream, use_video_port=True, splitter_port=0, format='rgb')
      SystemState.VideoState.stream.seek(0)
      SystemState.VideoState.stream.readinto(SystemState.rgb)  
      SystemState.VideoState.stream.close()
      SystemState.VideoState.img = SystemState.pygame.image.frombuffer(SystemState.rgb[0: (320 * 240 * 3)], (320, 240), 'RGB' )
      xa = (320 - SystemState.VideoState.img.get_width() ) / 2
      ya = (240 - SystemState.VideoState.img.get_height()) / 2
      Screen.RefreshScreen(image=SystemState.VideoState.img, wx=xa, wy=ya)
    def renderFrame(self):
	if not self.screen:
	    self.screen = Screen()

	self.screen.drawThis( self.titleBGImg )

	selectionBox = UIImage("box.png",
				pos=self.UI[self.selected].pos,
				size=[(self.res[0]*0.05)*10, self.res[1]*0.05])
	selectionBox.center()
	self.screen.drawThis( selectionBox )

	for uiObj in self.UI.values():
	    # draw the background image firstly
	    self.screen.drawThis( uiObj )

	return self
    def renderFrame(self):
	""" RenderFrame - Base Class """
	
	if not self.screen:
	    self.screen = Screen()

	self.screen.drawThis( self.titleBGImg )
	self.screen.drawThis( self.UI['nice_work'] )

	if self.engine.gameWorld.getPlayerType() == "Robber":
	    self.screen.drawThis( self.UI['robber_wins'] )
	elif self.engine.gameWorld.getPlayerType() == "Cop":
	    self.screen.drawThis( self.UI['cop_wins'] )

	self.screen.drawThis( self.UI['press_esc'] )

	return self
Esempio n. 10
0
    def moveScreen( self, offset=[0,0] ):
	"""
	Moves the screen in world coords offset from its current
	position.
	"""
	if not self.screen:
	    self.screen = Screen()
	
	# validate the upper and left extent
	self.scrScroll[0] = max( self.scrScroll[0]+offset[0], 0 )
	self.scrScroll[1] = max( self.scrScroll[1]+offset[1], 0 )

	tileSize = self.level.tileScrSize
	scrSize = self.screen.size
	mapSize = self.level.mapSize

	self.scrScroll[0] = min( self.scrScroll[0]
				, (mapSize[0]*tileSize[0]) - scrSize[0] )
	self.scrScroll[1] = min( self.scrScroll[1]
			    , (mapSize[1]*tileSize[1]) - scrSize[1] )
    def __init__(self):
	"""
	Initializes the game client
	"""
    
	# since our game client is a client...
	Client.__init__(self)

	self.setsMgr = SettingsManager()
	self.res = self.setsMgr.screenRes

	self._InitGLUT_()
	self._InitGL_()

	# Make a screen object - we want to make the first here
	#   so that we can ensure the size is set appropriately.
	#   All other objects using the screen-singleton will assume
	#   it is has already been sized and, thus, won't call setSize.
	self.screen = Screen()
	self.screen.setSize( self.res )

	# be the first entity to create the managers
	self.rsrcMgr = TextureManager()
	self.fontMgr = FontManager()

	self.connected = False
	self.serverOwner = False
	self.serverName = "default"

	# the gameworld is mostly undefined at this point
	self.gameWorld = GameWorld()
	
	# this variable denotes for certain game states whether
	#   the user 'start'-ed or 'join'-ed a server so they know
	#   which state to return to when the user pushes 'back'
	self.statePath = None
	# create the initial game state
	self.gState = TitleScreenState(self)
Esempio n. 12
0
    def __init__(self):
	"""
	Init: (self)
	"""

	# grab the settings manager cause we need it here
	self.setsMgr = SettingsManager()

	# all things in the world scene (except the level and the player)
	self.objects = []
	self.collisions = {}
	self.prevCols = {}
	# store this separately so we know where it is
	self.levelName = ""
	self.level = PreBuiltLevel()
	# the user's player object
	self.player = None
	# the peer players on other computers in the network
	self.peers = {}
	# the player's controller (set to settings-default)
	self.controller = None
	self.setControllerType( self.setsMgr.controller )

	# the screen object
	self.screen = Screen()
	# the screen's position in world space
	self.scrScroll = [0,0]
	self.scrSize = self.screen.getSize()
	scrMiddle = (self.scrSize[0]/2, self.scrSize[1]/2)
	#self.sideBuf = ( self.scrSize[0]*0.4, self.scrSize[1]*0.4 )
	self.sideBuf = ( 100, 100 )
	# the max deviation that the player 
	self.maxDevi = ( self.scrSize[0]/2 - self.sideBuf[0]
			, self.scrSize[1]/2 - self.sideBuf[1] )
	self.scrSpeed = (0,0)

	self.status = "undecided"

	self.active = False # This is the 'pause' flag.
	self.gameTime = 0.0
	self.gameStatus = 'unresolved'
	# Denotes whether the Robber has touched the drop point
	self.drop_point_hit = False	# for the 'Robber' only

	# A few messages for indicating to the user
	# get/load the font
	self.font = FontManager().loadFont( 'Basic' )

	# a text objects for der screenzimmer
	self.txtObjs = []   # this will make rendering easy
	self.cops_got_ya = UIText("The Cops got ya!!",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.cops_got_ya )

	self.robber_detained = UIText("The Robber has been detained.",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.robber_detained )

	self.lose_the_cops = UIText("Ya gotta lose the cops first!",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.lose_the_cops )

	self.go_to_base = UIText("Ya already dropped off the loot.",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.go_to_base )

	self.go_to_drop = UIText("Go to the Drop Point first.",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.go_to_drop )

	self.safe_at_base = UIText("Ya made it!  Great job.",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.safe_at_base )

	self.dropped_loot = UIText("Good, now head to the Base",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.dropped_loot )

	self.robber_eluded = UIText("The robber eluded us.",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.robber_eluded )

	for txtObj in self.txtObjs:
	    txtObj.setVisible( False )
	    txtObj.center()
Esempio n. 13
0
class GameWorld():
    """
    A class to encapsulate all objects in the world-space of the 'game'.
    """

    def __init__(self):
	"""
	Init: (self)
	"""

	# grab the settings manager cause we need it here
	self.setsMgr = SettingsManager()

	# all things in the world scene (except the level and the player)
	self.objects = []
	self.collisions = {}
	self.prevCols = {}
	# store this separately so we know where it is
	self.levelName = ""
	self.level = PreBuiltLevel()
	# the user's player object
	self.player = None
	# the peer players on other computers in the network
	self.peers = {}
	# the player's controller (set to settings-default)
	self.controller = None
	self.setControllerType( self.setsMgr.controller )

	# the screen object
	self.screen = Screen()
	# the screen's position in world space
	self.scrScroll = [0,0]
	self.scrSize = self.screen.getSize()
	scrMiddle = (self.scrSize[0]/2, self.scrSize[1]/2)
	#self.sideBuf = ( self.scrSize[0]*0.4, self.scrSize[1]*0.4 )
	self.sideBuf = ( 100, 100 )
	# the max deviation that the player 
	self.maxDevi = ( self.scrSize[0]/2 - self.sideBuf[0]
			, self.scrSize[1]/2 - self.sideBuf[1] )
	self.scrSpeed = (0,0)

	self.status = "undecided"

	self.active = False # This is the 'pause' flag.
	self.gameTime = 0.0
	self.gameStatus = 'unresolved'
	# Denotes whether the Robber has touched the drop point
	self.drop_point_hit = False	# for the 'Robber' only

	# A few messages for indicating to the user
	# get/load the font
	self.font = FontManager().loadFont( 'Basic' )

	# a text objects for der screenzimmer
	self.txtObjs = []   # this will make rendering easy
	self.cops_got_ya = UIText("The Cops got ya!!",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.cops_got_ya )

	self.robber_detained = UIText("The Robber has been detained.",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.robber_detained )

	self.lose_the_cops = UIText("Ya gotta lose the cops first!",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.lose_the_cops )

	self.go_to_base = UIText("Ya already dropped off the loot.",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.go_to_base )

	self.go_to_drop = UIText("Go to the Drop Point first.",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.go_to_drop )

	self.safe_at_base = UIText("Ya made it!  Great job.",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.safe_at_base )

	self.dropped_loot = UIText("Good, now head to the Base",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.dropped_loot )

	self.robber_eluded = UIText("The robber eluded us.",
		pos=scrMiddle, font=self.font, scale=0.025)
	self.txtObjs.append( self.robber_eluded )

	for txtObj in self.txtObjs:
	    txtObj.setVisible( False )
	    txtObj.center()


    #\\\\\\\\\\\\\\\\\\\\\\\\\\#
    # World control
    def pause(self):
	"""
	Pause/Unpause the gameworld
	"""
	if self.active == True:
	    self.active = False
	else:
	    self.active = True
	return self.active



    def startGame(self):
	"""
	Explicitly sets a game to active
	"""
	self.active = True


    def stopGame(self):
	"""
	Explicitly stops the game
	"""
	self.active = False


    def on_socket( self, packet ):
	"""
	receives the 'update' packet and reads it
	"""
	#process the packet
	try:
	    for plData in packet['players']:
		self.updatePeer( plData )
	except KeyError:
	    print "GameWorld -` on_socket - Missing 'players' in update packet"
	    pass



    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



    def addCollision(self, type1, type2):
	"""
	This function determines whether to add a new collision or
	to transfer an existing one to the new list.
	"""
	if (type1, type2) in self.prevCols:
	    self.collisions[(type1, type2)] = self.prevCols[(type1, type2)]
	else:
	    self.collisions[(type1, type2)] = Collision((type1, type2))




    #\\\\\\\\\\\\\\\\\\\\\\\\\\#
    # Player setup/control
    def setPlayer( self, player ):
	"""
	Set the player by object
	"""
	self.player = player
	#self.player.setName( self.setsMgr.player_name )

	if self.controller:
	    self.controller.setPlayer( self.player )




    def setPlayerType( self, type ):
	"""
	Set the player by type-str
	"""
	if type == 'Robber':
	    self.setPlayer( Robber() )
	    #self.player.setName( self.setsMgr.player_name )
	    
	    if self.level:
		self.level.setTilesPerView( [15,15] )
	    	self.player.setPos(self.level.getThiefInitPos())
		self.player.scaleSizeByTileSize( self.level.getTileSize() )

	elif type == 'Cop':
	    self.setPlayer( Cop() )
	    #self.player.setName( self.setsMgr.player_name )
	    
	    if self.level:
		self.level.setTilesPerView( -1 )
	    	self.player.setPos( self.level.getCopInitPos() )
		self.player.scaleSizeByTileSize( self.level.getTileSize() )

	else:
	    print type, ' is not an acceptable argument to setPlayer()'

	if self.controller:
	    self.controller.setPlayer( self.player )

	self.scrSpeed = ( int(self.player.moveSpeed[0]),
			    int(self.player.moveSpeed[1]) )
	self.centerScreenAroundPlayer()


    def getPlayer( self ):
	return self.player



    def getPlayerType( self ):
	if self.player:
	    return self.player.getType()
	else:
	    return None


    def movePlayer( self, offset=(0,0) ):
	"""
	Simply calls the position func of the player
	"""
	self.player.move( offset )


    def positionPlayer( self, pos=(1,1) ):
	"""
	Place the player at some particular spot
	"""
	self.player.setPos( pos )


    def ensureWithinLevel( self ):
	"""
	checks the player's position is within the level area
	"""

	mapSize = self.level.mapSize
	tileSize = self.level.tileScrSize
	playerPos = self.player.pos

	# check that PosX > left_edgeTileWidth
	if playerPos[0] < 0:
	    self.positionPlayer([0, playerPos[1]])

	# check that PosY > top_edgeTileHeight
	if playerPos[1] < 0:
	    self.positionPlayer([playerPos[0], 0])

	# check that PosX < right_EdgeTileWidths
	if playerPos[0] > mapSize[0]*tileSize[0]:
	    self.positionPlayer( [(mapSize[0]*tileSize[0]), playerPos[1]] )
	
	# check that PosY < bottom_EdgeTileWidth
	if playerPos[1] > mapSize[1]*tileSize[1]:
	    self.positionPlayer( [playerPos[0], (mapSize[1]*tileSize[1])] )
	    



    #\\\\\\\\\\\\\\\\\\\\\\\\\\#
    # Controller Setup
    def setController( self, controller ):
	"""
	Set the controller by passing a derived Controller class
	"""
	self.controller = controller
	self.controller.setPlayer( self.player )



    def setControllerType( self, type ):
	"""
	Sets the controller by passing either "keyboard" or "mouse"
	"""
	# determine which type of controller to create
	if type.lower() == "keyboard":
	    self.controller = Keyboard()
	elif type.lower() == "mouse":
	    self.controller = Mouse()
	else:
	    print "Set Controller Failed with type: ", type
	    return

	# set the player of the controller
	self.controller.setPlayer(self.player)



    def getController( self ):
	return self.controller



    def centerScreenAroundPlayer(self):
	"""
	As the name suggests, it centers the screen as best it can
	around the player.
	"""
	self.positionScreen( [self.player.pos[0]-(self.scrSize[0]/2),
			   self.player.pos[1]-(self.scrSize[1]/2) ] )
	# this will check the screen to make sure it is within the bounds
	#   of the level
	self.moveScreen( [0,0] )


    #\\\\\\\\\\\\\\\\\\\\\\\\\\#
    # Level setup
    def setLevelByName( self, level=None ):
	"""
	Set the level by name
	"""
	if level:
	    self.levelName = level
	    self.level.load( level )

	    if self.player:
		if self.player.type == 'Robber':
		    self.level.setTilesPerView( [15,15] )
		    self.player.setPos( self.level.getThiefInitPos() )
		    self.player.scaleSizeByTileSize( self.level.getTileSize() )
		elif self.player.type == 'Cop':
		    self.level.setTilesPerView( -1 )
		    self.player.setPos( self.level.getCopInitPos() )
		    self.player.scaleSizeByTileSize( self.level.getTileSize() )

	    self.centerScreenAroundPlayer()
	else:
	    self.level = None


    def setLevel( self, level=None ):
	"""
	Set the level with an instance
	"""
	self.level = level
	
	if self.player and self.level:
	    self.levelName = self.level.lvlName
	    if self.player.type == 'Robber':
		self.level.setTilesPerView( [15,15] )
		self.player.setPos( self.level.getThiefInitPos() )
		self.player.scaleSizeByTileSize( self.level.getTileSize() )
	    elif self.player.type == 'Cop':
		self.level.setTilesPerView( -1 )
		self.player.setPos( self.level.getCopInitPos() )
		self.player.scaleSizeByTileSize( self.level.getTileSize() )

	    self.centerScreenAroundPlayer()


    def getLevel( self ):
	return self.level



    def getLevelName( self ):
	return self.level.lvlName



    #\\\\\\\\\\\\\\\\\\\\\\\\\\#
    # Drawing
    def render( self ):
	"""
	Called by the screen class; this function will call render()
	of all entities in self.objects and return the compiled list
	"""

	renderList = []

	# don't update if paused
	if not self.active:
	    return renderList

	# render order is relevant in this function esp. wrt the level and
	#   the player.
	if self.level:
	    if self.player.type == 'Robber':
		renderList.extend(self.level.render(self.scrScroll))
	    elif self.player.type == 'Cop':
		quad = self.player.getQuad( self.scrScroll )
		renderList.extend(self.level.render(self.scrScroll, quad))
	
	if self.player:
	    renderList.extend( self.player.render(self.scrScroll) )

	for object in self.objects:
	    renderList.extend( object.render(self.scrScroll) )

	for peer in self.peers.values():
	    if self.player.type == "Cop":
	    	quad = self.player.getAreaUnder( self.scrScroll )

	    	if peer.pos[0] > quad[0] and peer.pos[0] < quad[2] \
	    	    and peer.pos[1] > quad[1] and peer.pos[1] < quad[3]:
	    		renderList.extend( peer.render(self.scrScroll) )
	    else:
		renderList.extend( peer.render(self.scrScroll) )


	for txt in self.txtObjs:
	    #renderList.extend( txt.render(self.scrScroll) )
	    renderList.extend( txt.render() )

	return renderList


    #\\\\\\\\\\\\\\\\\\\\\\\\\\#
    # Screen control
    def moveScreen( self, offset=[0,0] ):
	"""
	Moves the screen in world coords offset from its current
	position.
	"""
	if not self.screen:
	    self.screen = Screen()
	
	# validate the upper and left extent
	self.scrScroll[0] = max( self.scrScroll[0]+offset[0], 0 )
	self.scrScroll[1] = max( self.scrScroll[1]+offset[1], 0 )

	tileSize = self.level.tileScrSize
	scrSize = self.screen.size
	mapSize = self.level.mapSize

	self.scrScroll[0] = min( self.scrScroll[0]
				, (mapSize[0]*tileSize[0]) - scrSize[0] )
	self.scrScroll[1] = min( self.scrScroll[1]
			    , (mapSize[1]*tileSize[1]) - scrSize[1] )


    def positionScreen( self, pos=[0,0] ):
	"""
	Put the screen at a specific position
	"""
	self.scrScroll[0] = pos[0]
	self.scrScroll[1] = pos[1]
    

    def scrollScreen(self):
	
	dir = self.player.facingDir
	#playerPos = list(self.player.getCenterPos())
	playerPos = list(self.player.pos)

	if not self.screen:
	    self.screen = Screen()

	screenRes = self.screen.size

	# the extent from the side-buffer(above)
	scrExtent = ( self.scrScroll[0] + screenRes[0]
		    , self.scrScroll[1] + screenRes[1] )

	# The current screen scroll + the side buffer offset
	#   and the size 
	# The order of the "walls" indicated within are
	#   West, North, East, South
	scrEdge = ( self.scrScroll[0] + self.sideBuf[0]
		    , self.scrScroll[1] + self.sideBuf[1]
		    , scrExtent[0] - self.sideBuf[0]
		    , scrExtent[1] - self.sideBuf[1] )

	# the screen movement based on its current position
	offset = [0,0]

	# Horizontal, player is within the area
	if playerPos[0] > scrEdge[0] and dir[0] > 0:
	    if abs(playerPos[0] - scrEdge[0]) >= self.scrSpeed[0]:
		offset[0] = self.scrSpeed[0]
	    else:
		offset[0] = int(playerPos[0] - scrEdge[0])

	if playerPos[0] < scrEdge[2] and dir[0] < 0:
	    if abs(playerPos[0] - scrEdge[2]) >= self.scrSpeed[0]:
		offset[0] = -self.scrSpeed[0]
	    else:
		# ..subtracted in this order, (pos - scrEdge) is already negative..
		offset[0] = int(playerPos[0] - scrEdge[2])

	# Vertical
	if playerPos[1] > scrEdge[1] and dir[1] > 0:
	    if abs(playerPos[1] - scrEdge[1]) >= self.scrSpeed[1]:
		offset[1] = self.scrSpeed[1]
	    else:
		offset[1] = int(playerPos[1] - scrEdge[1])

	if playerPos[1] < scrEdge[3] and dir[1] < 0:
	    if abs(playerPos[1] - scrEdge[3]) >= self.scrSpeed[1]:
		offset[1] = -self.scrSpeed[1]
	    else:
		offset[1] = int(playerPos[1] - scrEdge[3])

	
	# move the screen by the ofset
	self.moveScreen( offset )


    #\\\\\\\\\\\\\\\\\\\\\\\\\\#
    # World-object stuff
    def addObject( self, newObj ):
	"""
	Appends an object to the game world(as long as it can be rendered)
	"""

	if 'render' in dir( newObj ):
	    self.objects.append( newObj )
	else:
	    print 'Warning : GameWorld : newObj does not have a "render" function; it was not added to the render list.'


    def updatePeer( self, update ):
	"""
	update (or add) a peer to the game world
	"""
	if update['name'] == self.player.getName():
	    # ignore this packet because it is the player packet
	    return

	if update['name'] not in self.peers:
	    # Make a player object of the type in the packet
	    if update['pType'] == 'Robber':
		newPlayer = Robber()
		newPlayer.setPos( self.scalePos(update['position']) )
		newPlayer.setSize( self.getPeerSize( "Robber") )
		self.peers[ update['name'] ] = newPlayer
	    if update['pType'] == 'Cop':
		newPlayer = Cop()
		newPlayer.setPos( self.scalePos(update['position']) )
		newPlayer.setSize( self.getPeerSize( "Cop") )
		self.peers[ update['name'] ] = newPlayer
	else:
	    self.peers[ update['name'] ].setPos(\
		    self.scalePos(update['position']))

    def scalePos(self, pos):
	"""
	scales the peer's map pos to tile coords
	"""
	tileSize = self.level.getTileSize()
	return [ pos[0]*tileSize[0], pos[1]*tileSize[1] ]

    def getPeerSize(self, type):
	"""
	Calculates and returns the size of a peer based on its type
	and the playyer's type.
	"""
	size = None
	tileSize = self.level.getTileSize()

	if self.player.type == type:
	    pass
	elif self.player.type == "Robber":
	    # then peer-type == "Cop"
	    size = [tileSize[0]*5, tileSize[1]*5]
	elif self.player.type == "Cop":
	    # then peer-type == "Robber"
	    size = [tileSize[0]*0.5, tileSize[1]*0.5]

	return size


    def on_key_press(self, key, x, y):
	"""On key press"""
	if self.active:
	    if self.controller and isinstance( self.controller, Keyboard ):
		self.controller.on_key_press(key, x, y)



    def on_key_release(self, key, x, y):
	"""On key release"""
	if self.active:
	    if self.controller and isinstance( self.controller, Keyboard ):
		self.controller.on_key_release(key, x, y)



    def on_specialkey_press(self, key, x, y):
	"""On special key press"""
	if self.active:
	    if self.controller and isinstance( self.controller, Keyboard ):
		self.controller.on_specialkey_press(key, x, y)




    def on_specialkey_release(self, key, x, y):
	"""On special key release"""
	if self.active:
	    if self.controller and isinstance( self.controller, Keyboard ):
		self.controller.on_specialkey_release(key, x, y)




    def on_mouse_motion(self, x, y):
	"""On mouse motion"""
	if self.active:
	    if self.controller and isinstance( self.controller, Mouse ):
		self.controller.on_mouse_motion(x, y)




    def on_mouse(self, button, state, x, y):
	"""On mouse press/release"""
	if self.active:
	    if self.controller and isinstance( self.controller, Mouse ):
		self.controller.on_mouse(button, state, x, y)
Esempio n. 14
0
class TitleScreenState(EngineState):

    def __init__(self, engine):
	"""
	The game determines what is happening on screen
	based on what state the GameEngine instance has.
	"""
	self.engine = engine

	self.screen = Screen()
	self.res = self.engine.setsMgr.screenRes
	res = self.res # saying 'self.res' was making lines too long. :P
	
	# get/load the font
	self.font = FontManager().loadFont( 'Basic' )

	# screen objects
	self.UI = {}
	self.UI['title'] = UIText("Breakin And Poppin"\
		, pos=[res[0]*.01,res[1]*.10], font=self.font, scale=0.05)
	self.UI['start_server'] = UIText("Start a Server"\
		, pos=[res[0]*0.5, res[1]*0.42], font=self.font, scale=0.04)
	self.UI['start_server'].center()
	self.UI['join_server'] = UIText("Join a Server"\
		, pos=[res[0]*0.5, res[1]*0.5], font=self.font, scale=0.04)
	self.UI['join_server'].center()
	self.UI['quit'] = UIText("Quit"\
		, pos=[res[0]*0.5, res[1]*0.58], font=self.font, scale=0.04)
	self.UI['quit'].center()
	self.titleBGImg = UIImage("TitleScreenBG.png"\
		, pos=[0,0], size=res)

	self.selected = 'start_server'

    def renderFrame(self):
	if not self.screen:
	    self.screen = Screen()

	self.screen.drawThis( self.titleBGImg )

	selectionBox = UIImage("box.png",
				pos=self.UI[self.selected].pos,
				size=[(self.res[0]*0.05)*10, self.res[1]*0.05])
	selectionBox.center()
	self.screen.drawThis( selectionBox )

	for uiObj in self.UI.values():
	    # draw the background image firstly
	    self.screen.drawThis( uiObj )

	return self

    def on_key_press(self, key, x, y):
	"""
	On key press
	"""

	if key == '\x1b':
	    return None

	elif key == chr(13):
	    if self.selected == "start_server":
		self.statePath = 'start'
		return CreateServerState(self.engine)
	    elif self.selected == "join_server":
		self.statePath = 'join'
		return JoinServerState(self.engine)
	    elif self.selected == "quit":
		return None

	elif key == 101:
	    if self.selected == "start_server":
		self.selected = "quit"
	    elif self.selected == "join_server":
		self.selected = "start_server"
	    elif self.selected == "quit":
		self.selected = "join_server"

	elif key == 103:
	    if self.selected == "start_server":
		self.selected = "join_server"
	    elif self.selected == "join_server":
		self.selected = "quit"
	    elif self.selected == "quit":
		self.selected = "start_server"

	return self


    def on_mouse_motion(self, x, y):
	"""
	On mouse motion
	"""
	# check the mouse pos against all the choices
	if self.UI['start_server'].CollidePoint( (x,y) ):
	    self.selected = "start_server"
	    
	elif self.UI['join_server'].CollidePoint( (x,y) ):
	    self.selected = "join_server"
	    
	elif self.UI['quit'].CollidePoint( (x,y) ):
	    self.selected = "quit"
    
	return self

    def on_mouse(self, button, state, x, y):
	"""
	On mouse release
	"""
	if button == GLUT_LEFT_BUTTON and state == GLUT_DOWN:
	    
	    # check the mouse pos against all the choices
	    if self.UI['start_server'].CollidePoint( (x,y) ):
		self.engine.statePath = 'start'
		return CreateServerState(self.engine)
		
	    if self.UI['join_server'].CollidePoint( (x,y) ):
		self.engine.statePath = 'join'
		return JoinServerState(self.engine)
		
	    if self.UI['quit'].CollidePoint( (x,y) ):
		return None

	return self
class EngineState():

    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)

    def renderFrame(self):
	""" RenderFrame - Base Class """
	if not self.screen:
	    self.screen = Screen()

	self.screen.drawThis( self.str_paused )

	return self

    def on_key_press(self, key, x, y):
	"""
	On key press
	"""
	if key == '\x1b':
	    return None

	# for now, this means to "spawn a server"
	if key == 'x':
	    if system() == "Linux" or system() == "Macintosh":
		Popen( [r'/usr/bin/python/python'
		    ,os.path.join( self.engine.setsMgr.home_dir
				    , 'StartServer.py' )] )
	    elif system() == "Windows":
		Popen([r'C:\Python25\python.exe'
		    ,os.path.join( self.engine.setsMgr.home_dir
				    , 'StartServer.py' )])
	    else:
	    	print "you are on an unsupported platform for spawning a server"
	    # declare that this game instance is the server owner
	    self.engine.serverOwner = True
	    
	# for now, its "connect"
	elif key == 'c':
	    self.engine.connect()

	elif key == 'v':
	    self.engine.disconnect()

	elif key == 'g':
	    self.str_paused.toggleVisible()
	    self.engine.gameWorld.pause()

	return self

    def on_key_release(self, key, x, y):
	"""
	On key release
	"""
	return self

    def on_specialkey_press(self, key, x, y):
	"""
	On special key press
	"""
	return self

    def on_specialkey_release(self, key, x, y):
	"""
	On special key release
	"""
	return self

    def on_mouse_motion(self, x, y):
	"""
	On mouse motion
	"""
	self.engine.gameWorld.startGame()
	return self

    def on_mouse(self, button, state, x, y):
	"""
	On mouse
	"""
	return self

    def on_socket(self, packet):
	"""
	On socket
	"""
	self.gameTime = packet['time']
	return self

    def update(self, elapsed):
	"""
	switches the state based on 
	"""
	return self
Esempio n. 16
0
class GameState(EngineState):

    def __init__(self, engine):
	"""
	The game determines what is happening on screen
	based on what state the GameEngine instance has.
	"""
	self.engine = engine
	self.res = self.engine.setsMgr.screenRes
	self.screen = None

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

	engine.gameWorld.setLevelByName( 'Level1L' )
	engine.gameWorld.gameTime = 0.0

	engine.gameWorld.startGame()
	#glutTimerFunc(300, self.print_game_world, 300)

    def print_game_world(self, elapsed):
	gW = self.engine.gameWorld
	tileSize = gW.level.getTileSize()
	peerPos = gW.peers.values()[0].pos
	print ''
	print '--- Gameworld ---'
	print 'Player = {', gW.player.playerName, ":", gW.player.pos, "}"
	print 'mapPixelPos = ', gW.player.pos[0] + gW.scrScroll[0]\
				, gW.player.pos[1] + gW.scrScroll[1]
	print 'mapTilePos = ', gW.player.pos[0] / tileSize[0],\
				gW.player.pos[1] / tileSize[1]
	print 'renderPos = ', gW.player.pos[0] - gW.scrScroll[0]\
			    , gW.player.pos[1] - gW.scrScroll[1]
	print '  ------ ------ '
	print 'Peers = {', gW.peers.values()[0].playerName, ":", peerPos, "}" 
	print 'mapTilePos = ', peerPos[0] / tileSize[0],\
				peerPos[1] / tileSize[1]
	print 'renderPos = ', peerPos[0] - gW.scrScroll[0]\
			    , peerPos[1] - gW.scrScroll[1]
	print '  ------ ------ '
	print 'TileSize = ', tileSize
	print ''
	glutTimerFunc(300, self.print_game_world, 300)

    def renderFrame(self):
	""" RenderFrame - Base Class """
	if not self.screen:
	    self.screen = Screen()

	scrSize = self.screen.getSize()
	#self.engine.gameWorld.positionPlayer( [scrSize[0],scrSize[1]] )

	self.screen.drawThis( self.str_paused )
	
	return self

    def on_key_press(self, key, x, y):
	"""
	On key press
	"""
	if key == chr(27):   # Escape
	    return ChoosePlayerState(self.engine)
	elif key == 'g':
	    self.str_paused.toggleVisible()
	    self.engine.gameWorld.pause()
	
	# controller
	self.engine.gameWorld.on_key_press(key, x, y)

	return self


    def on_key_release(self, key, x, y):
	"""On key release"""
	# controller	
	self.engine.gameWorld.on_key_release(key, x, y)
	return self


    def on_specialkey_press(self, key, x, y):
	"""On special key press"""
	# controller
	self.engine.gameWorld.on_specialkey_press(key, x, y)
	return self

    def on_specialkey_release(self, key, x, y):
	"""On special key release"""
	# controller
	self.engine.gameWorld.on_specialkey_release(key, x, y)
	return self

    def on_mouse_motion(self, x, y):
	"""On mouse motion"""
	# controller
	self.engine.gameWorld.on_mouse_motion(x, y)
	return self

    def on_mouse(self, button, state, x, y):
	"""On mouse press/release"""
	# controller
	self.engine.gameWorld.on_mouse(button, state, x, y)
	return self

    def update(self, elapsed):
	"""
	switches the state based on 
	"""
	if self.engine.gameWorld.gameStatus == "winner":
	    # Send a signal to the server that this player
	    #	seems to have won the game ( the server will
	    #	have to agree with our word )
	    
	    # Go to the appropriate engine-state screen
	    #self.engine.gameWorld = GameWorld()
	    print 'switching to winner state'
	    return WinnerState(self.engine)

	elif self.engine.gameWorld.gameStatus == "loser":
	    # Go to the appropriate engine-state screen
	    #self.engine.gameWorld = GameWorld()
	    return LoserState(self.engine)
	else:
	    return self
Esempio n. 17
0
class WinnerState(EngineState):

    def __init__(self, engine):
        """
	
	"""
	self.engine = engine
	self.res = self.engine.setsMgr.screenRes
	res = self.res
	self.screen = None

	# announce that the game is over
	#engine.announceGameOver( 'winner' )
	self.engine.gameWorld.status = 'winner'
	self.engine.gameWorld.stopGame()

	self.font = FontManager().loadFont( 'Basic' )
	self.UI = {}
	self.UI['nice_work'] = UIText("Nice Work!"
		, pos=[res[0]*0.5, res[1]*0.3], font=self.font, scale=0.047)
	self.UI['nice_work'].center()

	self.UI['cop_wins'] = UIText("You Caught The Robber!"
		, pos=[res[0]*0.5, res[1]*0.5], font=self.font, scale=0.04)
	self.UI['cop_wins'].center()

	self.UI['robber_wins'] = UIText("You made it home safe!"
		, pos=[res[0]*0.5, res[1]*0.5], font=self.font, scale=0.04)
	self.UI['robber_wins'].center()

    	self.UI['press_esc'] = UIText("Press escape to continue"
		, pos=[res[0]*0.5, res[1]*0.75], font=self.font, scale=0.04)
	self.UI['press_esc'].center()

	self.titleBGImg = UIImage("black_bg.png"\
		, pos=[0,0], size=res)

    def renderFrame(self):
	""" RenderFrame - Base Class """
	
	if not self.screen:
	    self.screen = Screen()

	self.screen.drawThis( self.titleBGImg )
	self.screen.drawThis( self.UI['nice_work'] )

	if self.engine.gameWorld.getPlayerType() == "Robber":
	    self.screen.drawThis( self.UI['robber_wins'] )
	elif self.engine.gameWorld.getPlayerType() == "Cop":
	    self.screen.drawThis( self.UI['cop_wins'] )

	self.screen.drawThis( self.UI['press_esc'] )

	return self

    def on_key_press(self, key, x, y):
	"""
	On key press
	"""
	if key == chr(27):   # Escape
	    self.engine.disconnect()
	    return TitleScreenState(self.engine)
	else:
	    return self


    def on_mouse(self, button, state, x, y):
	"""
	On mouse press
	"""
	self.engine.disconnect()
	return TitleScreenState(self.engine)
class GameEngine(Client):
    """
    The main game client:
      The game engine sends GLUT events to a gamestate class that
      manages what is happening on the screen.  It also handles
      server communication.
    """

    def __init__(self):
	"""
	Initializes the game client
	"""
    
	# since our game client is a client...
	Client.__init__(self)

	self.setsMgr = SettingsManager()
	self.res = self.setsMgr.screenRes

	self._InitGLUT_()
	self._InitGL_()

	# Make a screen object - we want to make the first here
	#   so that we can ensure the size is set appropriately.
	#   All other objects using the screen-singleton will assume
	#   it is has already been sized and, thus, won't call setSize.
	self.screen = Screen()
	self.screen.setSize( self.res )

	# be the first entity to create the managers
	self.rsrcMgr = TextureManager()
	self.fontMgr = FontManager()

	self.connected = False
	self.serverOwner = False
	self.serverName = "default"

	# the gameworld is mostly undefined at this point
	self.gameWorld = GameWorld()
	
	# this variable denotes for certain game states whether
	#   the user 'start'-ed or 'join'-ed a server so they know
	#   which state to return to when the user pushes 'back'
	self.statePath = None
	# create the initial game state
	self.gState = TitleScreenState(self)
	#self.gState = EngineState(self)


    def _InitGLUT_(self):
	"""Initialize GLUT"""
	glutInit()
	#*# Create/Initialize the Window
	glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA)
	glutInitWindowPosition( 0,0 )
	glutInitWindowSize( self.res[0], self.res[1] )

	self.window = glutCreateWindow( "Breakin & Poppin" )

	#*# setup the event handlers
	glutDisplayFunc(self.renderFrame)
	glutIdleFunc(self.on_tick)
	#glutReshapeFunc(self.changeSize)
	# keyboard
	glutKeyboardFunc( self.on_key_press )
	glutKeyboardUpFunc( self.on_key_release )
	glutIgnoreKeyRepeat( 1 ) # !=0 disables key repeat callbacks
	glutSpecialFunc( self.on_specialkey_press )
	glutSpecialUpFunc( self.on_specialkey_release )
	glutMouseFunc( self.on_mouse )
	glutPassiveMotionFunc( self.on_mouse_motion )
	
	#glutFullScreen()


    def _InitGL_(self):
	"""Initialize GL"""
	# Set up the rendering environment

	# setup the orthographic projection (firstly)
	glMatrixMode( GL_MODELVIEW )
	glPushMatrix()
	glLoadIdentity()

	# Set up the orthographic projection
	glOrtho(0, self.res[0], 0, self.res[1], -1, 1)
	# invert the y axis, down is positive
	glScalef(1, -1, 1)
	# mover the origin from the bottom left corner
	# to the upper left corner
	glTranslatef(0, -self.res[1], 0)

	# turn off the lighting and depth testing
	glPushAttrib( GL_DEPTH_BUFFER_BIT | GL_LIGHTING_BIT )
	glDisable( GL_LIGHTING )
	glDisable( GL_DEPTH_TEST )
	glDisable( GL_DITHER )	

    def on_key_press(self, key, x, y):
	"""On key press"""
	if self.gState:
	    self.gState = self.gState.on_key_press(key, x, y)

    def on_key_release(self, key, x, y):
	"""On key release"""
	if self.gState:
	    self.gState = self.gState.on_key_release(key, x, y)
	
    def on_specialkey_press(self, key, x, y):
	"""On special key press"""
	# game state
	if self.gState:
	    self.gState = self.gState.on_key_press(key, x, y)

    def on_specialkey_release(self, key, x, y):
	"""On special key release"""
	# game state
	if self.gState:
	    self.gState = self.gState.on_key_release(key, x, y)	

    def on_mouse_motion(self, x, y):
	"""On mouse motion"""
	# game state 
	if self.gState:
	    self.gState = self.gState.on_mouse_motion(x, y)

    def on_mouse(self, button, state, x, y):
	"""On mouse press/release"""
	# game state
	if self.gState:
	    self.gState = self.gState.on_mouse(button, state, x, y)

    def on_update(self, elapsed):
	"""
	The function that updates every object's animation status (45ms)
	"""

	# update the game state
	if self.gState:
	    self.gState = self.gState.update(elapsed)

	# gameworld
	self.gameWorld.update(elapsed)

	# gamestate
	glutTimerFunc(50, self.on_update, 50)	

    def on_socket( self, elapsed):
	"""
	"""
	# call the base class version (returns the packet)
	packet = Client.on_socket(self, elapsed)

	if packet != None:
	    #print 'client - recv - got a packet'
	    self.readPacket( packet )	# the real meat of this
	else:
	    # Oh well, no packet for some reason
	    pass

	glutTimerFunc(20, self.on_socket, 20)
	
    ###
    def readPacket(self, packet):
	"""
	This interpets a packet sent by the server
	"""

	# This case is usually handled by the GameEngine side
	#   (But this class isn't supposed to know that. :P)
	if packet['type'] == 'update':
	    #print 'Client : Got an update : ', packet
	
	    if self.connected:

		if self.gState:
		    # let the game state handle some bih'ness
		    self.gState= self.gState.on_socket(packet)


		if self.gameWorld:
		    self.gameWorld.on_socket(packet)

		# if the level is different or non-existant, load it
		#if not self.gameWorld.getLevel() \
		#	    or (packet['level'] != self.gameWorld.getLevelName()):
		#	self.gameWorld.setLevelByName( packet['level'] )


	if packet['type'] == 'message':
	    #print 'Client : Got a message : ', packet

	    # Connection Reset by Peer
	    if 'CRbP' in packet:
		print 'Disconnected: The server connection is dead.'
		self.disconnect()

	    # The server is full
	    if 'ServerFull' in packet:
		print 'Disconnected: The server is full.'
		# this is just like getting CRbP for now
		#   but the response to the user should
		#   be different at some point.
		self.disconnect()

	    if 'CurrentLevel' in packet:
		#self.engine.gameWorld.setLevel( packet['CurrentLevel'] )
		print 'Current level is ', packet['CurrentLevel']
		self.gameWorld.setLevelByName(packet['CurrentLevel'])

	    if 'NextLevel' in packet:
		print 'Next Level is ', packet['NextLevel']
		
	    if 'GameStatus' in packet:
		self.gameWorld.stopGame()
		if packet['GameStatus'] == 'winner':
		    self.gState = LoserState(self)
		elif packet['GameStatus'] == 'loser':
		    self.gState = WinnerState(self)
		    
		
	    

    def on_tick(self):
	"""Timer event: on tick"""
	# kill the app if there is no state
	if not self.gState:
	    self.on_close()
	# render the scene
	glutPostRedisplay()


    def on_close(self):
	"""On close"""
        # leave the server
	self.disconnect()
	glutDestroyWindow(self.window)
	sys.exit()


    def renderFrame(self):
	"""The glut display function"""
	# clear the buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

	# Draw the game world
	if self.gameWorld:
	    self.screen.drawThis( self.gameWorld )

	# Render if we have a state
	if self.gState:
	    # the state passes any objects the screen to be rendered
	    self.gState.renderFrame()

	# The screen draws all objects it has been passed
	self.screen.draw()

	# Dump the contents to the screen
	glutSwapBuffers()
Esempio n. 19
0
from engine import Screen, World, Tile, Entity
from systems import System, GraphicsSystem, ControlSystem, SpriteSystem
from components import Component, Position, Camera, Control, State, Sprite

DEBUG = True

playertile = (0, 0)
playerposition = (0, 0)

pygame.init()
pygame.display.set_caption('~ R I K \' S   G A M E ~')
pygame.display.set_icon(pygame.image.load('icon.png'))
clock = pygame.time.Clock()

w = World(size=1024, tilesize=32)
s = Screen(800, 800)

gs = GraphicsSystem()
cs = ControlSystem()
ss = SpriteSystem()

p = Entity(w)
p.camera = Camera(0, 0, 800, 800, track=True, entitytotrack=p)
p.position = Position(0, 0, 32, 32, 2)
p.control = Control(pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT)
p.state = State()

p.sprite = Sprite()
p.sprite.sprites['idle'] = [
    pygame.image.load('images/player/idle.png'),
    pygame.image.load('images/player/idle2.png'),
Esempio n. 20
0
def Main():
  Screen.WakeScreen()
  Timer.SetTimeOut('sleep_screen', 7, Screen.SleepScreen, permanent=True)
  RefreshDesktop()
Esempio n. 21
0
def Thread():
    serial_port = SystemState.PhoneState.serial_port

    # Infinite loop to pass found messages to InterruptSystem() in cobblr.
    while True:
        # Looks for incomming serial messages (calls, texts, etc).
        try:
            serial_data = serial_port.readlines()
        except serial.SerialException:
            serial_data = []  # Evil.

        serial_data = ParseSerialData(serial_data)
        if len(serial_data) > 0:
            print 'serial data: ', serial_data

        # Call related interrupts
        if len(serial_data) > 0:
            message_type = serial_data[0]
            if message_type == 'RING':
                serial_data = serial_data[1].strip()
                stripped_number = serial_data.split('"')[1].strip('"')
                Screen.WakeScreen()

                # Setting RING timeout timer to hang up if NO CARRIER is not received.
                callback = Menu.Back
                callback_args = {'change_application': True}
                Timer.DeleteTimeOut('ring_timeout')
                Timer.SetTimeOut('ring_timeout', 6, callback, callback_args)

                # Changes menu
                callback_args = {
                    'screen_mode': 3,
                    'application': 'phone',
                    'change_application': True,
                    'store_history': False
                }
                message = {
                    'callback': Menu.JumpTo,
                    'callback_args': callback_args
                }
                SystemState.interrupt_queue.put(message)

                # Print's 'Incomming Call' on the screen.
                callback_args = {
                    'permatext': True,
                    'text': 'Incomming Call',
                    'text_type': 'message'
                }
                message = {
                    'callback': TextWriter.Write,
                    'callback_args': callback_args
                }
                SystemState.interrupt_queue.put(message)

                # Print's the phone number on the screen.
                callback_args = {
                    'permatext': True,
                    'text': stripped_number,
                    'text_type': 'subtext'
                }
                message = {
                    'callback': TextWriter.Write,
                    'callback_args': callback_args
                }
                SystemState.interrupt_queue.put(message)

            if message_type == 'ATA':
                Timer.DeleteTimeOut('ring_timeout')

            # If someone hang's up, go back to the lass application.
            if message_type == 'NO CARRIER':
                Timer.DeleteTimeOut('ring_timeout')
                callback_args = {'change_application': True}
                message = {
                    'callback': Menu.Back,
                    'callback_args': callback_args
                }
                SystemState.interrupt_queue.put(message)