mirror of
https://github.com/evennia/evennia.git
synced 2026-03-16 21:06:30 +01:00
issue #2243 -- prefer f-strings over %-interpolation
edited docs to prefer f-strings, then str.format(), and remove %-interpolation additional ad-hoc documentation fixes, as opportunities seen: - replace Built-In Function (BIF) "min" variable with "mins" - prefer BIF str(var) over "%s" % var - reformat some code examples to clarify multiple args passed to functions - change some single-quote strings to double-quotes for consistency - fix mismatched parens misc edits: - add .vscode/ to gitignore
This commit is contained in:
parent
f45051050e
commit
851ca30be5
30 changed files with 207 additions and 193 deletions
|
|
@ -99,8 +99,9 @@ class CmdShoot(Command):
|
|||
# we have an argument, search for target
|
||||
target = caller.search(self.args.strip())
|
||||
if target:
|
||||
message = "BOOM! The mech fires its gun at %s" % target.key
|
||||
location.msg_contents(message)
|
||||
location.msg_contents(
|
||||
f"BOOM! The mech fires its gun at {target.key}"
|
||||
)
|
||||
|
||||
class CmdLaunch(Command):
|
||||
# make your own 'launch'-command here as an exercise!
|
||||
|
|
|
|||
|
|
@ -78,19 +78,18 @@ channel send. Edit `mygame/typeclasses/channels.py` (and then `@reload`):
|
|||
|
||||
```python
|
||||
# define our custom color names
|
||||
CHANNEL_COLORS = {'public': '|015Public|n',
|
||||
'newbie': '|550N|n|551e|n|552w|n|553b|n|554i|n|555e|n',
|
||||
'staff': '|010S|n|020t|n|030a|n|040f|n|050f|n'}
|
||||
CHANNEL_COLORS = {"public": "|015Public|n",
|
||||
"newbie": "|550N|n|551e|n|552w|n|553b|n|554i|n|555e|n",
|
||||
"staff": "|010S|n|020t|n|030a|n|040f|n|050f|n"}
|
||||
|
||||
# Add to the Channel class
|
||||
# ...
|
||||
def channel_prefix(self, msg, emit=False):
|
||||
prefix_string = ""
|
||||
if self.key in COLORS:
|
||||
prefix_string = "[%s] " % CHANNEL_COLORS.get(self.key.lower())
|
||||
p_str = CHANNEL_COLORS.get(self.key.lower())
|
||||
else:
|
||||
prefix_string = "[%s] " % self.key.capitalize()
|
||||
return prefix_string
|
||||
p_str = self.key.capitalize()
|
||||
return f"[{p_str}] "
|
||||
```
|
||||
Additional hint: To make colors easier to change from one place you could instead put the
|
||||
`CHANNEL_COLORS` dict in your settings file and import it as `from django.conf.settings import
|
||||
|
|
|
|||
|
|
@ -82,16 +82,16 @@ class CmdEcho(default_cmds.MuxCommand):
|
|||
"""
|
||||
This is called at the initial shout.
|
||||
"""
|
||||
self.caller.msg("You shout '%s' and wait for an echo ..." % self.args)
|
||||
self.caller.msg(f"You shout '{self.args}' and wait for an echo ...")
|
||||
# this waits non-blocking for 10 seconds, then calls self.echo
|
||||
utils.delay(10, self.echo) # call echo after 10 seconds
|
||||
|
||||
def echo(self):
|
||||
"Called after 10 seconds."
|
||||
shout = self.args
|
||||
string = "You hear an echo: %s ... %s ... %s"
|
||||
string = string % (shout.upper(), shout.capitalize(), shout.lower())
|
||||
self.caller.msg(string)
|
||||
self.caller.msg(
|
||||
f"You hear an echo: {shout.upper()} ... {shout.capitalize()} ... {shout.lower()}"
|
||||
)
|
||||
```
|
||||
|
||||
Import this new echo command into the default command set and reload the server. You will find that
|
||||
|
|
@ -146,7 +146,7 @@ class CmdEcho(default_cmds.MuxCommand):
|
|||
|
||||
def func(self):
|
||||
"This sets off a chain of delayed calls"
|
||||
self.caller.msg("You shout '%s', waiting for an echo ..." % self.args)
|
||||
self.caller.msg(f"You shout '{self.args}', waiting for an echo ...")
|
||||
|
||||
# wait 2 seconds before calling self.echo1
|
||||
utils.delay(2, self.echo1)
|
||||
|
|
@ -154,19 +154,19 @@ class CmdEcho(default_cmds.MuxCommand):
|
|||
# callback chain, started above
|
||||
def echo1(self):
|
||||
"First echo"
|
||||
self.caller.msg("... %s" % self.args.upper())
|
||||
self.caller.msg(f"... {self.args.upper()}")
|
||||
# wait 2 seconds for the next one
|
||||
utils.delay(2, self.echo2)
|
||||
|
||||
def echo2(self):
|
||||
"Second echo"
|
||||
self.caller.msg("... %s" % self.args.capitalize())
|
||||
self.caller.msg(f"... {self.args.capitalize()}")
|
||||
# wait another 2 seconds
|
||||
utils.delay(2, callback=self.echo3)
|
||||
|
||||
def echo3(self):
|
||||
"Last echo"
|
||||
self.caller.msg("... %s ..." % self.args.lower())
|
||||
self.caller.msg(f"... {self.args.lower()} ...")
|
||||
```
|
||||
|
||||
The above version will have the echoes arrive one after another, each separated by a two second
|
||||
|
|
@ -364,9 +364,9 @@ from evennia import default_cmds, utils
|
|||
def echo(caller, args):
|
||||
"Called after 10 seconds."
|
||||
shout = args
|
||||
string = "You hear an echo: %s ... %s ... %s"
|
||||
string = string % (shout.upper(), shout.capitalize(), shout.lower())
|
||||
caller.msg(string)
|
||||
caller.msg(
|
||||
f"You hear an echo: {shout.upper()} ... {shout.capitalize()} ... {shout.lower()}"
|
||||
)
|
||||
|
||||
class CmdEcho(default_cmds.MuxCommand):
|
||||
"""
|
||||
|
|
@ -384,7 +384,7 @@ class CmdEcho(default_cmds.MuxCommand):
|
|||
"""
|
||||
This is called at the initial shout.
|
||||
"""
|
||||
self.caller.msg("You shout '%s' and wait for an echo ..." % self.args)
|
||||
self.caller.msg(f"You shout '{self.args}' and wait for an echo ...")
|
||||
# this waits non-blocking for 10 seconds, then calls echo(self.caller, self.args)
|
||||
utils.delay(10, echo, self.caller, self.args, persistent=True) # changes!
|
||||
|
||||
|
|
|
|||
|
|
@ -59,10 +59,8 @@ Here is a simple example of the prompt sent/updated from a command class:
|
|||
self.caller.msg("Not a valid target!")
|
||||
return
|
||||
|
||||
text = "You diagnose %s as having " \
|
||||
"%i health, %i mana and %i stamina." \
|
||||
% (hp, mp, sp)
|
||||
prompt = "%i HP, %i MP, %i SP" % (hp, mp, sp)
|
||||
text = f"You diagnose {target} as having {hp} health, {mp} mana and {sp} stamina."
|
||||
prompt = f"{hp} HP, {mp} MP, {sp} SP"
|
||||
self.caller.msg(text, prompt=prompt)
|
||||
```
|
||||
## A prompt sent with every command
|
||||
|
|
@ -86,9 +84,7 @@ class MuxCommand(default_cmds.MuxCommand):
|
|||
def at_post_cmd(self):
|
||||
"called after self.func()."
|
||||
caller = self.caller
|
||||
prompt = "%i HP, %i MP, %i SP" % (caller.db.hp,
|
||||
caller.db.mp,
|
||||
caller.db.sp)
|
||||
prompt = f"{caller.db.hp} HP, {caller.db.mp} MP, {caller.db.sp} SP"
|
||||
caller.msg(prompt=prompt)
|
||||
|
||||
```
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ class CmdExitError(default_cmds.MuxCommand):
|
|||
auto_help = False
|
||||
def func(self):
|
||||
"returns the error"
|
||||
self.caller.msg("You cannot move %s." % self.key)
|
||||
self.caller.msg(f"You cannot move {self.key}.")
|
||||
|
||||
class CmdExitErrorNorth(CmdExitError):
|
||||
key = "north"
|
||||
|
|
|
|||
|
|
@ -127,15 +127,14 @@ class Character(DefaultCharacter):
|
|||
|
||||
if selfaccount and selfaccount.db.is_gm:
|
||||
# A GM. Show name as name(GM)
|
||||
name = "%s(GM)" % name
|
||||
name = f"{name}(GM)"
|
||||
|
||||
if lookaccount and \
|
||||
(lookaccount.permissions.get("Developers") or lookaccount.db.is_gm):
|
||||
# Developers/GMs see name(#dbref) or name(GM)(#dbref)
|
||||
return "%s(#%s)" % (name, self.id)
|
||||
else:
|
||||
return name
|
||||
name = f"{name}(#{self.id})"
|
||||
|
||||
return name
|
||||
```
|
||||
|
||||
Above, we change how the Character's name is displayed: If the account controlling this Character is
|
||||
|
|
@ -192,10 +191,10 @@ class CmdMakeGM(default_cmds.MuxCommand):
|
|||
|
||||
accountlist = evennia.search_account(self.args) # returns a list
|
||||
if not accountlist:
|
||||
caller.msg("Could not find account '%s'" % self.args)
|
||||
caller.msg(f"Could not find account '{self.args}'")
|
||||
return
|
||||
elif len(accountlist) > 1:
|
||||
caller.msg("Multiple matches for '%s': %s" % (self.args, accountlist))
|
||||
caller.msg(f"Multiple matches for '{self.args}': {accountlist}")
|
||||
return
|
||||
else:
|
||||
account = accountlist[0]
|
||||
|
|
@ -203,20 +202,20 @@ class CmdMakeGM(default_cmds.MuxCommand):
|
|||
if self.cmdstring == "gm":
|
||||
# turn someone into a GM
|
||||
if account.permissions.get("Admins"):
|
||||
caller.msg("Account %s is already a GM." % account)
|
||||
caller.msg(f"Account {account} is already a GM.")
|
||||
else:
|
||||
account.permissions.add("Admins")
|
||||
caller.msg("Account %s is now a GM." % account)
|
||||
account.msg("You are now a GM (changed by %s)." % caller)
|
||||
caller.msg(f"Account {account} is now a GM.")
|
||||
account.msg(f"You are now a GM (changed by {caller}).")
|
||||
account.character.db.is_gm = True
|
||||
else:
|
||||
# @ungm was entered - revoke GM status from someone
|
||||
if not account.permissions.get("Admins"):
|
||||
caller.msg("Account %s is not a GM." % account)
|
||||
caller.msg(f"Account {account} is not a GM.")
|
||||
else:
|
||||
account.permissions.remove("Admins")
|
||||
caller.msg("Account %s is no longer a GM." % account)
|
||||
account.msg("You are no longer a GM (changed by %s)." % caller)
|
||||
caller.msg(f"Account {account} is no longer a GM.")
|
||||
account.msg(f"You are no longer a GM (changed by {caller}).")
|
||||
del account.character.db.is_gm
|
||||
|
||||
```
|
||||
|
|
@ -511,11 +510,12 @@ ALLOWED_FIELDNAMES = ALLOWED_ATTRS + \
|
|||
def _validate_fieldname(caller, fieldname):
|
||||
"Helper function to validate field names."
|
||||
if fieldname not in ALLOWED_FIELDNAMES:
|
||||
err = "Allowed field names: %s" % (", ".join(ALLOWED_FIELDNAMES))
|
||||
list_of_fieldnames = ", ".join(ALLOWED_FIELDNAMES)
|
||||
err = f"Allowed field names: {list_of_fieldnames}"
|
||||
caller.msg(err)
|
||||
return False
|
||||
if fieldname in ALLOWED_ATTRS and not value.isdigit():
|
||||
caller.msg("%s must receive a number." % fieldname)
|
||||
caller.msg(f"{fieldname} must receive a number.")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
|
@ -570,7 +570,7 @@ class CmdSheet(MuxCommand):
|
|||
else:
|
||||
caller.chardata[fieldname] = value
|
||||
caller.update_charsheet()
|
||||
caller.msg("%s was set to %s." % (fieldname, value))
|
||||
caller.msg(f"{fieldname} was set to {value}.")
|
||||
|
||||
```
|
||||
|
||||
|
|
@ -641,13 +641,13 @@ class CmdGMsheet(MuxCommand):
|
|||
caller.msg("The character sheet is already locked.")
|
||||
else:
|
||||
character.db.sheet_locked = True
|
||||
caller.msg("%s can no longer edit their character sheet." % character.key)
|
||||
caller.msg(f"{character.key} can no longer edit their character sheet.")
|
||||
elif "unlock" in self.switches:
|
||||
if not character.db.sheet_locked:
|
||||
caller.msg("The character sheet is already unlocked.")
|
||||
else:
|
||||
character.db.sheet_locked = False
|
||||
caller.msg("%s can now edit their character sheet." % character.key)
|
||||
caller.msg(f"{character.key} can now edit their character sheet.")
|
||||
|
||||
if fieldname:
|
||||
if fieldname == "name":
|
||||
|
|
@ -655,7 +655,7 @@ class CmdGMsheet(MuxCommand):
|
|||
else:
|
||||
character.db.chardata[fieldname] = value
|
||||
character.update_charsheet()
|
||||
caller.msg("You set %s's %s to %s." % (character.key, fieldname, value)
|
||||
caller.msg(f"You set {character.key}'s {fieldname} to {value}.")
|
||||
else:
|
||||
# just display
|
||||
caller.msg(character.db.charsheet)
|
||||
|
|
|
|||
|
|
@ -252,11 +252,10 @@ class CmdTime(Command):
|
|||
def func(self):
|
||||
"""Execute the time command."""
|
||||
# Get the absolute game time
|
||||
year, month, day, hour, min, sec = custom_gametime.custom_gametime(absolute=True)
|
||||
string = "We are in year {year}, day {day}, month {month}."
|
||||
string += "\nIt's {hour:02}:{min:02}:{sec:02}."
|
||||
self.msg(string.format(year=year, month=month, day=day,
|
||||
hour=hour, min=min, sec=sec))
|
||||
year, month, day, hour, mins, secs = custom_gametime.custom_gametime(absolute=True)
|
||||
time_string = f"We are in year {year}, day {day}, month {month}."
|
||||
time_string += f"\nIt's {hour:02}:{mins:02}:{secs:02}."
|
||||
self.msg(time_string)
|
||||
```
|
||||
|
||||
Don't forget to add it in your CharacterCmdSet to see this command:
|
||||
|
|
|
|||
|
|
@ -87,10 +87,12 @@ class CmdInventory(MuxCommand):
|
|||
table.border = False
|
||||
for item in items:
|
||||
second = item.get_mass() \
|
||||
if 'weight' in self.switches else item.db.desc
|
||||
table.add_row(["%s" % item.get_display_name(self.caller.sessions),
|
||||
second and second or ""])
|
||||
string = "|wYou are carrying:\n%s" % table
|
||||
if "weight" in self.switches else item.db.desc
|
||||
table.add_row([
|
||||
str(item.get_display_name(self.caller.sessions)),
|
||||
second and second or "",
|
||||
])
|
||||
string = f"|wYou are carrying:\n{table}"
|
||||
self.caller.msg(string)
|
||||
|
||||
```
|
||||
|
|
@ -86,18 +86,17 @@ def menunode_shopfront(caller):
|
|||
# door! Let's remove that from our for sale list.
|
||||
wares = [ware for ware in wares if ware.key.lower() != "door"]
|
||||
|
||||
text = "*** Welcome to %s! ***\n" % shopname
|
||||
text = f"*** Welcome to {shopname}! ***\n"
|
||||
if wares:
|
||||
text += " Things for sale (choose 1-%i to inspect);" \
|
||||
" quit to exit:" % len(wares)
|
||||
text += f" Things for sale (choose 1-{len(wares)} to inspect); quit to exit:"
|
||||
else:
|
||||
text += " There is nothing for sale; quit to exit."
|
||||
|
||||
options = []
|
||||
for ware in wares:
|
||||
# add an option for every ware in store
|
||||
options.append({"desc": "%s (%s gold)" %
|
||||
(ware.key, ware.db.gold_value or 1),
|
||||
gold_val = ware.db.gold_value or 1
|
||||
options.append({"desc": f"{ware.key} ({gold_val} gold)",
|
||||
"goto": "menunode_inspect_and_buy"})
|
||||
return text, options
|
||||
```
|
||||
|
|
@ -124,26 +123,27 @@ def menunode_inspect_and_buy(caller, raw_string):
|
|||
ware = wares[iware]
|
||||
value = ware.db.gold_value or 1
|
||||
wealth = caller.db.gold or 0
|
||||
text = "You inspect %s:\n\n%s" % (ware.key, ware.db.desc)
|
||||
text = f"You inspect {ware.key}:\n\n{ware.db.desc}"
|
||||
|
||||
def buy_ware_result(caller):
|
||||
"This will be executed first when choosing to buy."
|
||||
if wealth >= value:
|
||||
rtext = "You pay %i gold and purchase %s!" % \
|
||||
(value, ware.key)
|
||||
rtext = f"You pay {value} gold and purchase {ware.key}!"
|
||||
caller.db.gold -= value
|
||||
ware.move_to(caller, quiet=True)
|
||||
else:
|
||||
rtext = "You cannot afford %i gold for %s!" % \
|
||||
(value, ware.key)
|
||||
rtext = f"You cannot afford {value} gold for {ware.key}!"
|
||||
caller.msg(rtext)
|
||||
|
||||
options = ({"desc": "Buy %s for %s gold" % \
|
||||
(ware.key, ware.db.gold_value or 1),
|
||||
"goto": "menunode_shopfront",
|
||||
"exec": buy_ware_result},
|
||||
{"desc": "Look for something else",
|
||||
"goto": "menunode_shopfront"})
|
||||
gold_val = ware.db.gold_value or 1
|
||||
options = ({
|
||||
"desc": f"Buy {ware.key} for {gold_val} gold",
|
||||
"goto": "menunode_shopfront",
|
||||
"exec": buy_ware_result,
|
||||
}, {
|
||||
"desc": "Look for something else",
|
||||
"goto": "menunode_shopfront",
|
||||
})
|
||||
|
||||
return text, options
|
||||
```
|
||||
|
|
@ -267,7 +267,7 @@ class CmdBuildShop(Command):
|
|||
key=shopname,
|
||||
location=None)
|
||||
storeroom = create_object(DefaultRoom,
|
||||
key="%s-storage" % shopname,
|
||||
key=f"{shopname}-storage",
|
||||
location=None)
|
||||
shop.db.storeroom = storeroom
|
||||
# create a door between the two
|
||||
|
|
@ -281,15 +281,15 @@ class CmdBuildShop(Command):
|
|||
location=storeroom,
|
||||
destination=shop)
|
||||
# make a key for accessing the store room
|
||||
storeroom_key_name = "%s-storekey" % shopname
|
||||
storeroom_key_name = f"{shopname}-storekey"
|
||||
storeroom_key = create_object(DefaultObject,
|
||||
key=storeroom_key_name,
|
||||
location=shop)
|
||||
# only allow chars with this key to enter the store room
|
||||
shop_exit.locks.add("traverse:holds(%s)" % storeroom_key_name)
|
||||
shop_exit.locks.add(f"traverse:holds({storeroom_key_name})")
|
||||
|
||||
# inform the builder about progress
|
||||
self.caller.msg("The shop %s was created!" % shop)
|
||||
self.caller.msg(f"The shop {shop} was created!")
|
||||
```
|
||||
|
||||
Our typeclass is simple and so is our `buildshop` command. The command (which is for Builders only)
|
||||
|
|
|
|||
|
|
@ -172,7 +172,7 @@ def add_XP(character, amount):
|
|||
character.db.level += 1
|
||||
character.db.STR += 1
|
||||
character.db.combat += 2
|
||||
character.msg("You are now level %i!" % character.db.level)
|
||||
character.msg(f"You are now level {character.db.level}!")
|
||||
|
||||
def skill_combat(*args):
|
||||
"""
|
||||
|
|
@ -182,24 +182,24 @@ def skill_combat(*args):
|
|||
"""
|
||||
char1, char2 = args
|
||||
roll1, roll2 = roll_hit(), roll_hit()
|
||||
failtext = "You are hit by %s for %i damage!"
|
||||
wintext = "You hit %s for %i damage!"
|
||||
failtext_template = "You are hit by {attacker} for {dmg} damage!"
|
||||
wintext_template = "You hit {target} for {dmg} damage!"
|
||||
xp_gain = randint(1, 3)
|
||||
if char1.db.combat >= roll1 > roll2:
|
||||
# char 1 hits
|
||||
dmg = roll_dmg() + char1.db.STR
|
||||
char1.msg(wintext % (char2, dmg))
|
||||
char1.msg(wintext_template.format(target=char2, dmg=dmg))
|
||||
add_XP(char1, xp_gain)
|
||||
char2.msg(failtext % (char1, dmg))
|
||||
char2.msg(failtext_template.format(attacker=char1, dmg=dmg))
|
||||
char2.db.HP -= dmg
|
||||
check_defeat(char2)
|
||||
elif char2.db.combat >= roll2 > roll1:
|
||||
# char 2 hits
|
||||
dmg = roll_dmg() + char2.db.STR
|
||||
char1.msg(failtext % (char2, dmg))
|
||||
char1.msg(failtext_template.format(attacker=char2, dmg=dmg))
|
||||
char1.db.HP -= dmg
|
||||
check_defeat(char1)
|
||||
char2.msg(wintext % (char1, dmg))
|
||||
char2.msg(wintext_template.format(target=char1, dmg=dmg))
|
||||
add_XP(char2, xp_gain)
|
||||
else:
|
||||
# a draw
|
||||
|
|
@ -217,7 +217,7 @@ def roll_challenge(character1, character2, skillname):
|
|||
if skillname in SKILLS:
|
||||
SKILLS[skillname](character1, character2)
|
||||
else:
|
||||
raise RunTimeError("Skillname %s not found." % skillname)
|
||||
raise RunTimeError(f"Skillname {skillname} not found.")
|
||||
```
|
||||
|
||||
These few functions implement the entirety of our simple rule system. We have a function to check
|
||||
|
|
|
|||
|
|
@ -113,7 +113,7 @@ class CombatHandler(DefaultScript):
|
|||
def at_script_creation(self):
|
||||
"Called when script is first created"
|
||||
|
||||
self.key = "combat_handler_%i" % random.randint(1, 1000)
|
||||
self.key = f"combat_handler_{random.randint(1, 1000)}"
|
||||
self.desc = "handles combat"
|
||||
self.interval = 60 * 2 # two minute timeout
|
||||
self.start_delay = True
|
||||
|
|
@ -400,57 +400,58 @@ def resolve_combat(combat_handler, actiondict):
|
|||
taction, tchar, ttarget = actiondict[target.id][isub]
|
||||
if action == "hit":
|
||||
if taction == "parry" and ttarget == char:
|
||||
msg = "%s tries to hit %s, but %s parries the attack!"
|
||||
messages.append(msg % (char, tchar, tchar))
|
||||
messages.append(
|
||||
f"{char} tries to hit {tchar}, but {tchar} parries the attack!"
|
||||
)
|
||||
elif taction == "defend" and random.random() < 0.5:
|
||||
msg = "%s defends against the attack by %s."
|
||||
messages.append(msg % (tchar, char))
|
||||
messages.append(
|
||||
f"{tchar} defends against the attack by {char}."
|
||||
)
|
||||
elif taction == "flee":
|
||||
msg = "%s stops %s from disengaging, with a hit!"
|
||||
flee[tchar] = -2
|
||||
messages.append(msg % (char, tchar))
|
||||
messages.append(
|
||||
f"{char} stops {tchar} from disengaging, with a hit!"
|
||||
)
|
||||
else:
|
||||
msg = "%s hits %s, bypassing their %s!"
|
||||
messages.append(msg % (char, tchar, taction))
|
||||
messages.append(
|
||||
f"{char} hits {tchar}, bypassing their {taction}!"
|
||||
)
|
||||
elif action == "parry":
|
||||
if taction == "hit":
|
||||
msg = "%s parries the attack by %s."
|
||||
messages.append(msg % (char, tchar))
|
||||
messages.append(f"{char} parries the attack by {tchar}.")
|
||||
elif taction == "feint":
|
||||
msg = "%s tries to parry, but %s feints and hits!"
|
||||
messages.append(msg % (char, tchar))
|
||||
messages.append(
|
||||
f"{char} tries to parry, but {tchar} feints and hits!"
|
||||
)
|
||||
else:
|
||||
msg = "%s parries to no avail."
|
||||
messages.append(msg % char)
|
||||
messages.append(f"{char} parries to no avail.")
|
||||
elif action == "feint":
|
||||
if taction == "parry":
|
||||
msg = "%s feints past %s's parry, landing a hit!"
|
||||
messages.append(msg % (char, tchar))
|
||||
messages.append(
|
||||
f"{char} feints past {tchar}'s parry, landing a hit!"
|
||||
)
|
||||
elif taction == "hit":
|
||||
msg = "%s feints but is defeated by %s hit!"
|
||||
messages.append(msg % (char, tchar))
|
||||
messages.append(f"{char} feints but is defeated by {tchar}'s hit!")
|
||||
else:
|
||||
msg = "%s feints to no avail."
|
||||
messages.append(msg % char)
|
||||
messages.append(f"{char} feints to no avail.")
|
||||
elif action == "defend":
|
||||
msg = "%s defends."
|
||||
messages.append(msg % char)
|
||||
messages.append(f"{char} defends.")
|
||||
elif action == "flee":
|
||||
if char in flee:
|
||||
flee[char] += 1
|
||||
else:
|
||||
flee[char] = 1
|
||||
msg = "%s tries to disengage (two subsequent turns needed)"
|
||||
messages.append(msg % char)
|
||||
messages.append(
|
||||
f"{char} tries to disengage (two subsequent turns needed)"
|
||||
)
|
||||
|
||||
# echo results of each subturn
|
||||
combat_handler.msg_all("\n".join(messages))
|
||||
|
||||
# at the end of both sub-turns, test if anyone fled
|
||||
msg = "%s withdraws from combat."
|
||||
for (char, fleevalue) in flee.items():
|
||||
if fleevalue == 2:
|
||||
combat_handler.msg_all(msg % char)
|
||||
combat_handler.msg_all(f"{char} withdraws from combat.")
|
||||
combat_handler.remove_character(char)
|
||||
```
|
||||
|
||||
|
|
@ -495,14 +496,14 @@ class CmdAttack(Command):
|
|||
if target.ndb.combat_handler:
|
||||
# target is already in combat - join it
|
||||
target.ndb.combat_handler.add_character(self.caller)
|
||||
target.ndb.combat_handler.msg_all("%s joins combat!" % self.caller)
|
||||
target.ndb.combat_handler.msg_all(f"{self.caller} joins combat!")
|
||||
else:
|
||||
# create a new combat handler
|
||||
chandler = create_script("combat_handler.CombatHandler")
|
||||
chandler.add_character(self.caller)
|
||||
chandler.add_character(target)
|
||||
self.caller.msg("You attack %s! You are in combat." % target)
|
||||
target.msg("%s attacks you! You are in combat." % self.caller)
|
||||
self.caller.msg(f"You attack {target}! You are in combat.")
|
||||
target.msg(f"{self.caller} attacks you! You are in combat.")
|
||||
```
|
||||
|
||||
The `attack` command will not go into the combat cmdset but rather into the default cmdset. See e.g.
|
||||
|
|
|
|||
|
|
@ -150,7 +150,7 @@ class CmdSetPower(Command):
|
|||
return
|
||||
# at this point the argument is tested as valid. Let's set it.
|
||||
self.caller.db.power = power
|
||||
self.caller.msg("Your Power was set to %i." % power)
|
||||
self.caller.msg(f"Your Power was set to {power}.")
|
||||
```
|
||||
This is a pretty straightforward command. We do some error checking, then set the power on ourself.
|
||||
We use a `help_category` of "mush" for all our commands, just so they are easy to find and separate
|
||||
|
|
@ -295,11 +295,17 @@ class CmdAttack(Command):
|
|||
caller.db.combat_score = combat_score
|
||||
|
||||
# announce
|
||||
message = "%s +attack%s with a combat score of %s!"
|
||||
caller.msg(message % ("You", "", combat_score))
|
||||
caller.location.msg_contents(message %
|
||||
(caller.key, "s", combat_score),
|
||||
exclude=caller)
|
||||
message_template = "{attacker} +attack{s} with a combat score of {c_score}!"
|
||||
caller.msg(message_template.format(
|
||||
attacker="You",
|
||||
s="",
|
||||
c_score=combat_score,
|
||||
))
|
||||
caller.location.msg_contents(message_template.format(
|
||||
attacker=caller.key,
|
||||
s="s",
|
||||
c_score=combat_score,
|
||||
), exclude=caller)
|
||||
```
|
||||
|
||||
What we do here is simply to generate a "combat score" using Python's inbuilt `random.randint()`
|
||||
|
|
@ -359,7 +365,7 @@ class Character(DefaultCharacter):
|
|||
looker sees when looking at this object.
|
||||
"""
|
||||
text = super().return_appearance(looker)
|
||||
cscore = " (combat score: %s)" % self.db.combat_score
|
||||
cscore = f" (combat score: {self.db.combat_score})"
|
||||
if "\n" in text:
|
||||
# text is multi-line, add score after first line
|
||||
first_line, rest = text.split("\n", 1)
|
||||
|
|
@ -435,12 +441,17 @@ class CmdCreateNPC(Command):
|
|||
npc = create_object("characters.Character",
|
||||
key=name,
|
||||
location=caller.location,
|
||||
locks="edit:id(%i) and perm(Builders);call:false()" % caller.id)
|
||||
locks=f"edit:id({caller.id}) and perm(Builders);call:false()")
|
||||
# announce
|
||||
message = "%s created the NPC '%s'."
|
||||
caller.msg(message % ("You", name))
|
||||
caller.location.msg_contents(message % (caller.key, name),
|
||||
exclude=caller)
|
||||
message_template = "{creator} created the NPC '{npc}'."
|
||||
caller.msg(message_template.format(
|
||||
creator="You",
|
||||
npc=name,
|
||||
))
|
||||
caller.location.msg_contents(message_template.format(
|
||||
creator=caller.key,
|
||||
npt=name,
|
||||
), exclude=caller)
|
||||
```
|
||||
Here we define a `+createnpc` (`+createNPC` works too) that is callable by everyone *not* having the
|
||||
`nonpcs` "[permission](../../../Components/Locks#Permissions)" (in Evennia, a "permission" can just as well be used to
|
||||
|
|
@ -532,10 +543,10 @@ class CmdEditNPC(Command):
|
|||
return
|
||||
if not self.propname:
|
||||
# this means we just list the values
|
||||
output = "Properties of %s:" % npc.key
|
||||
output = f"Properties of {npc.key}:"
|
||||
for propname in allowed_propnames:
|
||||
propvalue = npc.attributes.get(propname, default="N/A")
|
||||
output += "\n %s = %s" % (propname, propvalue)
|
||||
output += f"\n {propname} = {propvalue}"
|
||||
caller.msg(output)
|
||||
elif self.propname not in allowed_propnames:
|
||||
caller.msg("You may only change %s." %
|
||||
|
|
@ -619,7 +630,7 @@ class CmdNPC(Command):
|
|||
return
|
||||
# send the command order
|
||||
npc.execute_cmd(self.cmdname)
|
||||
caller.msg("You told %s to do '%s'." % (npc.key, self.cmdname))
|
||||
caller.msg(f"You told {npc.key} to do '{self.cmdname}'.")
|
||||
```
|
||||
|
||||
Note that if you give an erroneous command, you will not see any error message, since that error
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ class Npc(Character):
|
|||
message = message.split('says, ')[1].strip(' "')
|
||||
|
||||
# we'll make use of this in .msg() below
|
||||
return "%s said: '%s'" % (from_obj, message)
|
||||
return f"{from_obj} said: '{message}'"
|
||||
```
|
||||
|
||||
When someone in the room speaks to this NPC, its `msg` method will be called. We will modify the
|
||||
|
|
@ -60,7 +60,7 @@ class Npc(Character):
|
|||
# If there is a response
|
||||
if response != None:
|
||||
# speak ourselves, using the return
|
||||
self.execute_cmd("say %s" % response)
|
||||
self.execute_cmd(f"say {response}")
|
||||
|
||||
# this is needed if anyone ever puppets this NPC - without it you would never
|
||||
# get any feedback from the server (not even the results of look)
|
||||
|
|
|
|||
|
|
@ -66,16 +66,16 @@ command
|
|||
|
||||
keys = prototypes.keys()
|
||||
nprots = len(prototypes)
|
||||
tweet = "Prototype Count: %s Random Keys: " % nprots
|
||||
tweet = f"Prototype Count: {nprots} Random Keys: "
|
||||
|
||||
tweet += " %s" % keys[randint(0,len(keys)-1)]
|
||||
tweet += f" {keys[randint(0,len(keys)-1)]}"
|
||||
for x in range(0,2): ##tweet 3
|
||||
tweet += ", %s" % keys[randint(0,len(keys)-1)]
|
||||
tweet += f", {keys[randint(0,len(keys)-1)]}"
|
||||
# post the tweet
|
||||
try:
|
||||
response = api.PostUpdate(tweet)
|
||||
except:
|
||||
logger.log_trace("Tweet Error: When attempting to tweet %s" % tweet)
|
||||
logger.log_trace(f"Tweet Error: When attempting to tweet {tweet}")
|
||||
```
|
||||
|
||||
In the `at_script_creation` method, we configure the script to fire immediately (useful for testing)
|
||||
|
|
|
|||
|
|
@ -293,7 +293,7 @@ class TrainObject(DefaultObject):
|
|||
roomref = self.db.rooms[idx]
|
||||
room = search_object(roomref)[0]
|
||||
self.move_to(room)
|
||||
self.msg_contents("The train is moving forward to %s." % (room.name, ))
|
||||
self.msg_contents(f"The train is moving forward to {room.name}.")
|
||||
```
|
||||
|
||||
We added a lot of code here. Since we changed the `at_object_creation` to add in variables we will
|
||||
|
|
|
|||
|
|
@ -246,8 +246,12 @@ def creating(request):
|
|||
user.db._playable_characters.append(char)
|
||||
# add the right locks for the character so the account can
|
||||
# puppet it
|
||||
char.locks.add("puppet:id(%i) or pid(%i) or perm(Developers) "
|
||||
"or pperm(Developers)" % (char.id, user.id))
|
||||
char.locks.add(" or ".join([
|
||||
f"puppet:id({char.id})",
|
||||
f"pid({user.id})",
|
||||
"perm(Developers)",
|
||||
"pperm(Developers)",
|
||||
]))
|
||||
char.db.background = background # set the character background
|
||||
return HttpResponseRedirect('/chargen')
|
||||
else:
|
||||
|
|
@ -332,8 +336,12 @@ def creating(request):
|
|||
user.db._playable_characters.append(char)
|
||||
# add the right locks for the character so the account can
|
||||
# puppet it
|
||||
char.locks.add("puppet:id(%i) or pid(%i) or perm(Developers) "
|
||||
"or pperm(Developers)" % (char.id, user.id))
|
||||
char.locks.add(" or ".join([
|
||||
f"puppet:id({char.id})",
|
||||
f"pid({user.id})",
|
||||
"perm(Developers)",
|
||||
"pperm(Developers)",
|
||||
]))
|
||||
char.db.background = background # set the character background
|
||||
return HttpResponseRedirect('/chargen')
|
||||
else:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue