def render(self, data): output = list() statsLabels = { 'stat_hp': _('STAT_CURRENT_HP'), 'stat_attack': _('STAT_ATTACK'), 'stat_defence': _('STAT_DEFENCE'), 'stat_speed': _('STAT_SPEED'), 'stat_luck': _('STAT_LUCK') } longestStat = max({len(stat): stat for stat in statsLabels.values()}) # Display the health healthStat = '{0} / {1}'.format( stats.padStat(data['stat_current_hp'], 4), data['stat_max_hp'] ) lenHealthStat = len(healthStat) output.append(stats.formatStat( statsLabels['stat_hp'], longestStat, healthStat )) # The remaining stats for i in data: if i != 'stat_current_hp' and i != 'stat_max_hp': output.append(stats.formatStat( statsLabels[i], longestStat, stats.padStat(data[i], lenHealthStat) )) return '\n'.join(output)
def test_containers_text(self): self.rpg.setAction([_('LOOK_COMMAND'), _('LOOK_CONTAINERS_PARAM')]) output = self.rpg._runAction() self.assertEquals(output, _('AVAILABLE_ITEMS_CONTAINERS') +'\n'+\ ' chest #1\n' +\ ' wardrobe #1\n' +\ ' wardrobe #2')
def openMap(self): """ Method to open a map from a filename """ fileName = self._app.getMapFileName() + '.bmp' image = QtGui.QImage(fileName) if image is None or imghdr.what(str(fileName)) != "bmp": QtGui.QMessageBox.information( self, _('IMAGE_VIEWER'), _('ERROR_OPEN_%s') % (fileName) ) return self._imageScene.clear() mapPixmap = QtGui.QPixmap.fromImage(image) mapPixmap = QtGui.QGraphicsPixmapItem(mapPixmap, None, self._imageScene) mapPixmap.mousePressEvent = self.pixelSelect self._pixmaps = dict() self._pixmaps['map'] = mapPixmap self.refreshEntities() if self._app.map.startCellPosition is not None: self.displayStartCell(self._app.map.startCellPosition[0], self._app.map.startCellPosition[1]) self._scaleFactor = 1.0 self.menuBar().mapOpened.emit() if self._app.getSaveFileName() is None: self._app.flagAsUnsaved()
def _runAction(self, renderJson=False): """ Method to execute when an action is set and ready to be executed. """ if self._savedGame is None: raise core.exception.exception(_('ERROR_SAVED_GAME_NEEDED_TO_RUN_ACTION')) elif not self._player.isConnected(): raise core.exception.exception(_('ERROR_CONNECTED_PLAYER_NEEDED_FOR_COMMAND')) elif self._action is None: raise core.exception.exception(_('ERROR_NO_ACTION_SET')) try: c = command_factory.factory.create( self._player, self._action, self._savedGame['id_saved_game'] ) self._action = None if c == command_factory.quit: return c result = c.run() if not renderJson: result = c.render(result) return result except core.exception.exception as e: return self.renderException(e, renderJson)
def createMap(self): """ Method called when the "Create" button is pressed. The filled values are checked and if they are correct, a map is generated, in a thread """ valid = True try: name = str(self._mapNameField.text()).strip() width = self._mapWidthField.value() height = self._mapHeightField.value() if width <= 0 or height <= 0: self.displayMessage(_('ERROR_INVALID_WIDTH_HEIGHT_VALUE')) valid = False elif name == "": self.displayMessage(_('ERROR_EMPTY_MAP_NAME')) valid = False except ValueError: self.displayMessage(_('ERROR_INVALID_WIDTH_HEIGHT_VALUE')) valid = False if valid: self._app.setMapName(name) name = config.tempDir + '/' + self._app.escapeName(name) self._app.setMapFileName(name) self.displayMessage(_('LOADING_GENERATION_TEXT')) self._saveButton.setEnabled(False) self._cancelButton.setEnabled(False) self._thread = worker.generatorThread(self._app, width, height) self._thread.generatorError.connect(self.displayMessage) self._thread.generatorSuccess.connect(self._parent.openMap) self._thread.generatorSuccess.connect(self.close) self._thread.start()
def test_out_of_range_container_index_text(self): self.rpg.setAction([_("TAKE_COMMAND"), "Heavy breastplate", "wardrobe", 0]) output = self.rpg._runAction() self.assertEquals(output, _("ERROR_OUT_OF_RANGE_ITEM_CONTAINER_INDEX_%d") % (2,)) self.rpg.setAction([_("TAKE_COMMAND"), "Heavy breastplate", "wardrobe", 3]) output = self.rpg._runAction() self.assertEquals(output, _("ERROR_OUT_OF_RANGE_ITEM_CONTAINER_INDEX_%d") % (2,))
def validateFormData(self): valid = True internalName = str(self._npcInternalNameField.text()).strip() name = str(self._npcNameField.text()).strip() species = int(self._npcSpeciesField.currentIndex()) gender = int(self._npcGenderField.currentIndex()) if internalName == "": self.displayMessage(_('ERROR_EMPTY_NPC_INTERNAL_NAME')) valid = False elif self._editedRow != internalName and self._app.hasEntityWithName(self.entityType, internalName): self.displayMessage(_('ERROR_DUPLICATE_NPC_INTERNAL_NAME')) valid = False if name == "": self.displayMessage(_('ERROR_EMPTY_NPC_NAME')) valid = False if species < 0 or species >= len(self._app.map.getSpeciesNames()): self.displayMessage(_('ERROR_INVALID_NPC_SPECIES')) valid = False if gender < 0 or gender >= len(map.map.getGenders()): self.displayMessage(_('ERROR_INVALID_NPC_GENDER')) valid = False if valid is False: return False return { 'name': name, 'gender': self._npcGenderField.currentIndex(), 'species': self._npcSpeciesField.currentIndex(), 'internalName': internalName }
def render(self, data): attackConfirm = _('ATTACK_CONFIRM_PLAYER_TO_ENEMY_{enemy}_{damages}') attackConfirmEnemy = _('ATTACK_CONFIRM_ENEMY_TO_PLAYER_{enemy}_{damages}') attackVictory = _('ATTACK_VICTORY_{enemy}') attackLost = _('ATTACK_LOST_{enemy}') dataFormat = { 'enemy': data['enemy']['name'], 'damages': data['attackResult']['damagesToEnemy'] } output = [attackConfirm.format(**dataFormat)] if data['attackResult']['damagesToPlayer'] is not None: dataFormat = { 'enemy': data['enemy']['name'], 'damages': data['attackResult']['damagesToPlayer'] } output.append(attackConfirmEnemy.format(**dataFormat)) if data['attackResult']['fightFinished']: dataFormat = { 'enemy': data['enemy']['name'] } if data['attackResult']['winner'] == self._player: output.append(attackVictory.format(**dataFormat)) else: output.append(attackLost.format(**dataFormat)) return '\n'.join(output)
def run(self): """ Say something to a character in the player's area. """ if len(self._args) == 0: raise core.command.exception(_('ERROR_TALK_NO_CHARACTER_GIVEN')) elif len(self._args) == 1: raise core.command.exception(_('ERROR_TALK_NO_SENTENCE_GIVEN')) characterName = self._args[0] triggerWord = self._args[1] c = character.character.searchByNameAndIdArea( characterName, self._player.getAreaId() ) if c is None: raise character.exception(_('ERROR_TALK_UNKNOWN_CHARACTER')) s = sentence.sentence.loadByCharacterIdAndTriggerWord( c.getId(), triggerWord ) if len(s) is 0: raise sentence.exception(_('ERROR_TALK_UNKNOWN_SENTENCE')) s = s[random.randint(0, len(s) - 1)] return { 'question': triggerWord, 'character': characterName, 'answer': self.processSentence( s.getSentence(), self._player._model['name'] ) }
def create(p, commandFull, savedGameId=None): """ command.factory.create(p, commandFull, savedGameId=None) -> command.command Create the desired command. @param p player.player Current player. @param commandFull list command to run, the first element of the list is the command, the other elements are the command's arguments. @return the created command """ cmd = commandFull[0] del commandFull[0] if cmd in (_('QUIT_COMMAND'), _('QUIT_SHORT_COMMAND')): return quit elif cmd in factory.mapping.keys(): cmd = factory.mapping[cmd] module = sys.modules['core.commands.' + cmd['command']] if p.isFighting() and not cmd['allowed_while_fighting']: raise core.command.exception(_('ERROR_DENIED_COMMAND_WHILE_FIGHTING')) cmd = getattr(module, cmd['command'])() else: raise core.command.exception(_('ERROR_UNKNOWN_COMMAND')) cmd.setArgs(commandFull) cmd.setPlayer(p) cmd.setSavedGameId(savedGameId) return cmd
def test_directions_text(self): self.rpg.setAction([_('LOOK_COMMAND'), _('LOOK_DIRECTIONS_PARAM')]) output = self.rpg._runAction() self.assertEquals( output, _('AVAILABLE_DIRECTIONS') + '\n ' +\ _('DIRECTION_KEY_SOUTH') )
def creationForm(self): """ Method which creates the form to add a species. Returns a layout containing the form elements. """ form = QtGui.QGridLayout() self._messageLabel = QtGui.QLabel() self._messageLabel.setWordWrap(True) nameLabel = QtGui.QLabel(_('SPECIES_NAME_LABEL')) self._nameField = QtGui.QLineEdit() self._nameField.textChanged.connect(self.updateCreateButton) internalNameLabel = QtGui.QLabel(_('SPECIES_INTERNAL_NAME_LABEL')) self._internalNameField = QtGui.QLineEdit() self._internalNameField.textChanged.connect(self.updateCreateButton) descriptionLabel = QtGui.QLabel(_('SPECIES_DESCRIPTION_LABEL')) self._descriptionField = QtGui.QTextEdit() self._descriptionField.textChanged.connect(self.updateCreateButton) self._saveButton = QtGui.QPushButton(_('CREATE_BUTTON')) self._saveButton.setEnabled(False) self._saveButton.clicked.connect(self.createSpecies) form.addWidget(self._messageLabel, 0, 0, 1, 2) form.addWidget(internalNameLabel, 1, 0) form.addWidget(self._internalNameField, 1, 1) form.addWidget(nameLabel, 2, 0) form.addWidget(self._nameField, 2, 1) form.addWidget(descriptionLabel, 3, 0) form.addWidget(self._descriptionField, 3, 1) form.addWidget(self._saveButton, 4, 1) return form
def test_command_with_no_player(self): rpgEngine = Rpg.Rpg() rpgEngine.initWorld(self.dbFile) rpgEngine.initSavedGame(self.idEmptySavedGame) rpgEngine.setAction([_('LOOK_COMMAND')]) with self.assertRaises(core.exception.exception) as raised: rpgEngine._runAction(True) self.assertEquals(str(raised.exception), _('ERROR_CONNECTED_PLAYER_NEEDED_FOR_COMMAND'))
def formatSavedGameName(s): if s['id_player'] is None: return _('EMPTY_SAVED_GAME') else: data = { 'login': s['login'] } return _('SAVED_GAME_INFO_{login}').format(**data)
def yesNoQuestion(self, question): v = None yesNo = {'yes': _('ANSWER_YES'), 'no': _('ANSWER_NO')} questionDataFormat = {'choices': '({yes}/{no})'.format(**yesNo)} while v not in yesNo.values(): v = utils.read(question.format(**questionDataFormat)) return v == _('ANSWER_YES')
def checkForExport(self): """ Method to check if a cell is ready to be exported (start cell selected) """ if self.startCellPosition is None: raise exception(_('ERROR_NO_START_CELL_SELECTED')) if len(self.species) is 0: raise exception(_('ERROR_NO_SPECIES'))
def test_region_text(self): self.rpg.setAction([_('LOOK_COMMAND'), _('LOOK_REGION_PARAM')]) output = self.rpg._runAction() expected = [ _('CURRENT_REGION_%s') % 'The High lands', _('AREA_HAS_SAVE_POINT') ] self.assertEquals(output, '\n'.join(expected))
def getFromEntranceArea(idArea, t): if t not in types: raise exception(_('ERROR_UNKNOWN_PLACE_TYPE')) if t == _('PLACE_TYPE_DUNGEON'): return dungeon.getAvailable(idArea) elif t == _('PLACE_TYPE_CAVE'): return cave.getAvailable(idArea)
def test_quantity_too_low_text(self): inv = self.getInventory() self.rpg.setAction([_('DROP_COMMAND'), 0, 'Heavy breastplate']) output = self.rpg._runAction() self.assertEquals(output, _('ERROR_DROP_TOO_LOW_QUANTITY')) self.compareInventory(inv)
def test_quantity_too_low_json(self): inv = self.getInventory() self.rpg.setAction([_('DROP_COMMAND'), 0, 'Heavy breastplate']) output = self.rpg._runAction(True) self.assertEquals(output, {"error": {"message": _('ERROR_DROP_TOO_LOW_QUANTITY'), "code": 1}}) self.compareInventory(inv)
def test_invalid_quantity_text(self): inv = self.getInventory() self.rpg.setAction([_('DROP_COMMAND'), 'ten', 'Heavy breastplate', 'chest', 1]) output = self.rpg._runAction() self.assertEquals(output, _('ERROR_DROP_INVALID_FORMAT_QUANTITY')) self.compareInventory(inv)
def test_invalid_quantity_json(self): inv = self.getInventory() self.rpg.setAction([_('DROP_COMMAND'), 'ten', 'Heavy breastplate', 'chest', 1]) output = self.rpg._runAction(True) self.assertEquals(output, {"error": {"message": _('ERROR_DROP_INVALID_FORMAT_QUANTITY'), "code": 1}}) self.compareInventory(inv)
def _exportWorldCreation(self, thread, db, name): """ Method to export the world in the DB. """ c = db.cursor() thread.notifyProgressLocal.emit(0, _('LOCAL_PROGRESS_REGIONS_CREATION')) # Create main region query = str("INSERT INTO region (region_name) VALUES (?)") c.execute(query, [name]) thread.notifyProgressLocal.emit(33, _('LOCAL_PROGRESS_AREA_TYPES_CREATION')) # Create area types query = "INSERT INTO area_type (name) VALUES " areaTypesCodes = checks.getGroundTypes() valuesInsert = list() for t in self._placesTypes.keys(): valuesInsert.append("('" + t + "')") values = list() for t in areaTypesCodes: valuesInsert.append("(?)") values.append(t) query = query + ', '.join(valuesInsert) c.execute(query, values) thread.notifyProgressLocal.emit(66, _('LOCAL_PROGRESS_AREAS_CREATION')) # Get area types IDs query = "SELECT id_area_type, name FROM area_type" c.execute(query) result = c.fetchall() areaTypes = dict() for r in result: if r[1] in areaTypesCodes: code = areaTypesCodes[r[1]] areaTypes[code] = {'id_area_type': r[0], 'name': r[1]} # Open text file containing cells infos query = "INSERT INTO area (id_area_type, id_region, container, x, y, directions) VALUES (?, ?, ?, ?, ?, ?)" nbAreas = 0 for x in self.cells: for y in self.cells[x]: t = areaTypes[self.cells[x][y][0]] if t['name'] == 'water': continue nbAreas = nbAreas + 1 areas = [ areaTypes[self.cells[x][y][0]]['id_area_type'], 1, "world", x, y, self.cells[x][y][1] ] c.execute(query, areas) thread.notifyProgressLocal.emit(100, _('LOCAL_PROGRESS_FINISHED'))
def test_item_text(self): self.rpg.setAction([_("TAKE_COMMAND"), "Heavy breastplate"]) output = self.rpg._runAction() self.assertEquals( output, _("TAKE_CONFIRMATION_%(quantity)s_%(name)s") % {"quantity": 1, "name": "Heavy breastplate"} ) self.rpg.setAction([_("LOOK_COMMAND"), _("LOOK_OBJECTS_PARAM")]) output = self.rpg._runAction() self.assertEquals(output, _("AVAILABLE_ITEMS") + "\n" + " 5 Heavy breastplate")
def test_no_save_move_json(self): self.rpg.setAction([_('MOVE_COMMAND'), _('DIRECTION_KEY_SOUTH')]) outputMove = self.rpg._runAction(True) self.initialiseClient() self.rpg.setAction([_('LOOK_COMMAND'), _('LOOK_REGION_PARAM')]) outputLook = self.rpg._runAction(True) self.assertNotEquals((outputMove['x'], outputMove['y']), (outputLook['region']['x'], outputLook['region']['y']))
def test_out_of_range_container_index_json(self): self.rpg.setAction([_('TAKE_COMMAND'), 'Heavy breastplate']) self.rpg._runAction(True) self.rpg.setAction([_('DROP_COMMAND'), 'Heavy breastplate', 'wardrobe', 0]) output = self.rpg._runAction(True) self.assertEquals(output, {"error": {"message": _('ERROR_OUT_OF_RANGE_ITEM_CONTAINER_INDEX_%d') % (2,), "code": 1}}) self.rpg.setAction([_('DROP_COMMAND'), 'Heavy breastplate', 'wardrobe', 3]) output = self.rpg._runAction(True) self.assertEquals(output, {"error": {"message": _('ERROR_OUT_OF_RANGE_ITEM_CONTAINER_INDEX_%d') % (2,), "code": 1}})
def test_out_of_range_container_index_text(self): self.rpg.setAction([_('TAKE_COMMAND'), 'Heavy breastplate']) self.rpg._runAction() self.rpg.setAction([_('DROP_COMMAND'), 'Heavy breastplate', 'wardrobe', 0]) output = self.rpg._runAction() self.assertEquals(output, _('ERROR_OUT_OF_RANGE_ITEM_CONTAINER_INDEX_%d') % (2,)) self.rpg.setAction([_('DROP_COMMAND'), 'Heavy breastplate', 'wardrobe', 3]) output = self.rpg._runAction() self.assertEquals(output, _('ERROR_OUT_OF_RANGE_ITEM_CONTAINER_INDEX_%d') % (2,))
def test_save_no_change_json(self): self.rpg.setAction([_('SAVE_COMMAND')]) self.rpg._runAction(True) self.initialiseClient() self.rpg.setAction([_('INVENTORY_COMMAND')]) output = self.rpg._runAction(True) self.assertEquals(output, [])
def setSaveMapName(self, name): """ Set the map's name used to save the map """ name = str(name) if not os.path.exists(os.path.dirname(name)): raise BaseException(_('ERROR_UNEXISTING_FOLDER')) elif os.path.exists(name) and not os.path.isfile(name): raise BaseException(_('ERROR_NOT_A_FILE')) self._saveFileName = name
def run(self): """ c.run() Move the player in the desired direction. """ if len(self._args) == 0: raise core.command.exception(_('ERROR_MOVE_NO_DIRECTION_GIVEN')) direction = self._args[0] if direction not in area.area.getDirections(): raise core.command.exception(_('ERROR_MOVE_INVALID_DIRECTION_%s') % direction) curAreaId = self._player.getAreaId() curArea = area.model.loadById(curAreaId) a = area.area.getNeighbourFromDirection(curAreaId, direction) if area.area.canGoTo(curArea['directions'], direction) is False or a is None: raise core.command.exception(_('ERROR_MOVE_DIRECTION_NOT_AVAILABLE')) ret = {'direction': direction, 'x': a._model['x'], 'y': a._model['y']} wasFighting = self._player.isFighting() f = fight.getFight() if wasFighting: enemy = f.enemy if not fight.canFlee(self._player._model, enemy): raise core.fight.exception(_('ERROR_FLEE_FIGHT_FAILS')) fight.stopFight() ret['flee'] = True ret['enemy'] = enemy['name'] self._player.goTo(a._model['id_area']) # let's be fair, if the player succesfully ran away from a # fight, he probably does not want to arrive right away in a # new one enemy = None if not wasFighting: probability = randint(0, 1000) / 1000.0 enemy = creature.creature.getFromAreaType( a._model['id_area_type'], probability ) if enemy is not None: ret['enemy'] = enemy['name'] f = fight.startFight(self._player, enemy) # Deal with enemy attacking first damages = f.enemyTriesToAttackFirst(self._player) if damages is not None: ret['damages'] = damages return ret
async def cmd_start(message: types.Message): print('START COMMAND') # NOTE: This is a test translation. For more info visit: https://github.com/aiogram/aiogram/blob/dev-2.x/examples/i18n_example.py await message.reply(_('Hi!!'))