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:
Dimitri 2021-10-12 12:13:42 -06:00
parent f45051050e
commit 851ca30be5
30 changed files with 207 additions and 193 deletions

View file

@ -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

View file

@ -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.

View file

@ -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