west_button = None root = None refresh_location = True refresh_objects_visible = True current_location = STARTING_POINT_LOCATION turns_in_room_with_dragon = 3 end_of_game = False sword_found = False dragon_killed = False door_openend = False scroll_object = GameObject.GameObject( "scroll", PASSAGE_WAY_B_LOCATION, True, True, False, "There are some barely readable words on it!") sword_object = GameObject.GameObject("sword", WEAPONS_STORAGE_LOCATION, True, False, False, "Wow, it looks sharp!") weapon_rack_object = GameObject.GameObject( "weapon rack", WEAPONS_STORAGE_LOCATION, False, True, False, "Hey, there is a cool-looking sword") key_object = GameObject.GameObject( "key", DRAGONS_LAYER_LOCATION, True, False, False, "It is one of those old-fashioned keys that may open up a door!") mouse_object = GameObject.GameObject( "mouse", PASSAGE_WAY_D_LOCATION, True, True, False, "The mouse insolently looks back at you.") dragon_object = GameObject.GameObject("dragon", DRAGONS_LAYER_LOCATION, False, False, False, "That is one evil-looking dragon!")
from timeit import Timer '''custome modules''' import GameObject import Player import TrueRandomAttack as tra import AttackWaves as atw import ClassPack as cp import Timer import Socket_Client as socket pg.init() pg.font.init() display_width = 800 display_height = 600 gameObject = GameObject.GameObject() colors = GameObject.Colors() #display x,y #gameDisplay = pg.display.set_mode((display_width, display_height)) #pg.display.set_caption('Block Hunger Games') #socket_client object sc = socket.Sock_Con() font = pg.font.SysFont(None, 25) def message_to_screen(msg, color, gameDisplay): screen_text = font.render(msg, True, color) gameDisplay.blit(
def initVars(self): self.width = 0 self.height = 0 # Objects for Cars, Logs, Frogs, and Turtles self.cars = [] self.logs = [] self.frogs = [] self.winning_frogs = [] self.dead_frogs = [] self.turtles = [] self.fly = GameObject(os.path.join('images', "fly_big.png")) self.fly.image.set_colorkey((0, 0, 0)) self.fly_appear_time = 12 self.fly_appear_timer = Timer(self.fly_appear_time) self.fly_timer = Timer(self.fly_appear_time / 2) self.croc = Croc(os.path.join('images', "croc_sprites_big.png")) # Background self.background = pygame.image.load(os.path.join('images', "background.png")) self.background_music = pygame.mixer.Sound(os.path.join('sounds','bgmusic.ogg')) self.frog_win_sound = pygame.mixer.Sound(os.path.join('sounds', 'frogwin.ogg')) self.frog_win_sound.set_volume(1000) # Vars for UI element data self.score = 0 self.timeSinceNew = 0 self.level = 1 self.message = "" # Surfaces for UI elements self.scoreSurface = None self.levelSurface = None self.timeRemainingSurface = None self.liveSurface = pygame.image.load(os.path.join("images", "safe_frog_big.png")).subsurface(Rect(0, 0, 40, 35)) self.messageSurface = None # Rects self.timeRemainingRect = Rect(0, 10, BARWIDTH, 22) self.goalRects = [] # More pygame stuff. Timer and font self.clock = pygame.time.Clock() self.font = pygame.font.Font(os.path.join('fonts', "FreeMonoBold.ttf"), 22) self.carSpeed = 1 self.num_logs = 3 self.lives = 5 self.frog_died = False self.frog_won = False self.game_over = False self.level_complete = False self.fly_shown = False self.level_complete_time = 0 self.paused = False self.croc_in_level = False self.back_to_menu = False self.timer = Timer(FROG_LIFE) self.game_over_time = 0 self.powerup_time = 3 self.powerup_timer = Timer(self.powerup_time)
def __init__(self): ShowBase.__init__(self) self.createLoadScreen('./LEGameAssets/Textures/title_screen.png') base.graphicsEngine.renderFrame() #== Environment and Rendering Settings == base.setFrameRateMeter(FLAG_SHOW_FRAMES_PER_SECOND) if FLAG_USE_AUTOSHADER: render.setShaderAuto() self.filters = CommonFilters(base.win, self.cam) # NEW if FLAG_SHOW_GLOW: bloomSize = 4 #'small' filterok = self.filters.setBloom(blend=(0, 0, 0, 1), desat=-0.5, intensity=3.0, size=bloomSize) if (filterok == False): print 'WARNING:Video card not powerful enough to do image postprocessing' #tex = loader.loadTexture("./LEGameAssets/Textures/loadbar_tray.png") self.loadBar = DirectWaitBar(text="", value=0, scale=(.35, .5, .5), pos=(0.006, .83, .83)) #self.loadBar['barRelief'] = DirectWaitBar.GROOVE #self.loadBar['scale'] = 0.05 #self.loadBar['barTexture'] = tex self.loadBar['barColor'] = (6.0 / 255.0, 11.0 / 255, 28.0 / 255.0, 1) self.loadBar.reparentTo(render2d) self.loadBar.hide() base.graphicsEngine.renderFrame() self.setBackgroundColor(166.0 / 255.0, 207.0 / 255.0, 240.0 / 255.0, 1) self.skybox = self.loader.loadModel( "LEGameAssets/Models/skybox_final.egg") self.skybox.setScale(50) self.skybox.reparentTo(render) #== Load the level and the managers == self.assets, self.objects, self.gameObjects, self.sounds, self.sequences = loadWorld( SCENE_FILE, LIBRARY_INDEX) self.loadBar['value'] += 5 base.graphicsEngine.renderFrame() self.conversations = loadConversations(SCENE_FILE, LIBRARY_INDEX) self.scenes = {} self.loadScenes() self.loadBar['value'] += 5 base.graphicsEngine.renderFrame() self.journalMgr = JournalMgr(self) self.loadJournal(self.journalMgr, JOURNAL_FILE) self.conversationMgr = ConversationMgr(self, self.conversations) self.scriptMgr = ScriptMgr(self) self.scriptMgr.loadScripts(SCRIPTS_LIST) self.scriptInterface = ScriptInterface(self) self.inventoryMgr = InventoryMgr(self) loadInventory(self.inventoryMgr, INVENTORY_FILE) self.loadBar['value'] += 5 base.graphicsEngine.renderFrame() self.ranSequences = [] #== Main Character == self.hero = None for name, gameObj in self.gameObjects.iteritems(): if gameObj.getNP().hasTag('LE-mainChar'): self.hero = gameObj break else: # make a default hero defaultHeroNP = loader.loadModel("panda") self.hero = GameObject(defaultHeroNP) self.hero.reparentTo(render) self.hero.setPos(0, 0, 0) self.hero.setTag('LE-mainChar', '180') self.gameObjects[self.hero.getName()] = self.hero self.setCollideMasks(self.gameObjects) # remove the hero from the objects dict so it cannot be clicked by player if self.hero.getName() in self.objects: del self.objects[self.hero.getName()] #== Camera == camHeightFactor = CAMERA_HEIGHT camTrailFactor = -CAMERA_TRAIL # careful of +/- distinction self.heroHeight = self.getModelHeight(self.hero) self.heroHeadingOffset = float(self.hero.getTag('LE-mainChar')) self.lastHeroH = self.hero.getH(render) + self.heroHeadingOffset # setup the camera pivot, which will follow the main character model and anchor the camera self.camPivot = NodePath('camPivot') self.camPivot.reparentTo(render) self.camHeight = camHeightFactor * self.heroHeight self.camTrail = camTrailFactor * self.heroHeight self.cam.setPos(self.camPivot.getPos() + (0, self.camTrail, self.camHeight)) self.cam.wrtReparentTo(self.camPivot) self.placeCamera(self.hero) # match X and Y to main character self.alignCamera(self.hero) # match heading to main character #self.camPivot.setH(render, self.hero.getH(render) + self.heroHeadingOffset) self.gameCam = self.cam #== Collisions == self.setupCollisions() #== Controls == self.disableMouse() self.keyMap = {'w': False, 'a': False, 's': False, 'd': False} self.enableMovement(self.hero) self.accept("mouse1", self.onClickin3D) self.accept('escape', sys.exit) self.accept('z', render.place) #== UI and Combat == self.gameplayUI = GameplayUI(self) self.gameplayUI.hideAll() # for health bars and on screen UI self.overlayAmbientLight = AmbientLight('overlayAmbientLight') self.overlayAmbientLight.setColor(VBase4(1.0, 1.0, 1.0, 1.0)) self.overlayAmbientLightNP = render.attachNewNode( self.overlayAmbientLight) # initialize the combat manager (which includes AI) now that a main character and gameplayUI instance and overlay light is established self.combatMgr = CombatMgr(self) # initialize player's spells self.heroSpells = [] for properties in PLAYER_SPELLS: spell = Spell(self.hero, properties) self.heroSpells.append(spell) #== Start Tasks taskMgr.add(self.moveHeroTask, 'moveHeroTask', appendTask=True) taskMgr.add(self.cameraFollowTask, 'cameraFollowTask', appendTask=True) taskMgr.add(self.processHeroCollisions, 'processHeroCollisions') taskMgr.add(self.updateHeroHeight, 'updateHeroHeight') self.combatMgr.startTasks() self.accept('enter', self.destroyLoadScreen) self.destroyLoadScreen()
def make_sprite(self, img_name): ship = GameObject.GameObject(img_name) return ship
def Instanciate(self, start, entityList, instance): # Create new entity #print("processing " + entityName) # Set up search visited = set() queue = deque() visited.add(start) queue.append(start) while queue: currentnode = queue.popleft() if currentnode.label == "base": entityList.appendleft(instance) for relation in currentnode.relations: if relation.destination not in visited: # If we have a new entity, instanciate it if relation.type == ControlRelationActions.Instanciate: # Check if we are to instanciate this entity if self.CheckProbability(relation.attributes): for i in range(self.GetCount(relation.attributes)): # Generate the new instance name name = relation.destination.label + str(i) # Check that the entity is not already there for existingInstance in entityList: if name == existingInstance.name: return #print("instanciating " + name) newInstance = GameObject.GameObject(name) #print("New instance environment: " + str(newInstance.environment)) self.AddAttributesToEntity( newInstance, relation.destination.attributes, start.attributes) self.Instanciate(relation.destination, entityList, newInstance) visited.add(relation.destination) # if we are inheriting attributes, accumulate node attributes and continue the search elif relation.type == ControlRelationActions.Inherit: # Check for a 'probability' attribute and get the value from the control attribute it if it's there if self.CheckProbability(relation.attributes): print("inheriting from " + relation.destination.label) self.AddAttributesToEntity( instance, relation.destination.attributes, {}) visited.add(relation.destination) queue.append(relation.destination) # if we have an association, make the link elif relation.type == ControlRelationActions.Associate: # Check for a 'probability' attribute and get the value from the control attribute it if it's there if self.CheckProbability(relation.attributes): # prepend the destination node label as a variable to the associate relation attribute for use by the scripts print("associating with " + relation.destination.label) self.AddAttributesToEntity( instance, relation.attributes, {}, relation.destination.label) visited.add(relation.destination) # if all else fails, just continue the search else: visited.add(relation.destination) queue.append(relation.destination)
def draw(self): self.fill() temp = GameObject.GameObject(0, 0, c.toolbar_width(), c.height) pygame.draw.rect(self.screen, c.toolbar_color, temp.bounds) for i in self.buttons: i.draw(self.screen)
def __init__(self): super().__init__() self.title = GameObject.GameObject() self.titleBg = GameObject.GameObject() self.pressAnyKey = GameObject.GameObject() self.flag = False
def loadWorld(sceneFile, libraryFile): Debug.debug(__name__, "Loading the world.") sceneFilename = Filename(sceneFile) libraryFilename = Filename.fromOsSpecific(os.getcwd()) + '/' + libraryFile lib = Library(Filename(libraryFilename.getDirname())) objects = {} gameObjects = {} tempObjs = {} assetIndex = AssetIndex(lib) sounds = {} sequences = {} f = open(sceneFilename.toOsSpecific()) doc = xml.dom.minidom.parse(f) root = doc.childNodes[0] for node in root.childNodes: if node.localName == "objects": for n in node.childNodes: if n.localName: if n.localName == "dummy": obj = Object.decode(n, inEditor=False, lib=lib) elif n.localName == "staticmesh": obj = StaticMesh.decode(n, lib=lib) elif n.localName == "actor": obj = LEActor.decode(n, lib=lib) elif n.localName == "ambient": obj = AmbLight.decode(n, inEditor=False, lib=lib) elif n.localName == "directional": obj = DirLight.decode(n, inEditor=False, lib=lib) elif n.localName == "point": obj = PoiLight.decode(n, inEditor=False, lib=lib) elif n.localName == "spot": obj = SpoLight.decode(n, inEditor=False, lib=lib) if obj.castsShadows: obj.light.setShadowCaster(True, obj.bufferX, obj.bufferY) else: obj.light.setShadowCaster(False) elif n.localName == "camera": obj = Cam.decode(n, inEditor=False, lib=lib) elif n.localName == "sphere": obj = SphereCollider.decode(n, inEditor=False, lib=lib) elif n.localName == "box": obj = BoxCollider.decode(n, inEditor=False, lib=lib) elif n.localName == "plane": obj = PlaneCollider.decode(n, inEditor=False, lib=lib) elif n.localName == "texturecard": obj = LETextureCard.decode(n, inEditor=False, lib=lib) elif n.localName == "LETerrain": obj = LETerrain.decode(n, inEditor=False, lib=lib) elif n.localName == "LERope": obj = LERope.decode(n, inEditor=False, lib=lib) tempObjs[obj.name] = obj # If the object is an actor if isinstance(obj, LEActor): # Add any joints to the dictionary for jointName in obj.joints: # Reference by "actorname/jointname" tempObjs[obj.name + "/" + jointName] = obj.joints[jointName] elif node.localName == "sounds": for n in node.childNodes: if n.localName: if n.localName == "sound": sound = Sound.decode(n, inEditor=False, lib=lib) sounds[sound.name] = sound #make sure everything is parented correctly for obj in tempObjs.values(): # If object is not a joint if not isinstance(obj, Joint): if obj.parentName == "*render": parent = render # If the parent is a joint elif obj.parentName.find(" <joint>") != -1: parName = obj.parentName[0:obj.parentName.index(" <joint>")] parent = tempObjs[parName].joint parent.setName( parent.getName()[0:parent.getName().index(" <joint>")]) else: parent = tempObjs[obj.parentName].nodePath if isinstance(obj, LERope): vertices = [] vertices.append({'point': obj.getPos()}) for wp in obj.waypoints: o = tempObjs[wp] if o: vertices.append({'node': o.getNodePath()}) else: obj.waypoints.remove(wp) obj.rope.verts = vertices obj.rope.recompute() obj.nodePath.reparentTo(parent) objects[obj.name] = obj.rope else: obj.nodePath.reparentTo(parent) objects[obj.name] = obj.nodePath gameObjects[obj.name] = GameObject(obj.nodePath) gameObjects[obj.name].setScripts(obj.scripts) else: objects[obj.joint.getParent().getName() + "/" + obj.getName()] = obj.joint #apply shaders toUpdate = [] for obj in tempObjs.values(): # If it is not a joint if not isinstance(obj, Joint): if obj.shader: #fix object shader inputs for i in obj.shader.inputs.values(): if i.__class__.__name__ == "LEShaderInputObj": i.obj = tempObjs[i.obj] if i.updateMe: toUpdate.append(obj.shader) break if obj.shader.active: obj.applyShader() if isinstance(obj, LELight): for name in obj.targetNames: target = tempObjs[name] obj.addTarget(target) # Terrain focal points # elif isinstance(obj, LETerrain): # fpNP = tempObjs[obj.fp] # obj.setFocalPoint(fpNP.getNodePath()) # Camera Waypoints rope and sequence elif isinstance(obj, Cam): if obj.waypoints != []: if obj.lookAt is not None: #print obj.lookAt obj.lookAt = tempObjs[obj.lookAt].getNodePath() # Generate the sequence vertices = [] #vertices.append({'point': obj.getPos()}) for wp in obj.waypoints: o = tempObjs[wp] if o: vertices.append({'node': o.getNodePath()}) else: o.waypoints.remove(wp) obj.rope.verts = vertices obj.rope.recompute() obj.genCamSequence() # if isinstance(obj, Cam): # print obj.waypoints # if obj.waypoints != []: # if obj.lookAt is not None: # print obj.lookAt # #obj.lookAt = tempObjs[obj.lookAt].nodePath # print obj.lookAt # obj.genWaypointRope() # print "Here passed" sequences[obj.getName()] = obj.sequence #print "weeee" def updateShaders(task): for s in toUpdate: s.update() return task.cont #taskMgr.add(updateShaders, 'updateShaders') return assetIndex, objects, gameObjects, sounds, sequences