def init(self, boardHandler, playerHandler, boardUIHandler): self.boardHandler = boardHandler self.playerHandler = playerHandler self.boardUIHandler = boardUIHandler self.displayMode = 0 self.reachable = set() self.attackable = set() self.focus = None self.reachIndicatorPool = [[ GameObject.GameObject() for i in range(self.boardUIHandler.size[1]) ] for i in range(self.boardUIHandler.size[0])] self.attackIndicatorPool = [[ GameObject.GameObject() for i in range(self.boardUIHandler.size[1]) ] for i in range(self.boardUIHandler.size[0])] redimage = ResourceManager.instance.getResourceHandler("red") blueimage = ResourceManager.instance.getResourceHandler("blue") for i in range(self.boardUIHandler.size[0]): for j in range(self.boardUIHandler.size[1]): self.reachIndicatorPool[i][j].init( blueimage, self.boardUIHandler.getPosOnScreen((i, j)), (50, 50)) self.attackIndicatorPool[i][j].init( redimage, self.boardUIHandler.getPosOnScreen((i, j)), (50, 50))
def SetGameStart(): pygame.mixer.music.load('Sound/backgroundSound.mp3') pygame.mixer.music.play(-1, 0) pygame.mixer.music.set_volume(0.3) gameExit = False while not gameExit: #gameDisplay.blit(StartBackground,(0,0)) gameDisplay.blit(__StartBackground, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_d: Boss = AIBossObject('Image/Boss_1.png', 200, 50, 10 * random.randint(5, 50)) Player1 = GameObject('Image/Player_1.png', 100, 1150, 10 * random.randint(5, 50)) AIBossGame(Boss, Player1) if event.key == pygame.K_k: Player1 = GameObject('Image/Player_1.png', 200, 1150, 10 * random.randint(5, 50)) Player2 = GameObject('Image/Player_2.png', 200, 50, 10 * random.randint(5, 50)) TwoPlayerVS(Player1, Player2) pygame.display.update() clock.tick(60)
def __init__(self, x, y, w, h, vel=(0, 0)): GameObject.__init__(x, y, w, h) self.color = choice('orange', 'pink') self.velocity = vel self.x = x self.y = y self.dx = 1 self.dy = 1
def draw(): GameWorld.draw() GameObject.draw_collision_box() font.draw(95, get_canvas_height() - 60, "X %d" % TOTAL_COIN_COUNT, FONT_COLOR) if (state == STATE_GAME_OVER): game_over_image.draw(400, 300, get_canvas_width(), get_canvas_height())
def __init__(self): super().__init__() self.result = GameObject.GameObject() self.battleBg = GameObject.GameObject() self.accounter = ResourceManager.instance.getResourceHandler("Accounter") self.statusFont = None self.playerStatus = [GameObject.GameObject() for i in range(5)] self.enemyStatus = [GameObject.GameObject() for i in range(5)]
def __init__(self): super().__init__() self.menuBg = GameObject.GameObject() self.gameStart = GameObject.GameObject() self.gameContinue = GameObject.GameObject() self.gameTutorial = GameObject.GameObject() self.gameExit = GameObject.GameObject() self.flag = False
def gameover(self): self.objects = [] content = open('gameover','r').read() pos = get_list(content) gameover_obj = go.Object('gameover') gameover_obj.add_pixel([go.pixel(i) for i in pos]) self.add_object(gameover_obj) self.fill_panel() self.render_once() self.set_pause() return 0
def handle_event(self, event): pair = (event.type, event.button) if (self.mouse_point == None): if (pair == LBUTTON_DOWN): if (GameObject.point_in_rect(GameObject.get_pico2d_pos(event), self.get_bb())): self.mouse_point = GameObject.get_pico2d_pos(event) if (self.menu == EXIT): self.left = 400 else: self.left = 300 return self if (event.type == SDL_MOUSEMOTION): mouse_pos = GameObject.get_pico2d_pos(event) in_rect = GameObject.point_in_rect(mouse_pos, self.get_bb()) if (in_rect): if (self.menu == EXIT): self.left = 400 else: self.left = 300 Button.SELECT_WAV.play() else: if (self.menu == EXIT): self.left = 100 else: self.left = 0 self.src_rect = (self.left, self.bottom, self.width, self.height) return False if (pair == LBUTTON_UP): self.mouse_point = None mouse_pos = GameObject.get_pico2d_pos(event) in_rect = GameObject.point_in_rect(mouse_pos, self.get_bb()) if (in_rect): if (self.menu == GAME_START): GameFramework.push(GameState) elif (self.menu == DESCRIPTION): pass elif (self.menu == EXIT): GameFramework.quit() return False if (event.type == SDL_MOUSEMOTION): mouse_pos = GameObject.get_pico2d_pos(event) in_rect = GameObject.point_in_rect(mouse_pos, self.get_bb()) if (in_rect): if (self.menu == EXIT): self.left = 400 else: self.left = 300 self.src_rect = (self.left, self.bottom, self.width, self.height) return False
def load_level(level_num): file = open("levels/level" + str(level_num) + ".data", "r") level = Level() for line in file: items = line.split() if len(items) == 0 or line[0] == "#": continue if len(items) == 2 and items[0] == "w": level.level_width = float(items[1]) continue if len(items) == 3: if items[0] == "tg": level.top_goal.x = int(items[1]) level.top_goal.y = 300 - int(items[2]) elif items[0] == "bg": level.bottom_goal.x = int(items[1]) level.bottom_goal.y = 300 + int( items[2]) - level.bottom_goal.height continue if len(items) == 5: if items[0] == "t": level.top_blocks.append( GameObject.GameObject(float(items[1]), 300 - float(items[2]), float(items[3]), float(items[4]), 0)) elif items[0] == "b": level.bottom_blocks.append( GameObject.GameObject( float(items[1]), 300 + float(items[2]) - float(items[4]), float(items[3]), float(items[4]), 0)) elif items[0] == "tb": level.top_blocks.append( GameObject.GameObject(float(items[1]), 300 - float(items[2]), float(items[3]), float(items[4]), 0)) level.bottom_blocks.append( GameObject.GameObject( float(items[1]), 300 + float(items[2]) - float(items[4]), float(items[3]), float(items[4]), 0)) file.close() return level
def __init__(self): super().__init__() self.image = None self.movingObject = None # (index, pos, source) # index: index in hand/characDict # pos: original pos on screen # source is the same as _cursorFocus # 1 player1, 2 player2, 3 board self.movingObjectInfo = None # logic status handler to init UI self.status = None self.cursorImage = None self.cursor = GameObject.GameObject() self.player1Hand = PlayerUI.PlayerUI() self.player2Hand = PlayerUI.PlayerUI() self.boardUI = BoardUI.BoardUI() self._cursorFocus = 0 # 0 lost focus, 1 player1, 2 player2, 3 board self.stateMachine = StateMachine.StateMachine() self.dpos = None
def _CreateProjectile(self, **kwargs): width = 4 height = -12 go = gameObject.GameObject(kwargs["callable"]) go.Type = "Projectile" go.name = kwargs["name"] go.transform.x = kwargs["transform"].x go.transform.y = kwargs["transform"].y go.transform.rotation = kwargs["transform"].rotation go.transform.speed = kwargs["transform"].speed go.transform.rotationSpeed = kwargs["transform"].rotationSpeed if kwargs["playerType"] is PlayerType.player1: go.Render = renderer.Renderer(width, height, None, go.transform, None, Qt.gray, go.Type) if kwargs["playerType"] is PlayerType.player2: go.Render = renderer.Renderer(width, height, None, go.transform, None, Qt.red, go.Type) if kwargs["playerType"] is PlayerType.player3: go.Render = renderer.Renderer(width, height, None, go.transform, None, Qt.green, go.Type) if kwargs["playerType"] is PlayerType.player4: go.Render = renderer.Renderer(width, height, None, go.transform, None, Qt.yellow, go.Type) self.SceneManager.scene.addItem(go.Render) go.Render.moveItem() go.Render.rotateItem() return go
def _CreteAsteroid(self, **kwargs): go = gameObject.GameObject(kwargs["callable"]) go.Type = "Asteroid" go.asteroidType = kwargs["asteroidType"] go.transform = transform.Transform() go.transform.x = kwargs["transform"].x go.transform.y = kwargs["transform"].y go.transform.speed = kwargs["transform"].speed go.transform.rotation = kwargs["transform"].rotation go.transform.rotationSpeed = kwargs["transform"].rotationSpeed if go.asteroidType is AsteroidType.large: go.sound = self.bigAsteroidExplosionSound go.radius = 40 image, path = self.itemFactory.getAsteroid(AsteroidType.large) go.Render = renderer.Renderer(80, 80, path, go.transform, image, None, go.Type) elif go.asteroidType is AsteroidType.medium: go.sound = self.mediumAsteroidExplosionSound go.radius = 25 go.transform.speed += 0.2 image, path = self.itemFactory.getAsteroid(AsteroidType.medium) go.Render = renderer.Renderer(50, 50, path, go.transform, image, None, go.Type) else: go.sound = self.smallAsteroidExplosionSound go.transform.speed += 0.4 go.radius = 15 image, path = self.itemFactory.getAsteroid(AsteroidType.small) go.Render = renderer.Renderer(30, 30, path, go.transform, image, None, go.Type) go.Render.setCacheMode(QGraphicsItem.DeviceCoordinateCache) self.SceneManager.scene.addItem(go.Render) return go
def RunGame(self): frame = Screen.Screen(400, 300, "Space Invaders") frame.Open() frame.GameBorder(4, 200, 150) self.player = GameObject.GameObject(0, -130) self.player.Create("Player") self.enemy1 = GameObject.GameObject(-185, 130) self.enemy1.Create("Enemy") self.bullet = GameObject.GameObject(self.player.player.xcor(), -130) self.bullet.Create("Bullet") frame.frame.listen() frame.frame.onkeypress(self.playerMoveLeft, "Left") frame.frame.onkeypress(self.playerMoveRight, "Right") frame.frame.onkey(self.playerShot, "space") self.GameLoop() frame.frame.mainloop()
def addSpect(cont): own = cont.owner ''' added = GameObject.KX_SpectObject(own.scene.addObject("spectrum")) added.worldPosition = own.worldPosition added.hertz = 2936 added.setup() own.worldPosition.x -= 8 added = GameObject.KX_SpectObject(own.scene.addObject("spectrum")) added.worldPosition = own.worldPosition added.hertz = 632 added.setup() own.worldPosition.x -= 8 added = GameObject.KX_SpectObject(own.scene.addObject("spectrum")) added.worldPosition = own.worldPosition added.hertz = 60 added.setup() own.worldPosition.x -= 8 ''' qzer = [2936, 1500, 632, 100, 40] for i in qzer: added = GameObject.KX_SpectObject(own.scene.addObject("spectrum")) added.worldPosition = own.worldPosition added.hertz = i added.setup() own.worldPosition.x -= 6 cont.activate(cont.actuators['s3'])
def __init__(self, centerPoint, image): GameObject.GameObject.__init__(self, centerPoint, image) """Definiujemy 4 dodatkowe obiekty gry w ramach scianach, ktore beda nam sluzyly jako collidery, po to zeby mozna bylo zniszczyc czesc sciany""" #Zmienne pomocnicze do stworzenie prostokatow x = self.rect.left y = self.rect.top x_off = self.rect.width/4 y_off = self.rect.height/4 self.wallFragments = [] #Tworze prostokaty fragmentow sciany for i in range(4): for j in range(4): rect = pygame.Rect(j*x_off, i*y_off, x_off, y_off) rectImage = pygame.Surface(rect.size).convert() rectImage.blit(self.image, (0,0), rect) self.wallFragments.append(GameObject.GameObject((x+(2*j+1)*x_off/2, y+(2*i+1)*y_off/2), rectImage)) topLeftRect = pygame.Rect(0, 0, x_off, y_off) topRightRect = pygame.Rect(x_off, 0, x_off, y_off) bottomLeftRect = pygame.Rect(0, y_off, x_off, y_off) bottomRightRect = pygame.Rect(x_off, y_off, x_off, y_off)
def place_objects(self, room): #choose random number of monsters num_monsters = randint(0, MAX_ROOM_MONSTERS) for i in range(num_monsters): #choose random spot for this monster x = randint(room.x1, room.x2) y = randint(room.y1, room.y2) if randint(0, 100) < 80: #80% chance of getting an orc #create an orc monster = GameObject(x, y, 'o', (66, 134, 244)) else: #create a troll monster = GameObject(x, y, 'T', (187, 65, 244)) objects.append(monster)
def loop(): gameobj = GameObject.GameObject() while not gameobj.close: gameobj.update() gameobj.draw() pygame.display.update(screenRect) clock.tick()
def initPlayer(data): w, h = data.width, data.height # 2 player controlled circles data.player1 = GameObject.Player( ("Left", "Right"), data.ui.playerAMaxRadius, data.ui.ballAColor, 1, w, h) data.player2 = GameObject.Player(("Up", "Down"), data.ui.playerBMaxRadius, data.ui.ballBColor, 2, w, h) # Player background data.player1Pad = GameObject.DirectionPad(data.ui.ballBgColor, data.ui.ballBgRadius + 2, 1, w, h) data.player2Pad = GameObject.DirectionPad(data.ui.ballBgColor, data.ui.ballBgRadius + 2, 2, w, h) getPlayerControlDirections(data)
def addGameObject(self, gameObject: GameObject) -> None: if gameObject['type'] == 'GameObjectType_Card': if gameObject['zoneId'] == self.zoneId('Battlefield'): if 'CardType_Creature' in gameObject['cardTypes']: return Creature(gameObject) else: return Card(gameObject) else: return Card(gameObject) else: return GameObject(gameObject)
def main(): test = False for i in range(1, len(sys.argv)): print sys.argv[i] if sys.argv[i] == "--test-install": test = True print "Test" if test: gameManager = GameManager.GameManager(GameObject.GameObject(None), 30, None, None, True) else: #try: handler = ButtonHandler.ButtonHandler() piFaceManager = PiFaceManager.PiFaceManager(handler) gameManager = GameManager.GameManager(GameObject.GameObject(None), 30, handler, piFaceManager) gameObject = GameObject.LoaderGameObject(None) gameManager.setCurrentGameObject(gameObject) gameManager.run() piFaceManager.deactivate()
def check_collision(): global TOTAL_COIN_COUNT global mario for coin in GameWorld.objects_at(GameWorld.layer.coin): if GameObject.collides_box(mario, coin): GameWorld.remove(coin) TOTAL_COIN_COUNT -= 1 coin_wav.play() for obstacle in GameWorld.objects_at(GameWorld.layer.obstacle): if GameObject.collides_box(mario, obstacle): mario.is_collide = True break for plant in GameWorld.objects_at(GameWorld.layer.plant): if GameObject.collides_box(mario, plant): mario.is_collide = True break #for box in GameWorld.objects_at(GameWorld.layer.box): # if GameObject.collides_box(mario, box): # box.is_collide = True # else: # box.is_collide = False for obstacle in GameWorld.objects_at(GameWorld.layer.obstacle): if ("Stone" in obstacle.name): for plant in GameWorld.objects_at(GameWorld.layer.plant): if GameObject.collides_box(obstacle, plant): GameWorld.remove(obstacle) plant.state = GameSprite.Plant.DIE plant_dead_wav.play() return for box in GameWorld.objects_at(GameWorld.layer.box): if GameObject.collides_box(obstacle, box): GameWorld.remove(obstacle) GameWorld.remove(box) ladder = GameSprite.Platform("Ladder_1", 740, 430, 39, 170) GameWorld.add(GameWorld.layer.platform, ladder, 3) return
def initLogsInRow(self, row, bigLogs = False, croc = False, logSpeed = 2): startLogs = self.num_logs if croc: # startLogs -= 1 self.croc.speed = logSpeed if not bigLogs: crocX = 0 crocY = 0 for i in range(startLogs): log = GameObject("images/log_big.png") log.image.set_colorkey((0, 0, 0)) x = self.width / 2 - i * LOG_MARGIN - row * 10 y = self.getYforRow(row) log.setPos(x, y) log.speed = logSpeed self.logs.append(log) if i == startLogs - 1: crocX = self.width / 2 - startLogs * LOG_MARGIN - row * 10 crocY = y self.croc.body_rect.left = crocX self.croc.body_rect.top = crocY self.croc.head_rect.left = crocX + 80 self.croc.head_rect.top = crocY self.croc_in_level = True else: for i in range(self.num_logs - 1): log = GameObject("images/log_bigger.png") c = log.image.get_at((0, 0)) log.image.set_colorkey(c) x = self.width / 2 - i * (LOG_MARGIN + log.rect.width) - i * LOG_MARGIN y = self.getYforRow(row) log.setPos(x, y) log.speed = logSpeed - 1 self.logs.append(log)
def __init__(self): super().__init__() self.image = None self.characterUIPool = [CharacterUI.CharacterUI() for i in range(10)] self.movingObject = None self.cursorImage = None self.cursor = GameObject.GameObject() self.boardUI = BoardUI.BoardUI() self.dpos = None
def __init__(self): self.level_width = 0 self.top_goal = GameObject.GameObject(0, 0, 25, 50, 2) self.bottom_goal = GameObject.GameObject(0, 0, 25, 50, 2) self.top_blocks = [] self.bottom_blocks = [] self.top_blocks.append(GameObject.GameObject(0, 300, 800, 300, 0)) self.top_blocks.append(GameObject.GameObject(0, -200, 0, 500, 0)) self.top_blocks.append(GameObject.GameObject(800, -200, 0, 500, 0)) self.bottom_blocks.append(GameObject.GameObject(0, 0, 800, 300, 0)) self.bottom_blocks.append(GameObject.GameObject(0, 300, 0, 500, 0)) self.bottom_blocks.append(GameObject.GameObject(800, 300, 0, 500, 0))
def __init__(self): super().__init__() self.image = None self.movingObject = None # (index, pos) self.movingObjectInfo = None self.cursorImage = None self.cursor = GameObject.GameObject() self.boardUI = BoardUI.BoardUI() self.dpos = None
def __init__(self): super().__init__() self.image = None self.movingObject = None # (index, pos, source) # index: index in hand/characDict # pos: original pos on screen # source is the same as _cursorFocus # 1 player1, 2 player2, 3 board self.movingObjectInfo = None self.status = None # testObject = GameObject.GameObject() self.cursorImage = None self.cursor = GameObject.GameObject() self.player1Hand = PlayerUI.PlayerUI() self.player2Hand = PlayerUI.PlayerUI() self.boardUI = BoardUI.BoardUI() self.indicator = RangeIndicator.RangeIndicator() self._cursorFocus = 0 # 0 lost focus, 1 player1, 2 player2, 3 board self.waitForAttackOpt = False self.waitForAttackCharacPos = None self.waitForAttackCharacRange = None self.bufferOpt = None self.bufferCharac = None dpos = None self.battleBg = GameObject.GameObject() self.turnEndButton = GameObject.GameObject() self.pauseGameButton = GameObject.GameObject()
def hit(self, particle): if particle.parent.name == 'Player': if self.currentTime < self.times: i = -5 while self.numberOfEnemy > 0: e = go.Enemy(self.x + i * 100, self.y - 1000 - random.randint(-200, 200), playerSize[0], playerSize[1], self.env.player, self.env) self.numberOfEnemy -= 1 i += 1 self.currentTime += 1 self.isHit = True
def __init__(self, size): # Initializes pygame pygame.init() # Initializes game variables self.DEBUG = False self.vehicles = [] # Initializes screen self.screen = pygame.display.set_mode(size) self.screen_size = size # Sets screen title pygame.display.set_caption("Roads of Code") # Initializes time variables self.last_time = 0 self.dt_multiplier = 1 self.dt_mult_pace = 0.25 self.dt_step = False self.dt_manual = 0.25 # Creates running flag self.run = True # Creates mouse object self.mouse = GameObject(pygame.image.load("../img/dot.png")) # Creates tracked objects dict self.tracked_objects = {'vehicles': self.vehicles, 'mouse': self.mouse} # Initializes single vehicle position = Vector2(self.screen_size[0] / 2, self.screen_size[1] / 2) vehicle = Camaro(position, debug=self.DEBUG) vehicle.set_velocity(Vector2(0, 0)) vehicle.set_accel(Vector2(0, 0)) self.vehicles.append(vehicle)
def __init__(self): snake = Snake("snake") global snake food = go.Object("food") global food Game.__init__(self) #self.gameover = False self.direction = [-1,0] self.score = 0 self.add_object(snake) self.add_object(food) self.isPause = False self.frame = 0.1 self.foodpos = [] self.instance_food()
def instance_food(self): food.pixels = [] random.seed(int(time.time())) temppos = [random.randrange(self.cols-1),random.randrange(self.rows-1)] #if self.foodpos == temppos: # self.foodpos = instance_food() #else: # self.foodpos = temppos while self.foodpos == temppos: random.seed(int(time.time())) temppos = [random.randrange(self.cols-1),random.randrange(self.rows-1)] self.foodpos = temppos food.add_pixel([go.pixel(self.foodpos)]) self.iseaten = False return 0
def initCarRow(self, row, width, startX, direction = 0, offset = 0, speed = 0): for i in range(4): car = GameObject("images/car_sprites_big.png") car.clips = [] car.image.set_colorkey((0, 0, 0)) # main clip car.clips.append(Rect(startX, 0, width, 35)) car.setPos(i * 150 + offset, self.getYforRow(row)) if direction == 0: car.speed = self.carSpeed else: car.speed = -self.carSpeed if speed != 0: car.speed = speed self.cars.append(car)
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)
class MainGame(object): # Creates and initializes all member # variables 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) # Returns whether or not the game is # ready to return to the menu def is_over(self): return self.back_to_menu # Returns whether or not the game is paused def is_paused(self): return self.paused # Starts the timer and plays the background # music def startGame(self): self.background_music.play(-1) self.timer.start() # stops the background music def endGame(self): self.background_music.stop() def __init__(self, w, h): self.initVars() self.width = w self.height = h self.timeRemainingRect.left = self.width / 2 - self.timeRemainingRect.width / 2 - 20 self.initializeElements() # Used to kill the current frog # Plays a death animation depending on # the method of death def killFrog(self): self.frogs[0].is_alive = False if not self.frogs[0].died_by_water: self.frogs[0].dead_sound.play() else: self.frogs[0].splash_sound.play() self.frogs[0].dead_time = pygame.time.get_ticks() self.frog_died = True self.frog_won = False # Creates the game objects (cars, turtles, etc) # based on the level def initializeElements(self): self.cars = [] self.logs = [] self.frogs = [] self.winning_frogs = [] self.dead_frogs = [] self.turtles = [] self.frog_died = False self.frog_won = False # Create the frogs self.initFrogs() if self.level == 1: # Create the cars self.initCarRow(2, 40, 0, 0, 10) self.initCarRow(3, 40, 60, 0, -5) self.initCarRow(4, 70, 126, 1, -20) self.initCarRow(5, 40, 220, 1, 45) self.initCarRow(6, 40, 280, 0, 20) self.initTurlesInRow(8, 3) self.initTurlesInRow(12, 3) self.initLogsInRow(9) self.initLogsInRow(10, True) self.initLogsInRow(11) elif self.level == 2: # Create the cars self.initCarRow(2, 40, 0, 0, 10) self.initCarRow(3, 40, 60, 0, -5) self.initCarRow(4, 70, 126, 1, -20) self.initCarRow(5, 40, 220, 1, 45) self.initCarRow(6, 40, 280, 0, 20) self.initTurlesInRow(8, 3) self.initTurlesInRow(11, 3) self.initLogsInRow(9) self.initLogsInRow(10, True) self.initLogsInRow(12, False, True) elif self.level == 3: # Create the cars self.initCarRow(2, 40, 0, 0, 10) self.initCarRow(3, 40, 60, 0, -5, 2) self.initCarRow(4, 70, 126, 1, -20) self.initCarRow(5, 40, 220, 1, 45) self.initCarRow(6, 40, 280, 0, 20, 2) self.initTurlesInRow(8, 3) self.initTurlesInRow(11, 3) self.initLogsInRow(9, False, True, 3) self.initLogsInRow(10, True) self.initLogsInRow(12, False, True, 3) self.initGoalRects() # Creates the rectangles for the goals def initGoalRects(self): r = Rect(24, 80, 33, 34) self.goalRects.append(r) r = Rect(144, 80, 33, 34) self.goalRects.append(r) r = Rect(264, 80, 33, 34) self.goalRects.append(r) r = Rect(384, 80, 33, 34) self.goalRects.append(r) r = Rect(504, 80, 33, 34) self.goalRects.append(r) # Creates 10 frogs def initFrogs(self): for i in range(NUM_FROGS): frog = Frog(os.path.join('images', "frog_sprites_big.png")) frog.image.set_colorkey((0, 0, 0)) # standing frog.clips.append(Rect(120, 0, 35, 26)) # mid-jump frog.clips.append(Rect(62, 0, 26, 35)) # full jump frog.clips.append(Rect(0, 0, 30, 33)) frog.explosion_clips.append(Rect(114, 0, 41, 40)) frog.explosion_clips.append(Rect(56 , 0, 41, 40)) frog.explosion_clips.append(Rect(0 , 0, 41, 40)) frog.setPos(self.width / 2 - 30, self.height - 95) self.frogs.append(frog) # Creates turtles positioned in a certain row def initTurlesInRow(self, row, perGroup, groups = 3): rand_group = random.randrange(groups) # create turtles in eighth row for i in range(groups): x = ((groups + 5) * 40) + (turtle_group_margin * i) y = self.getYforRow(row) for j in range(perGroup): turtle = Turtle("images/turtle_sprites_big.png") turtle.image.set_colorkey((0, 0, 0)) if i == rand_group: turtle.goes_under_water = True # main turtle.clips.append(Rect(0, 0, 32, 35)) # swimming half turtle.clips.append(Rect(56, 0, 40, 35)) # swimming full turtle.clips.append(Rect(116, 0, 40, 35)) # underwater half turtle.clips.append(Rect(204, 0, 35, 35)) # underwater full turtle.clips.append(Rect(260, 0, 35, 35)) turtle.speed = -1 turtle.setPos(x + turtle.clips[1].width * j + 5, y) self.turtles.append(turtle) # Creates logs (big or small) positioned in a certain row # A crocodile could also be added to the row if "croc" is true def initLogsInRow(self, row, bigLogs = False, croc = False, logSpeed = 2): startLogs = self.num_logs if croc: # startLogs -= 1 self.croc.speed = logSpeed if not bigLogs: crocX = 0 crocY = 0 for i in range(startLogs): log = GameObject("images/log_big.png") log.image.set_colorkey((0, 0, 0)) x = self.width / 2 - i * LOG_MARGIN - row * 10 y = self.getYforRow(row) log.setPos(x, y) log.speed = logSpeed self.logs.append(log) if i == startLogs - 1: crocX = self.width / 2 - startLogs * LOG_MARGIN - row * 10 crocY = y self.croc.body_rect.left = crocX self.croc.body_rect.top = crocY self.croc.head_rect.left = crocX + 80 self.croc.head_rect.top = crocY self.croc_in_level = True else: for i in range(self.num_logs - 1): log = GameObject("images/log_bigger.png") c = log.image.get_at((0, 0)) log.image.set_colorkey(c) x = self.width / 2 - i * (LOG_MARGIN + log.rect.width) - i * LOG_MARGIN y = self.getYforRow(row) log.setPos(x, y) log.speed = logSpeed - 1 self.logs.append(log) # Creates a car in a certain row # The specific car is determined by using the startx and width # variables with an offset def initCarRow(self, row, width, startX, direction = 0, offset = 0, speed = 0): for i in range(4): car = GameObject("images/car_sprites_big.png") car.clips = [] car.image.set_colorkey((0, 0, 0)) # main clip car.clips.append(Rect(startX, 0, width, 35)) car.setPos(i * 150 + offset, self.getYforRow(row)) if direction == 0: car.speed = self.carSpeed else: car.speed = -self.carSpeed if speed != 0: car.speed = speed self.cars.append(car) # Moves all game objects def moveObjects(self): # Move the cars for car in self.cars: if car.speed == 0: car.speed = -self.carSpeed car.move(car.speed, 0) # Checks if a leftbound car goes out of the screen if car.rect.right <= -1 and car.speed < 0: car.rect.left = self.width + 150 # Checks if a rightbound car goes out of the screen elif car.rect.left >= self.width and car.speed > 0: car.rect.left = -150 if len(self.frogs) >= 1: # Check if a car hit the frog if self.frogs[0].rect.colliderect(car.rect) and self.frogs[0].is_alive: # The frog is dead. -1 life self.killFrog() carHitFrog = True # Move the logs frogOnObject = False frogSpeed = 0 for log in self.logs: log.move(log.speed, 0) # Checks if a log has gone out of the screen if log.rect.left > self.width: log.rect.left = -LOG_MARGIN - log.rect.width # Checks if the frog is on a log if len(self.frogs) >= 1: if self.frogs[0].rect.colliderect(log.rect): frogOnObject = True self.frogs[0].horiz_speed = log.speed # Move the turtles frogFellInWater = False for turtle in self.turtles: turtle.move(turtle.speed, 0) # Animates the turtles turtle.update(pygame.time.get_ticks()) # Checks if a turtle went off the screen if turtle.rect.right < 0: turtle.rect.left = self.width + 10 if len(self.frogs) >= 1: # Check if the frog is on a turtle if self.frogs[0].rect.colliderect(turtle.rect): if not turtle.is_under_water: frogOnObject = True self.frogs[0].horiz_speed = turtle.speed elif not frogFellInWater: self.frogs[0].died_by_water = True self.killFrog() frogFellInWater = True if self.croc_in_level: # Animates the crocodile self.croc.update(pygame.time.get_ticks()) self.croc.move(self.croc.speed, 0) # Checks if the crocodile goes off the screen if self.croc.body_rect.left > self.width: self.croc.body_rect.left = self.logs[-1].rect.left - LOG_MARGIN self.croc.head_rect.left = self.logs[-1].rect.left - LOG_MARGIN + 80 # Checks if the frog is on the crocodile if self.croc.body_rect.colliderect(self.frogs[0].rect) and \ not self.croc.head_rect.colliderect(self.frogs[0].rect): self.frogs[0].horiz_speed = self.croc.speed frogOnObject = True frogOnCroc = True # Checks if the frog is on the crocodile's # head. If so, the frog dies elif self.croc.head_rect.colliderect(self.frogs[0].rect) \ and self.croc.biting: self.killFrog() # If a frog is on a log or turtle, move the frog with it if frogOnObject and self.frogs[0].is_alive: self.frogs[0].move(self.frogs[0].horiz_speed, 0) # Check if the frog has gone out of bounds. # If so, the frog dies if self.frogs[0].rect.right < 0 or self.frogs[0].rect.left > self.width: self.killFrog() def placePowerups(self): # Place the fly in a goal every 12 seconds if self.fly_appear_timer.get_seconds() == 0 and not self.fly_shown: self.fly_timer.start() # place the fly in a random goal rectangle r = self.goalRects[random.randrange(len(self.goalRects))] # check if the rectangle picked is already taken up unoccupied = True for i in self.winning_frogs: if i.rect.colliderect(r): unoccupied = False # Place the fly in a goal that is not # taken up by a frog while not unoccupied: unoccupied = True r = self.goalRects[random.randrange(len(self.goalRects))] for i in self.winning_frogs: if i.rect.colliderect(r): unoccupied = False # Place the fly and tell draw() to draw it self.fly.rect.left = r.left + 2 self.fly.rect.top = r.top + 2 self.fly_shown = True # Hide the fly 6 seconds after being shown elif self.fly_timer.get_seconds() == 0 and self.fly_shown: self.fly_shown = False self.fly_appear_timer.reset() # Checks if the game is over, # Changes the timer, # Toggles the fly # Handles other logic def play(self): if not self.fly_appear_timer.is_started(): self.fly_appear_timer.start() # End the game if the player is out of lives if self.lives == 0: self.message = "Game over. You need more practice." self.messageSurface = self.font.render(self.message, True, (255, 255, 255)) self.game_over = True if self.game_over_time == 0: self.game_over_time = pygame.time.get_ticks() self.timer.toggle_pause() # End the game if the level limit has been reached if self.level >= MAX_LEVELS: self.game_over = True self.message = "For more levels, send $10 to [email protected]" self.messageSurface = self.font.render(self.message, True, (255, 255, 255)) if self.game_over_time == 0: self.game_over_time = pygame.time.get_ticks() self.timeSinceNew = self.timer.get_seconds() # Check if the timer ran out if self.timeSinceNew == 0: # frog will die, new one spawn self.killFrog() self.timer.reset() pass if len(self.frogs) > 0: # Play the frog's animation if it's jumping if self.frogs[0].jumping or self.frogs[0].died_by_water: self.frogs[0].update(pygame.time.get_ticks()) if self.frogs[0].current_clip == self.frogs[0].max_frames - 1: # self.frogs[0].reset_jump_flags() self.frogs[0].jumping = False self.moveObjects() self.placePowerups() # Helper function. # Calculates the starting y value for a row def getYforRow(self, row): return self.height - MARGIN_FROM_HUD - row * LANE_HEIGHT # Draw the objects for this game mode def draw(self): pygame.display.get_surface().blit(self.background, (0, 60)) # create UI surfaces self.levelSurface = self.font.render("Level " + str(self.level), True, (155, 255, 155)) self.timeRemainingSurface = self.font.render(str(self.timeSinceNew), True, (155, 255, 155)) self.scoreSurface = self.font.render("Score: " + str(self.score), True, (155, 255, 155)) # adjust bar rect width self.timeRemainingRect.w = (BARWIDTH / FROG_LIFE) * self.timeSinceNew # draw UI surfaces pygame.display.get_surface().blit(self.levelSurface, (self.width / 2 + 170, 10)) pygame.display.get_surface().blit(self.timeRemainingSurface, (self.width / 2 - BARWIDTH + 50, 10)) pygame.display.get_surface().blit(self.scoreSurface, (10, self.height - 42)) pygame.draw.rect(pygame.display.get_surface(), (155, 255, 155), self.timeRemainingRect) for turtle in self.turtles: turtle.draw() for log in self.logs: log.draw() if self.fly_shown: self.fly.draw() if self.croc_in_level: self.croc.draw() if len(self.frogs) >= 1 and self.lives > 0: if self.frogs[0].is_alive: self.frogs[0].draw() else: self.frogs[0].drawDead() # Wait 1 second to spawn a new frog if pygame.time.get_ticks() - self.frogs[0].dead_time >= 1000: self.dead_frogs.append(self.frogs[0]) self.frogs = self.frogs[1:] self.frog_death_time = 0 self.lives -= 1 self.timer.reset() for car in self.cars: car.draw() for i in range(self.lives): x = self.width - 50 - (i * 40) - (10 * i) y = self.height - 50 pygame.display.get_surface().blit(self.liveSurface, (x, y)) for frog in self.winning_frogs: frog.draw() if self.level_complete or self.game_over or self.paused: pygame.display.get_surface().blit(self.messageSurface, (self.width / 2 - self.messageSurface.get_rect().width / 2, self.height / 2 - self.messageSurface.get_rect().height / 2)) if self.level_complete and pygame.time.get_ticks() - self.level_complete_time >= 3000: self.level_complete = False self.game_over = False self.level_complete_time += 3000 self.level += 1 self.initializeElements() self.timer.reset() if self.game_over and pygame.time.get_ticks() - self.game_over_time >= 3000: self.back_to_menu = True # Checks whether or not the frog is in the # water def frogInWater(self): on_float = False for turtle in self.turtles: if self.frogs[0].rect.colliderect(turtle.rect): on_float = True for log in self.logs: if self.frogs[0].rect.colliderect(log.rect): on_float = True if self.croc_in_level: if self.frogs[0].rect.colliderect(self.croc.body_rect) \ or self.frogs[0].rect.colliderect(self.croc.head_rect): on_float = True return not on_float # Handle input for this game mode def handleInput(self, event): moved = False alive = False # The y value of the first row of water y = self.getYforRow(7) goal_y = self.getYforRow(12) if event.type == KEYDOWN: if event.key == K_UP and self.frogs[0].is_alive: # Keep the frog in-bounds if self.frogs[0].rect.top - LANE_HEIGHT > 60: self.frogs[0].jump_time = pygame.time.get_ticks() self.frogs[0].rect.top -= LANE_HEIGHT self.frogs[0].jumping_right = False self.frogs[0].jumping_left = False self.frogs[0].jumping_down = False self.frogs[0].jumping_up = True # Check if the frog is between the water and the goal # rows if self.frogs[0].rect.top <= y and self.frogs[0].rect.top > goal_y: alive = not self.frogInWater() else: alive = True moved = True if self.frogs[0].rect.top <= goal_y: frogInRect = False # Loop through goal rects for r in self.goalRects: # Get center of rect r_center = [(r.left + r.right) / 2.0, (r.top + r.bottom) / 2.0] # Get center of frog rect # print "frogs:", len(self.frogs) f_center = [(self.frogs[0].rect.left + self.frogs[0].rect.right) / 2.0, (self.frogs[0].rect.top + self.frogs[0].rect.bottom) / 2.0] # Get the distance between the two centers distance = ((f_center[0] - r_center[0]) ** 2 + (f_center[1] - r_center[1]) ** 2) ** 0.5 if distance < self.frogs[0].rect.width / 2: spaceTaken = False # Check winning frog rects to see if they collide with goal rects for f in self.winning_frogs: if r.colliderect(f.rect): spaceTaken = True if not spaceTaken: self.frog_win_sound.play() frogInRect = True # The frog made it to the jump frog = Frog() frog.setImage(pygame.image.load("images/safe_frog_big.png").subsurface(Rect(0, 0, 40, 35))) frog.image.set_colorkey((0, 0, 0)) frog.setPos(r.left - 4, r.top) frog.winning_time = pygame.time.get_ticks() self.winning_frogs.append(frog) if self.fly.rect.colliderect(frog.rect) and self.fly_shown: self.score += 100 self.frog_won = True self.frog_died = False if len(self.frogs) > 1: self.frogs = self.frogs[1:] self.score += 200 # Level complete if len(self.winning_frogs) == 5: if self.level + 1 <= MAX_LEVELS: self.level_complete = True self.level_complete_time = pygame.time.get_ticks() self.message = "Level complete" self.messageSurface = self.font.render(self.message, True, (255, 255, 255)) else: self.timer.reset() # If a frog was already in the goal space if not frogInRect: self.killFrog() if alive: self.score += 10 moved = True else: self.frogs[0].died_by_water = True self.killFrog() if event.key == K_DOWN and self.frogs[0].is_alive: # Keep the frog in-bounds if self.frogs[0].rect.top + LANE_HEIGHT < self.height - 60: self.frogs[0].jump_time = pygame.time.get_ticks() self.frogs[0].rect.top += LANE_HEIGHT self.frogs[0].jumping_right = False self.frogs[0].jumping_left = False self.frogs[0].jumping_down = True self.frogs[0].jumping_up = False if self.frogs[0].rect.top <= y: alive = not self.frogInWater() else: alive = True moved = True if alive: self.score += 10 moved = True else: self.frogs[0].died_by_water = True self.killFrog() if event.key == K_LEFT and self.frogs[0].is_alive: w = FROG_HORIZ_JUMP # Keep the frog in-bounds if self.frogs[0].rect.left - w > 0: self.frogs[0].jump_time = pygame.time.get_ticks() self.frogs[0].rect.left -= w self.frogs[0].jumping_right = False self.frogs[0].jumping_left = True self.frogs[0].jumping_down = False self.frogs[0].jumping_up = False if self.frogs[0].rect.top <= y: alive = not self.frogInWater() else: alive = True if alive: moved = True else: self.frogs[0].died_by_water = True self.killFrog() if event.key == K_RIGHT and self.frogs[0].is_alive: w = FROG_HORIZ_JUMP # Keep the frogs in-bounds if self.frogs[0].rect.right + w < self.width: self.frogs[0].jump_time = pygame.time.get_ticks() self.frogs[0].rect.left += w self.frogs[0].jumping_right = True self.frogs[0].jumping_left = False self.frogs[0].jumping_down = False self.frogs[0].jumping_up = False y = self.height - MARGIN_FROM_HUD - 7 * LANE_HEIGHT alive = False if self.frogs[0].rect.top <= y: alive = not self.frogInWater() else: alive = True if alive: moved = True else: self.frogs[0].died_by_water = True self.killFrog() if event.key == K_p: self.timer.toggle_pause() if not self.paused: self.paused = True self.message = "Paused" self.messageSurface = self.font.render(self.message, True, (255, 255, 255)) else: self.paused = False if moved: self.frogs[0].jump_sound.play() self.frogs[0].jumping = True
def run(self): femaleLock.naFila = femaleLock.naFila + 1 test = GameObject((0, 100), (100, 100), testTex2) test.changeDestination((self.threadID%5)*40,100) if maleLock.naFila > 0 and femaleLock.consecutive > 5: femaleLock.consecutive = 0 femaleTurnstile.clear() femaleTurnstile.wait() femaleLock.consecutive = femaleLock.consecutive + 1 femaleLock.counter = femaleLock.counter+1 while femaleLock.status == 'False': femaleLock.changeStatus() while femaleLock.lastIn + 1 != self.threadID: time.sleep(0) femaleLock.lastIn = femaleLock.lastIn + 1 femaleMultiplex.acquire() print "Mulher %d entrou no banheiro" %(self.threadID) femaleLock.insideCounter = femaleLock.insideCounter + 1 femaleLock.naFila = femaleLock.naFila - 1 test.changeDestination(180,100) time.sleep(3-(self.threadID%3)/2) test.changeDestination((self.threadID%3)*40+150,20) time.sleep(5) femaleLock.insideCounter = femaleLock.insideCounter - 1 print "Mulher %d saiu do banheiro" %(self.threadID) femaleLock.counter = femaleLock.counter-1 if femaleLock.counter == 0: maleTurnstile.set() femaleLock.changeStatus() femaleMultiplex.release() test.changeDestination(200,400) time.sleep(12) test.kill()
screen = pygame.display.set_mode(screen_size, pygame.HWSURFACE, bpp) laser_shot_sfx = mixer.Sound("../Assets/laser_shot.wav") enemy_laser_sfx = mixer.Sound("../Assets/laser_shot_2.wav") hit_sfx = mixer.Sound("../Assets/hit.wav") laser_shot_sfx.set_volume(0.1) hit_sfx.set_volume(0.4) enemy_laser_sfx.set_volume(0.5) all_game_objects = list() ######################################################################################## # MAKE THE PLAYER player = GameObject() player.position.x = screen_size[0]/2.0 player.position.y = screen_size[1]/2.0 player.color = (255, 0, 0) player.boundingBox = Rect(player.position.to_tuple(), (12, 12)) all_game_objects.append(player) # Motion variables player_accel = 500.0 player_friction = 0.95 player_thrust_interval = 0.05 player_thrust_timer = 0.0 player_firing_interval = 0.1 player_firing_timer = 0.0
class World(ShowBase): # CONDISER: change to DirectObject/FSM 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() ##== Utility and World Initialization functions =============================## def loadJournal(self,journalMgr,journalFile): f = open(Filename(journalFile).toOsSpecific()) doc = xml.dom.minidom.parse(f) root = doc.childNodes[0] for n in root.childNodes: if n.localName == "journalEntries": journalMgr.decode(n) f.close() def getModelHeight(self, model): min, max = Point3(), Point3() model.calcTightBounds(min, max) return max.getZ() - min.getZ() def createLoadScreen(self, imageFile='./LEGameAssets/Textures/load_screen.png'): self.loadScreen = OnscreenImage(image=imageFile) aspect2d.hide() self.loadScreen.reparentTo(render2d) if(hasattr(self, "gameplayUI")): self.gameplayUI.hideAll() def destroyLoadScreen(self): self.loadBar.hide() self.loadScreen.detachNode() self.loadScreen.destroy() aspect2d.show() self.ignore('enter') self.gameplayUI.showAll() for name, gameObj in self.gameObjects.iteritems(): gameObj.callTrigger(self, 'LE-trigger-onScene') def startLoadBar(self, range=100): self.loadBar.show() self.loadBar['range'] = range self.loadBar['value'] = 0 base.graphicsEngine.renderFrame() def increaseLoadBar(self, value): self.loadBar['value'] += value base.graphicsEngine.renderFrame() ##== Collisions =============================================================## def setupCollisions(self): self.cTrav = CollisionTraverser('mainTraverser') self.cTrav.setRespectPrevTransform(True) # Line collider for setting hero height based on ground geometry heroLine = CollisionNode('heroLine') heroLine.addSolid(CollisionRay(Point3(0,0,self.heroHeight), Vec3(0,0,-1))) heroLine.setFromCollideMask(BITMASK_GROUND) heroLine.setIntoCollideMask(BitMask32.allOff()) self.heroGroundCollide = render.attachNewNode(heroLine) self.heroGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.heroGroundCollide, self.heroGroundHandler) # cameraSphere = CollisionNode('cameraSphere') # cameraSphere.addSolid(CollisionSphere(0,0,0,10)) # cameraSphere.setFromCollideMask(BITMASK_CAMERA) # cameraSphere.setIntoCollideMask(BitMask32.allOff()) # self.cameraSphereCollide = self.cam.attachNewNode(cameraSphere) # self.cameraSphereQueue = CollisionHandlerQueue() # self.cTrav.addCollider(self.cameraSphereCollide, self.cameraSphereQueue) self.herowallcollision = False self.heroWallCollideX = render.attachNewNode("heroWallX") self.heroWallCollideY = render.attachNewNode("heroWallY") self.heroWallCollideZ = render.attachNewNode("heroWallZ") # Line collider for running into obstacles and walls in X direction heroLineX = CollisionNode('heroLineX') heroLineX.addSolid(CollisionRay(Point3(0,0,0), Vec3(0,0,1))) self.heroWallCollideLineX = self.heroWallCollideX.attachNewNode(heroLineX) self.heroWallCollideLineX.node().setFromCollideMask(BITMASK_WALL_TERRAIN) self.heroWallCollideLineX.node().setIntoCollideMask(BitMask32.allOff()) self.heroWallQueueX = CollisionHandlerQueue() self.cTrav.addCollider(self.heroWallCollideLineX, self.heroWallQueueX) # Line collider for running into obstacles and walls in Y direction heroLineY = CollisionNode('heroLineY') heroLineY.addSolid(CollisionRay(Point3(0,0,0), Vec3(0,0,1))) self.heroWallCollideLineY = self.heroWallCollideY.attachNewNode(heroLineY) self.heroWallCollideLineY.node().setFromCollideMask(BITMASK_WALL_TERRAIN) self.heroWallCollideLineY.node().setIntoCollideMask(BitMask32.allOff()) self.heroWallQueueY = CollisionHandlerQueue() self.cTrav.addCollider(self.heroWallCollideLineY, self.heroWallQueueY) # Line collider for running into obstacles and walls in Z direction heroLineZ = CollisionNode('heroLineZ') heroLineZ.addSolid(CollisionRay(Point3(0,0,0), Vec3(0,0,1))) self.heroWallCollideLineZ = self.heroWallCollideZ.attachNewNode(heroLineZ) self.heroWallCollideLineZ.node().setFromCollideMask(BITMASK_WALL_TERRAIN) self.heroWallCollideLineZ.node().setIntoCollideMask(BitMask32.allOff()) self.heroWallQueueZ = CollisionHandlerQueue() self.cTrav.addCollider(self.heroWallCollideLineZ, self.heroWallQueueZ) # # Sphere collider for running into obstacles and walls # heroSphere = CollisionNode('heroSphere') # heroSphere.addSolid(CollisionSphere(0,0,0,7)) # self.heroWallCollide = render.attachNewNode(heroSphere) # self.heroWallCollide.node().setFromCollideMask(BITMASK_WALL) # self.heroWallCollide.node().setIntoCollideMask(BitMask32.allOff()) # self.heroWallQueue = CollisionHandlerQueue() # self.cTrav.addCollider(self.heroWallCollide, self.heroWallQueue) # self.herowallcollision = False # Sphere collider for running into obstacles and walls in X direction heroSphereX = CollisionNode('heroSphereX') heroSphereX.addSolid(CollisionSphere(0,0,0,7)) self.heroWallCollideSphereX = self.heroWallCollideX.attachNewNode(heroSphereX) self.heroWallCollideSphereX.node().setFromCollideMask(BITMASK_WALL) self.heroWallCollideSphereX.node().setIntoCollideMask(BitMask32.allOff()) #self.heroWallQueueX = CollisionHandlerQueue() self.cTrav.addCollider(self.heroWallCollideSphereX, self.heroWallQueueX) self.herowallcollision = False # Sphere collider for running into obstacles and walls in Y direction heroSphereY = CollisionNode('heroSphereY') heroSphereY.addSolid(CollisionSphere(0,0,0,7)) self.heroWallCollideSphereY = self.heroWallCollideY.attachNewNode(heroSphereY) self.heroWallCollideSphereY.node().setFromCollideMask(BITMASK_WALL) self.heroWallCollideSphereY.node().setIntoCollideMask(BitMask32.allOff()) #self.heroWallQueueY = CollisionHandlerQueue() self.cTrav.addCollider(self.heroWallCollideSphereY, self.heroWallQueueY) # Sphere collider for running into obstacles and walls in Z direction heroSphereZ = CollisionNode('heroSphereZ') heroSphereZ.addSolid(CollisionSphere(0,0,0,7)) self.heroWallCollideSphereZ = self.heroWallCollideZ.attachNewNode(heroSphereZ) self.heroWallCollideSphereZ.node().setFromCollideMask(BITMASK_WALL) self.heroWallCollideSphereZ.node().setIntoCollideMask(BitMask32.allOff()) #self.heroWallQueueZ = CollisionHandlerQueue() self.cTrav.addCollider(self.heroWallCollideSphereZ, self.heroWallQueueZ) # Ray collider for clicking on objects in the game self.pickerCollisionQueue = CollisionHandlerQueue() self.pickerCN = CollisionNode('pickerRayCN') self.pickerCNP = self.cam.attachNewNode(self.pickerCN) self.pickerCN.setFromCollideMask(BITMASK_CLICK) self.pickerCN.setIntoCollideMask(BitMask32.allOff()) self.pickerRay = CollisionRay() self.pickerCN.addSolid(self.pickerRay) self.cTrav.addCollider(self.pickerCNP, self.pickerCollisionQueue) # Sphere collider for triggering scripts self.heroCN = CollisionNode('heroCN') self.heroCN.addSolid(CollisionSphere(0, 0, 0, 5)) # TODO: find good radius self.heroCNP = self.hero.attachNewNode(self.heroCN) self.heroCN.setFromCollideMask(BITMASK_HERO_COLLIDE) self.heroCN.setIntoCollideMask(BitMask32.allOff()) self.heroCollisionQueue = CollisionHandlerQueue() self.cTrav.addCollider(self.heroCNP, self.heroCollisionQueue) # Line collider for transparency self.cameraEntriesPre = [] radius = self.getModelHeight(self.hero)*CAMERA_TRAIL/2 self.cameraCollisionQueue = CollisionHandlerQueue() self.cameraHero = CollisionNode('cameraHero') self.cameraHeroLine = CollisionSegment(self.hero.getPos(render), self.cam.getPos(render)) self.cameraHero.addSolid(self.cameraHeroLine) self.cameraHero.setFromCollideMask(BITMASK_CAMERA) self.cameraHero.setIntoCollideMask(BitMask32.allOff()) self.cameraHeroP = self.render.attachNewNode(self.cameraHero) self.cTrav.addCollider(self.cameraHeroP, self.cameraCollisionQueue) #self.cameraHeroP.show() if FLAG_SHOW_COLLISIONS: self.cTrav.showCollisions(render) # TODO: show specific collision nodepaths def setCollideMasks(self, gameObjDict): for name, obj in gameObjDict.iteritems(): bitmask = obj.getCollideMask() if obj.hasTag('LE-ground'): bitmask |= BITMASK_GROUND #obj.getNP().setCollideMask(bitmask) # TODO: remove if obj.hasTag('LE-attackable'): bitmask |= BITMASK_CLICK if obj.hasTag('LE-wall'): if(isinstance(obj.getNP(), GeoMipTerrain)): bitmask |= BITMASK_TERRAIN else: bitmask |= BITMASK_WALL if obj.scripts.has_key('LE-trigger-onClick'): bitmask |=BITMASK_CLICK if obj.scripts.has_key('LE-trigger-onCollision'): bitmask |=BITMASK_HERO_COLLIDE if obj.hasTag('OBJRoot'): if obj.hasTag('LE-ground') or obj.hasTag('LE-mainChar'): pass else: bitmask |= BITMASK_CAMERA obj.setCollideMask(bitmask) def onClickin3D(self): pickedObj = None if self.conversationMgr.isConversationOpen(): return if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() else: return self.cTrav.addCollider(self.pickerCNP, self.pickerCollisionQueue) self.pickerRay.setFromLens(self.cam.node(), mpos.getX(), mpos.getY()) self.cTrav.traverse(render) if(self.pickerCollisionQueue.getNumEntries() > 0): self.pickerCollisionQueue.sortEntries() for i in range(self.pickerCollisionQueue.getNumEntries()): parent = self.pickerCollisionQueue.getEntry(i).getIntoNodePath().getParent() while not self.objects.has_key(parent.getName()): if(parent.getName() == "render"): return parent = parent.getParent() pickedObj = parent if(pickedObj == None): continue else: break #if pickedObj.hasTag("LE-trigger-onClick"): # TODO: needed, or is having key in self.objects enough? if (pickedObj == None): return self.pickerCollisionQueue.clearEntries() self.cTrav.removeCollider(self.pickerCNP) gameObj = self.gameObjects[pickedObj.getName()] distToTarget = self.hero.getDistance(gameObj) if self.combatMgr.checkCanAttack(self.hero, gameObj): if distToTarget <= self.heroSpells[self.curSpellIndex].getAttackRange(): self.combatMgr.queueAttack(self.hero, self.heroSpells[self.curSpellIndex], gameObj) else: textObject = OnscreenText(text = 'The target is out of range!',fg =(1,0,0,1), pos = (0, 0), scale = 0.09, align = TextNode.ACenter ) def destroyWarning1(): textObject.destroy() sequence =Sequence(Wait(2), Func(destroyWarning1)) sequence.start() return elif(distToTarget > CLICK_RANGE): textObject = OnscreenText(text = 'The target is out of range!',fg =(1,0,0,1), pos = (0, 0), scale = 0.09, align = TextNode.ACenter ) def destroyWarning2(): textObject.destroy() sequence =Sequence(Wait(2), Func(destroyWarning2)) sequence.start() return gameObj.callTrigger(self, 'LE-trigger-onClick') # Task for processing hero's collisions with GameObjects, triggering OnCollision scripts def processHeroCollisions(self, task): #self.cTrav.traverse(render) debug("processHeroCollisions") # CONSIDER: may not be necessary to sort if(self.heroCollisionQueue.getNumEntries() > 0): self.heroCollisionQueue.sortEntries() debug("queue size: "+str(self.heroCollisionQueue.getNumEntries())) for i in range(self.heroCollisionQueue.getNumEntries()): # CONSIDER: if entry.hasInto(): for efficiency debug("i: "+str(i)) # TODO: check if GameObject is passable, and react accordingly (store old position, revert to it) if(self.heroCollisionQueue.getNumEntries() <= 0): return entry = self.heroCollisionQueue.getEntry(i) debug("entry: "+str(entry)) if(entry): intoNP = entry.getIntoNodePath() else: continue if (intoNP != None) or (not intoNP.isEmpty()): while not self.objects.has_key(intoNP.getName()): if(intoNP.getName() == "render"): return task.cont intoNP = intoNP.getParent() pickedObj = intoNP if pickedObj == None: continue gameObj = self.gameObjects[pickedObj.getName()] gameObj.callTrigger(self, 'LE-trigger-onCollision') return task.cont ##== Camera Movement ========================================================## # places the camera pivot to match the position of the node path parameter # used to have the camera pivot match the main character's position as he moves def placeCamera(self, np): self.camPivot.setX(render, np.getX(render)) self.camPivot.setY(render, np.getY(render)) def alignCamera(self, np): self.camPivot.setH(render, self.hero.getH(render) + self.heroHeadingOffset) self.cam.setP(CAMERA_PITCH) def cameraFollowTask(self, task): heroH = self.hero.getH(render) + self.heroHeadingOffset camPivotH = self.camPivot.getH(render) # normalizes the headings to avoid jumps in the difference # which could come from passing 360 and going back to 0, for example # TODO: stress test, esp. with different values of self.heroHeadingOffset while heroH + 180 < camPivotH: heroH += 360 while camPivotH + 180 < heroH: camPivotH += 360 self.lastHeroH = heroH rotateLeft = (heroH >= camPivotH) rotateRight = not rotateLeft diff = math.fabs(heroH - camPivotH) if diff > CAMERA_TURN_THRESHOLD: if rotateLeft: self.camPivot.setH(self.camPivot.getH() + CAMERA_TURN_SPEED) elif rotateRight: self.camPivot.setH(self.camPivot.getH() - CAMERA_TURN_SPEED) # if(len(self.cameraEntriesPre)>0): # #print self.cameraEntriesPre # if(self.hero.getDistance(self.cam) > 5): # moveAmount = min(globalClock.getDt()*200,5.0) # pos = self.cam.getQuat().getForward()*moveAmount # newpos = self.cam.getPos() + pos # self.oldCameraEntriesPre = [] # for e in self.cameraEntriesPre: # self.oldCameraEntriesPre.append(e) # self.cam.setFluidPos(newpos) # # else: # if(self.hero.getDistance(self.cam) < 100): # moveAmount = min(globalClock.getDt()*200,5.0) # pos = self.cam.getQuat().getForward()*(-moveAmount) # oldpos = self.cam.getPos() # newpos = self.cam.getPos() + pos # self.cam.setFluidPos(newpos) # for e in self.oldCameraEntriesPre: # #print e.getIntoNodePath() # self.cTrav.traverse(e.getIntoNodePath()) # #self.cTrav.traverse(render) # if(len(self.cameraSphereQueue.getEntries())>0): # self.cam.setFluidPos(oldpos) return task.cont def runCamera(self, cameraName, sequence, isLoop = False): debug("Running the camera") #debug(str(self.sequences)) self.oldCamera = self.cam self.dr = self.win.makeDisplayRegion() dr2 = self.cam.node().getDisplayRegion(0)# self.objects[cameraName].node().setLens(base.camLens) parent = self.cam.getParent() self.cam.detachNode() self.dr.setCamera(self.objects[cameraName]) def temp(): dr2.setCamera(self.oldCamera) self.oldCamera.reparentTo(parent) self.dr.setActive(False) del self.dr self.dr = None self.accept("mouse1", self.onClickin3D) debug("Ran") if(isLoop): newSequence = Sequence(sequence) self.addSequence(newSequence) def stopCameraFromLoop(): newSequence.finish() temp() self.accept("mouse1", stopCameraFromLoop) self.addSequence(newSequence) newSequence.loop() else: newSequence = Sequence(sequence,Func(temp)) def stopCamera(): newSequence.finish() self.accept("mouse1", stopCamera) self.addSequence(newSequence) newSequence.start() ##== Character Movement =====================================================## def moveHeroTo(self, destinationObj): pos = destinationObj.getPos(render) hpr = destinationObj.getHpr(render) self.hero.setPosHpr(render, pos, hpr) self.placeCamera(self.hero) self.alignCamera(self.hero) def updateHeroHeight(self, task=None): groundEntries = [] #move the collision line to the hero position self.heroGroundCollide.setPos(self.hero.getPos(render)) #loop through every collision entry for the line for e in self.heroGroundHandler.getEntries(): if e.getIntoNodePath().hasNetTag('OBJRoot'): #find the actual root of the object np = e.getIntoNodePath().findNetTag('OBJRoot') #only react to objects that are tagged as the ground if np.hasTag('LE-ground'): groundEntries.append(e) if groundEntries: #sort the collision entries based on height groundEntries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(),\ x.getSurfacePoint(render).getZ())) #set hero height and pivot height self.hero.setZ(groundEntries[0].getSurfacePoint(render).getZ() + MAIN_CHAR_GROUND_OFFSET) self.camPivot.setZ(groundEntries[0].getSurfacePoint(render).getZ() + MAIN_CHAR_GROUND_OFFSET) # TODO: unlink these from being in the same task in case we want pivot to not be linked to hero (ex. cutscene) self.heroGroundHandler.clearEntries() return task.cont def updateHeroPos(self, queue, stepSize): wallEntries = [] for w in queue.getEntries(): np = w.getIntoNodePath().findNetTag('OBJRoot') if np.hasTag('LE-wall'): if self.isInObstacleRange(self.hero, w, stepSize): wallEntries.append(w) if len(wallEntries) > 0: self.herowallcollision = True #self.collisionsurfaceP = wallEntries[0].getSurfacePoint(render) else: self.herowallcollision = False def updateCameraCollision(self): self.cameraHeroLine.setPointA(self.cam.getPos(render)) self.cameraHeroLine.setPointB(self.hero.getPos(render)) if(self.cameraEntriesPre): for i in self.cameraEntriesPre: i.getIntoNodePath().setTransparency(TransparencyAttrib.MAlpha) i.getIntoNodePath().setAlphaScale(1.0) del self.cameraEntriesPre[:] for i in self.cameraCollisionQueue.getEntries(): i.getIntoNodePath().setAlphaScale(0.5) self.cameraEntriesPre.append(i) def moveHero(self,direction, dt): temp = render.attachNewNode("Dummy")#NodePath() moveStep = MAIN_CHAR_MOVE_SPEED*dt if moveStep > MAIN_CHAR_MAX_STEP: moveStep = MAIN_CHAR_MAX_STEP temp.setPos(self.camPivot, 0,direction*moveStep, 0) #oldPos = self.heroWallCollideX.getPos() self.heroWallCollideX.setX(temp.getX()) self.heroWallCollideY.setY(temp.getY()) self.heroWallCollideZ.setZ(temp.getZ())#+10) self.cTrav.traverse(render) #check on X direction self.updateHeroPos(self.heroWallQueueX, moveStep) self.moveHeroToWallCollide(Point3(temp.getX(),self.hero.getY(),self.hero.getZ())) #check on Y direction self.updateHeroPos(self.heroWallQueueY, moveStep) self.moveHeroToWallCollide(Point3(self.hero.getX(),temp.getY(),self.hero.getZ())) #check on Z direction self.updateHeroPos(self.heroWallQueueZ, moveStep) self.moveHeroToWallCollide(Point3(self.hero.getX(),self.hero.getY(),temp.getZ())) self.heroWallCollideX.setPos(self.hero.getPos()) self.heroWallCollideY.setPos(self.hero.getPos()) self.heroWallCollideZ.setPos(self.hero.getPos()) self.placeCamera(self.hero) self.updateCameraCollision() temp.detachNode() def moveHeroToWallCollide(self,pos): if self.herowallcollision==False: self.hero.setPos(pos)#self.camPivot, 0, MAIN_CHAR_MOVE_SPEED, 0) def isInObstacleRange(self, mover, colEntry, stepSize): colPoint = colEntry.getSurfacePoint(render) if colPoint[2] >= mover.getZ(render): dist = findDistance3D(mover.getX(), mover.getY(), mover.getZ(), colPoint[0], colPoint[1], colPoint[2]) obstacleThreshold = self.heroHeight*self.heroHeight + stepSize*stepSize if dist*dist <= obstacleThreshold: return True return False def turnHeroLeft(self): up = render.getRelativeVector(base.cam, Vec3(0, 0, 1)) up.normalize() curHeroQuat = self.hero.getQuat() newHeroQuat = Quat() newHeroQuat.setFromAxisAngle(MAIN_CHAR_ROTATE_SPEED, up) self.hero.setQuat(curHeroQuat*newHeroQuat) self.hero.setR(0) self.hero.setP(0) self.updateCameraCollision() def turnHeroRight(self): up = render.getRelativeVector(base.cam, Vec3(0, 0, 1)) up.normalize() curHeroQuat = self.hero.getQuat() newHeroQuat = Quat() newHeroQuat.setFromAxisAngle(-MAIN_CHAR_ROTATE_SPEED, up) self.hero.setQuat(curHeroQuat*newHeroQuat) self.hero.setR(0) self.hero.setP(0) self.updateCameraCollision() def disableMovement(self, gameObj): if gameObj.getName() == self.hero.getName(): self.ignore('w') self.ignore('w-up') self.ignore('a') self.ignore('a-up') self.ignore('s') self.ignore('s-up') self.ignore('d') self.ignore('d-up') else: if gameObj.getAIBehaviorsHandle().behaviorStatus('pursue') != -1: gameObj.getAIBehaviorsHandle().pauseAi('pursue') def enableMovement(self, gameObj): if gameObj.getName() == self.hero.getName(): self.accept('w', self.setKeyStatus, extraArgs=['w', True]) self.accept('w-up', self.setKeyStatus, extraArgs=['w', False]) self.accept('a', self.setKeyStatus, extraArgs=['a', True]) self.accept('a-up', self.setKeyStatus, extraArgs=['a', False]) self.accept('s', self.setKeyStatus, extraArgs=['s', True]) self.accept('s-up', self.setKeyStatus, extraArgs=['s', False]) self.accept('d', self.setKeyStatus, extraArgs=['d', True]) self.accept('d-up', self.setKeyStatus, extraArgs=['d', False]) else: if gameObj.getAIBehaviorsHandle().behaviorStatus('pursue') == 'paused': gameObj.getAIBehaviorsHandle().resumeAi('pursue') def setKeyStatus(self, key, isDown): self.keyMap[key] = isDown print self.hero.getName() ###################################################################### ## # ZJC - 07/29/2011: THIS CODE WAS COMMENTED OUT BECAUSE A MORE EFFICIENT WAY WAS FOUND ## ## prefixList = [] ## #NEXT LINE- ZJC - 07/29/2011: This line is used to mark where to import the array used to deal with import flags. ## #LoaderFlagImportArray ## name = self.hero.getName().split('_')[0] # ZJC - 07/29/2011: name is assumed to be formatted NAME_otherstuff ## name2 = self.hero.getName().split('_')[1] # ZJC - 07/29/2011: name2 is assumed to be PREFIX_NAME_otherstuff ## if name in prefixList: # ZJC - 07/29/2011: Checks if the name is in the array, if it is name is not formatted as assumed ## name = name2 # ZJC - 07/29/2011: Use the second format if the first name is in the list ## print name ###################################################################### name = self.hero.getName().split('_')[0] # ZJC - 07/29/2011: Assumes format is Name_mod:# ## print name for i in range(len(self.here.getName().split('_'))): # ZJC - 07/29/2011: Loop will check every possibility in the name string for any level of merges/imports name2 = self.hero.getName().split('_')[i] # ZJC - 07/29/2011: name2 holds the current piece of the name string if ("mod:" in name2) and (name != name2): # ZJC - 07/29/2011: This means the name format is Prefix(es)_Name_mod:# name = self.hero.getName().split('_')[i-1] # ZJC - 07/29/2011: Assigns correct model name, the one just before mod:# if isDown: if key == 'w': if self.hero.getActorHandle() != None: self.hero.getActorHandle().stop(name + '_ani_idle') # ZJC - 07/26/2011: Stop the 'name' specific idle animation self.hero.getActorHandle().setPlayRate(1.0, name + '_ani_run') # ZJC - 07/26/2011: Set play rate for the 'name' specific run animation self.hero.getActorHandle().loop(name + '_ani_run') # ZJC - 07/26/2011: Run the 'name' specific run animation self.keyMap['s'] = False elif key == 's': if self.hero.getActorHandle() != None: self.hero.getActorHandle().stop(name + '_ani_idle') # ZJC - 07/26/2011: Stop the 'name' specific idle animation self.hero.getActorHandle().setPlayRate(-0.7, name + '_ani_run') # ZJC - 07/26/2011: Set play rate for the 'name' specific run animation self.hero.getActorHandle().loop(name + '_ani_run') # ZJC - 07/26/2011: Run the 'name' specific run animation self.keyMap['w'] = False elif key == 'a': self.keyMap['d'] = False elif key == 'd': self.keyMap['a'] = False elif not isDown: if key == 'w': if not self.keyMap['s']: if self.hero.getActorHandle() != None: self.hero.getActorHandle().stop(name + '_ani_run') # ZJC - 07/26/2011: Stop the 'name' specific run animation self.hero.getActorHandle().loop(name + '_ani_idle') # ZJC - 07/26/2011: Run the 'name' specific idle animation elif key == 's': if not self.keyMap['w']: if self.hero.getActorHandle() != None: self.hero.getActorHandle().stop(name + '_ani_run') # ZJC - 07/26/2011: Stop the 'name' specific run animation self.hero.getActorHandle().loop(name + '_ani_idle') # ZJC - 07/26/2011: Run the 'name' specific idle animation elif key == 'a': pass elif key == 'd': pass ## ZJC - 07/26/2011: This was the previous version of the code, it has been commented out and left as ## a reference. The changes made are defined in the comments above. ## if isDown: ## if key == 'w': ## if self.hero.getActorHandle() != None: ## self.hero.getActorHandle().stop('anim_idleFemale') # TODO: make a constant / set in LE ## self.hero.getActorHandle().setPlayRate(1.0, 'anim_jogFemale') ## self.hero.getActorHandle().loop('anim_jogFemale') ## self.keyMap['s'] = False ## elif key == 's': ## if self.hero.getActorHandle() != None: ## self.hero.getActorHandle().stop('anim_idleFemale') # TODO: make a constant / set in LE ## self.hero.getActorHandle().setPlayRate(-0.7, 'anim_jogFemale') ## self.hero.getActorHandle().loop('anim_jogFemale') ## self.keyMap['w'] = False ## elif key == 'a': ## self.keyMap['d'] = False ## elif key == 'd': ## self.keyMap['a'] = False ## elif not isDown: ## if key == 'w': ## if not self.keyMap['s']: ## if self.hero.getActorHandle() != None: ## self.hero.getActorHandle().stop('anim_jogFemale') ## self.hero.getActorHandle().loop('anim_idleFemale') ## elif key == 's': ## if not self.keyMap['w']: ## if self.hero.getActorHandle() != None: ## self.hero.getActorHandle().stop('anim_jogFemale') ## self.hero.getActorHandle().loop('anim_idleFemale') ## elif key == 'a': ## pass ## elif key == 'd': ## pass def moveHeroTask(self, task): dt = globalClock.getDt() direction = int(self.keyMap['w'])-int(self.keyMap['s']) self.moveHero(direction, dt) if self.keyMap['a']: self.turnHeroLeft() elif self.keyMap['d']: self.turnHeroRight() return task.cont ##== Scene Handling =========================================================## def loadScenes(self): # NOTE: Do not remove! This function is populated by StandaloneExporter pass def addSequence(self, sequence): self.ranSequences.append(sequence) #this is for changing scenes def resetAllSequences(self): for seq in self.ranSequences: seq.finish() dr = self.cam.node().getDisplayRegion(0) dr.setCamera(self.gameCam) self.ranSequences = [] def openScene(self, sceneName): if (self.scenes.has_key(sceneName)==False): print "ERROR:There is no scene under the name ", sceneName,"." return self.startLoadBar(12) self.createLoadScreen() #Part2:Clear all of the collision lists self.cTrav.removeCollider(self.heroCNP) self.heroGroundHandler.clearEntries() self.heroCollisionQueue.clearEntries() self.resetAllSequences() self.increaseLoadBar(1) #Part3: stop all of the tasks taskMgr.remove('processHeroCollisions') taskMgr.remove('updateHeroHeight') taskMgr.remove('moveHeroTask') taskMgr.remove('cameraFollowTask') taskMgr.remove("updateShaders") # ? self.combatMgr.stopTasks() self.gameplayUI.stop() self.gameplayUI.removeAllHealthBars() self.increaseLoadBar(1) #Part1.1: Stop currently running parts like conversations or camera if(self.conversationMgr.isConversationOpen()): self.conversationMgr.closeConversation() #Part 1.2: stop the camera self.increaseLoadBar(1) #Part4: Turn-Off all of the player controls self.ignore("mouse1") self.increaseLoadBar(1) #Part5: Remove all of the game elements that are related with the current scene del self.combatMgr self.increaseLoadBar(1) #Part6: Remove all of the children and the lights from the render render.getChildren().detach() render.clearLight() self.increaseLoadBar(1) #Part7:Add the camera and hero or any game element that should be exist in any scene back self.camPivot.reparentTo(render) self.hero.reparentTo(render) #self.heroWallCollide.reparentTo(render) self.heroWallCollideX.reparentTo(render) self.heroWallCollideY.reparentTo(render) self.heroWallCollideZ.reparentTo(render) self.heroGroundCollide.reparentTo(render) self.cameraHeroP.reparentTo(render) self.overlayAmbientLightNP.reparentTo(render) self.increaseLoadBar(1) #Part8:Add the new objects from the new scene self.assets, self.objects, self.gameObjects, self.sounds, self.sequences = loadWorld(self.scenes[sceneName], LIBRARY_INDEX) self.increaseLoadBar(1) #Part9:Add the hero to the new gameObject list and remove the duplicates of the hero self.gameObjects[self.hero.getName()] = self.hero if(self.objects.has_key(self.hero.getName())): object = self.objects[self.hero.getName()] if(object.hasTag('LE-mainChar')): object.detachNode() del self.objects[self.hero.getName()] for name, gameObj in self.gameObjects.iteritems(): if gameObj.getNP().hasTag('LE-ground'): #debug("is Ground") bitmask = gameObj.getNP().getCollideMask() bitmask |= BITMASK_GROUND gameObj.getNP().setCollideMask(bitmask) self.increaseLoadBar(1) #Part10:Restart the tasks. self.combatMgr = CombatMgr(self) taskMgr.add(self.processHeroCollisions, 'processHeroCollisions') taskMgr.add(self.updateHeroHeight, 'updateHeroHeight') taskMgr.add(self.moveHeroTask, 'moveHeroTask') taskMgr.add(self.cameraFollowTask, 'cameraFollowTask') self.combatMgr.startTasks() self.gameplayUI.start() self.increaseLoadBar(1) self.setCollideMasks(self.gameObjects) self.increaseLoadBar(1) #Part11: Change the color of the sky if(sceneName.startswith("interior") or sceneName.startswith("Interior")): self.setBackgroundColor(BGC_DARK_GREY) else: self.skybox.reparentTo(render) self.setBackgroundColor(BGC_LIGHT_BLUE) self.increaseLoadBar(1) #Part12: Restart the player controls self.accept("mouse1", self.onClickin3D) self.increaseLoadBar(1) self.accept("enter",self.destroyLoadScreen) debug("After open Scene: "+str(self.heroCollisionQueue.getNumEntries())) self.heroCollisionQueue.clearEntries() self.cTrav.addCollider(self.heroCNP, self.heroCollisionQueue) self.destroyLoadScreen()
def run(self): maleLock.naFila = maleLock.naFila + 1 test = GameObject((400, 100), (100, 100), testTex) #cria novo objeto (pinguim) e o adiciona ao grupo para desenhar a sprite na tela test.changeDestination((self.threadID%5)*40+200,100) #muda as coordenadas de destino do objeto if femaleLock.naFila > 0 and maleLock.consecutive > 5: maleLock.consecutive = 0 maleTurnstile.clear() maleTurnstile.wait() maleLock.consecutive = maleLock.consecutive + 1 maleLock.counter = maleLock.counter+1 while maleLock.status == 'False': maleLock.changeStatus() while maleLock.lastIn + 1 != self.threadID: #faz com que a ordem de entrada seja tal que obedeca a regra de 1 por slot time.sleep(0) maleLock.lastIn = maleLock.lastIn + 1 maleMultiplex.acquire() test.changeDestination(180,100) time.sleep(3-(self.threadID%3)/2) #tempo de sleep varia com a localizacao do pinguim. Serve para que todos entrem pela porta. maleLock.naFila = maleLock.naFila - 1 test.changeDestination((self.threadID%3)*40+150,20) print "Homem %d entrou no banheiro" %(self.threadID) maleLock.insideCounter = maleLock.insideCounter + 1 time.sleep(5) maleLock.insideCounter = maleLock.insideCounter - 1 print "Homem %d saiu do banheiro" %(self.threadID) test.changeDestination(180,400) maleLock.counter = maleLock.counter-1 if maleLock.counter == 0: femaleTurnstile.set() maleLock.changeStatus() maleMultiplex.release() time.sleep(9) #aguarda o objeto sair da tela para exlcui-lo test.kill()
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()