Ran formatting on code

This commit is contained in:
Griatch 2022-10-31 20:43:27 +01:00
parent 83154de19e
commit 353e4c0aa7
20 changed files with 296 additions and 327 deletions

View file

@ -343,6 +343,7 @@ class CraftingRecipeBase:
class NonExistentRecipe(CraftingRecipeBase):
"""A recipe that does not exist and never produces anything."""
allow_craft = True
allow_reuse = True

View file

@ -61,21 +61,21 @@ from django.conf import settings
from evennia import CmdSet
from evennia.commands.default.muxcommand import MuxCommand
_BASIC_MAP_SIZE = settings.BASIC_MAP_SIZE if hasattr(settings, 'BASIC_MAP_SIZE') else 2
_MAX_MAP_SIZE = settings.BASIC_MAP_SIZE if hasattr(settings, 'MAX_MAP_SIZE') else 10
_BASIC_MAP_SIZE = settings.BASIC_MAP_SIZE if hasattr(settings, "BASIC_MAP_SIZE") else 2
_MAX_MAP_SIZE = settings.BASIC_MAP_SIZE if hasattr(settings, "MAX_MAP_SIZE") else 10
# _COMPASS_DIRECTIONS specifies which way to move the pointer on the x/y axes and what characters to use to depict the exits on the map.
_COMPASS_DIRECTIONS = {
'north': (0, -3, ' | '),
'south': (0, 3, ' | '),
'east': (3, 0, '-'),
'west': (-3, 0, '-'),
'northeast': (3, -3, '/'),
'northwest': (-3, -3, '\\'),
'southeast': (3, 3, '\\'),
'southwest': (-3, 3, '/'),
'up': (0, 0, '^'),
'down': (0, 0, 'v')
"north": (0, -3, " | "),
"south": (0, 3, " | "),
"east": (3, 0, "-"),
"west": (-3, 0, "-"),
"northeast": (3, -3, "/"),
"northwest": (-3, -3, "\\"),
"southeast": (3, 3, "\\"),
"southwest": (-3, 3, "/"),
"up": (0, 0, "^"),
"down": (0, 0, "v"),
}
@ -91,7 +91,7 @@ class Map(object):
"""
self.start_time = time.time()
self.caller = caller
self.max_width = int(size * 2 + 1) * 5 # This must be an odd number
self.max_width = int(size * 2 + 1) * 5 # This must be an odd number
self.max_length = int(size * 2 + 1) * 3 # This must be an odd number
self.has_mapped = {}
self.curX = None
@ -109,8 +109,8 @@ class Map(object):
board = []
for row in range(self.max_length):
board.append([])
for column in range(int(self.max_width/5)):
board[row].extend([' ', ' ', ' '])
for column in range(int(self.max_width / 5)):
board[row].extend([" ", " ", " "])
return board
def exit_name_as_ordinal(self, ex):
@ -124,11 +124,13 @@ class Map(object):
"""
exit_name = ex.name
if exit_name not in _COMPASS_DIRECTIONS:
compass_aliases = [direction in ex.aliases.all() for direction in _COMPASS_DIRECTIONS.keys()]
compass_aliases = [
direction in ex.aliases.all() for direction in _COMPASS_DIRECTIONS.keys()
]
if compass_aliases[0]:
exit_name = compass_aliases[0]
if exit_name not in _COMPASS_DIRECTIONS:
return ''
return ""
return exit_name
def update_pos(self, room, exit_name):
@ -179,7 +181,7 @@ class Map(object):
# Additionally, if the name of the exit is not ordinal but an alias of it is, use that.
for ex in [x for x in room.exits if x.access(self.caller, "traverse")]:
ex_name = self.exit_name_as_ordinal(ex)
if not ex_name or ex_name in ['up', 'down']:
if not ex_name or ex_name in ["up", "down"]:
continue
if self.has_drawn(ex.destination):
continue
@ -201,20 +203,20 @@ class Map(object):
continue
ex_character = _COMPASS_DIRECTIONS[ex_name][2]
delta_x = int(_COMPASS_DIRECTIONS[ex_name][1]/3)
delta_y = int(_COMPASS_DIRECTIONS[ex_name][0]/3)
delta_x = int(_COMPASS_DIRECTIONS[ex_name][1] / 3)
delta_y = int(_COMPASS_DIRECTIONS[ex_name][0] / 3)
# Make modifications if the exit has BOTH up and down exits
if ex_name == 'up':
if 'v' in self.grid[x][y]:
self.render_room(room, x, y, p1='^', p2='v')
if ex_name == "up":
if "v" in self.grid[x][y]:
self.render_room(room, x, y, p1="^", p2="v")
else:
self.render_room(room, x, y, here='^')
elif ex_name == 'down':
if '^' in self.grid[x][y]:
self.render_room(room, x, y, p1='^', p2='v')
self.render_room(room, x, y, here="^")
elif ex_name == "down":
if "^" in self.grid[x][y]:
self.render_room(room, x, y, p1="^", p2="v")
else:
self.render_room(room, x, y, here='v')
self.render_room(room, x, y, here="v")
else:
self.grid[x + delta_x][y + delta_y] = ex_character
@ -234,7 +236,7 @@ class Map(object):
self.has_mapped[room] = [self.curX, self.curY]
self.render_room(room, self.curX, self.curY)
def render_room(self, room, x, y, p1='[', p2=']', here=None):
def render_room(self, room, x, y, p1="[", p2="]", here=None):
"""
Draw a given room with ascii characters
@ -253,7 +255,7 @@ class Map(object):
you[0] = f"{p1}|n"
you[1] = f"{here if here else you[1]}"
if room == self.caller.location:
you[1] = '|[x|co|n' # Highlight the location you are currently in
you[1] = "|[x|co|n" # Highlight the location you are currently in
you[2] = f"{p2}|n"
self.grid[x][y] = "".join(you)
@ -300,6 +302,7 @@ class CmdMap(MuxCommand):
Usage: map (optional size)
"""
key = "map"
def func(self):

View file

@ -17,19 +17,32 @@ class TestIngameMap(BaseEvenniaCommandTest):
Expected output:
[ ]--[ ]
"""
def setUp(self):
super().setUp()
self.west_room = create_object(rooms.Room, key="Room 1")
self.east_room = create_object(rooms.Room, key="Room 2")
create_object(exits.Exit, key="east", aliases=["e"], location=self.west_room, destination=self.east_room)
create_object(exits.Exit, key="west", aliases=["w"], location=self.east_room, destination=self.west_room)
create_object(
exits.Exit,
key="east",
aliases=["e"],
location=self.west_room,
destination=self.east_room,
)
create_object(
exits.Exit,
key="west",
aliases=["w"],
location=self.east_room,
destination=self.west_room,
)
def test_west_room_map_room(self):
self.char1.location = self.west_room
map_here = ingame_map_display.Map(self.char1).show_map()
self.assertEqual(map_here.strip(), '[|n|[x|co|n]|n--[|n ]|n')
self.assertEqual(map_here.strip(), "[|n|[x|co|n]|n--[|n ]|n")
def test_east_room_map_room(self):
self.char1.location = self.east_room
map_here = ingame_map_display.Map(self.char1).show_map()
self.assertEqual(map_here.strip(), '[|n ]|n--[|n|[x|co|n]|n')
self.assertEqual(map_here.strip(), "[|n ]|n--[|n|[x|co|n]|n")

View file

@ -1421,16 +1421,19 @@ class TestBuildExampleGrid(BaseEvenniaTest):
mock_room_callbacks = mock.MagicMock()
mock_exit_callbacks = mock.MagicMock()
class TestXyzRoom(xyzroom.XYZRoom):
def at_object_creation(self):
mock_room_callbacks.at_object_creation()
def at_object_creation(self):
mock_room_callbacks.at_object_creation()
class TestXyzExit(xyzroom.XYZExit):
def at_object_creation(self):
mock_exit_callbacks.at_object_creation()
def at_object_creation(self):
mock_exit_callbacks.at_object_creation()
MAP_DATA = {
"map": """
"map": """
+ 0 1
@ -1439,35 +1442,37 @@ MAP_DATA = {
+ 0 1
""",
"zcoord": "map1",
"prototypes": {
("*", "*"): {
"key": "room",
"desc": "A room.",
"prototype_parent": "xyz_room",
},
("*", "*", "*"): {
"desc": "A passage.",
"prototype_parent": "xyz_exit",
}
},
"options": {
"map_visual_range": 1,
"map_mode": "scan",
}
"zcoord": "map1",
"prototypes": {
("*", "*"): {
"key": "room",
"desc": "A room.",
"prototype_parent": "xyz_room",
},
("*", "*", "*"): {
"desc": "A passage.",
"prototype_parent": "xyz_exit",
},
},
"options": {
"map_visual_range": 1,
"map_mode": "scan",
},
}
class TestCallbacks(BaseEvenniaTest):
def setUp(self):
super().setUp()
mock_room_callbacks.reset_mock()
mock_exit_callbacks.reset_mock()
def setup_grid(self, map_data):
self.grid, err = xyzgrid.XYZGrid.create("testgrid")
def _log(msg):
print(msg)
print(msg)
self.grid.log = _log
self.map_data = map_data
@ -1489,5 +1494,9 @@ class TestCallbacks(BaseEvenniaTest):
self.grid.spawn()
# Two rooms and 2 exits, Each one should have gotten one `at_object_creation` callback.
self.assertEqual(mock_room_callbacks.at_object_creation.mock_calls, [mock.call(), mock.call()])
self.assertEqual(mock_exit_callbacks.at_object_creation.mock_calls, [mock.call(), mock.call()])
self.assertEqual(
mock_room_callbacks.at_object_creation.mock_calls, [mock.call(), mock.call()]
)
self.assertEqual(
mock_exit_callbacks.at_object_creation.mock_calls, [mock.call(), mock.call()]
)

View file

@ -321,7 +321,9 @@ class MapNode:
# with proper coordinates etc
typeclass = self.prototype.get("typeclass")
if typeclass is None:
raise MapError(f"The prototype {self.prototype} for this node has no 'typeclass' key.", self)
raise MapError(
f"The prototype {self.prototype} for this node has no 'typeclass' key.", self
)
self.log(f" spawning room at xyz={xyz} ({typeclass})")
Typeclass = class_from_module(typeclass)
nodeobj, err = Typeclass.create(self.prototype.get("key", "An empty room"), xyz=xyz)
@ -405,7 +407,10 @@ class MapNode:
prot = maplinks[key.lower()][3].prototype
typeclass = prot.get("typeclass")
if typeclass is None:
raise MapError(f"The prototype {self.prototype} for this node has no 'typeclass' key.", self)
raise MapError(
f"The prototype {self.prototype} for this node has no 'typeclass' key.",
self,
)
self.log(f" spawning/updating exit xyz={xyz}, direction={key} ({typeclass})")
Typeclass = class_from_module(typeclass)

View file

@ -7,6 +7,7 @@ from evennia.server.sessionhandler import SESSIONS
import git
import datetime
class GitCommand(MuxCommand):
"""
The shared functionality between git/git evennia
@ -17,31 +18,35 @@ class GitCommand(MuxCommand):
Parse the arguments, set default arg to 'status' and check for existence of currently targeted repo
"""
super().parse()
if self.args:
split_args = self.args.strip().split(" ", 1)
self.action = split_args[0]
if len(split_args) > 1:
self.args = ''.join(split_args[1:])
self.args = "".join(split_args[1:])
else:
self.args = ''
self.args = ""
else:
self.action = "status"
self.args = ""
self.err_msgs = ["|rInvalid Git Repository|n:",
self.err_msgs = [
"|rInvalid Git Repository|n:",
"The {repo_type} repository is not recognized as a git directory.",
"In order to initialize it as a git directory, you will need to access your terminal and run the following commands from within your directory:",
" git init",
" git remote add origin {remote_link}"]
" git remote add origin {remote_link}",
]
try:
self.repo = git.Repo(self.directory, search_parent_directories=True)
except git.exc.InvalidGitRepositoryError:
err_msg = '\n'.join(self.err_msgs).format(repo_type=self.repo_type, remote_link=self.remote_link)
err_msg = "\n".join(self.err_msgs).format(
repo_type=self.repo_type, remote_link=self.remote_link
)
self.caller.msg(err_msg)
raise InterruptCommand
self.commit = self.repo.head.commit
try:
@ -56,16 +61,20 @@ class GitCommand(MuxCommand):
"""
short_sha = repo.git.rev_parse(hexsha, short=True)
return short_sha
def get_status(self):
"""
Retrieves the status of the active git repository, displaying unstaged changes/untracked files.
"""
time_of_commit = datetime.datetime.fromtimestamp(self.commit.committed_date)
status_msg = '\n'.join([f"Branch: |w{self.branch}|n ({self.repo.git.rev_parse(self.commit.hexsha, short=True)}) ({time_of_commit})",
f"By {self.commit.author.email}: {self.commit.message}"])
status_msg = "\n".join(
[
f"Branch: |w{self.branch}|n ({self.repo.git.rev_parse(self.commit.hexsha, short=True)}) ({time_of_commit})",
f"By {self.commit.author.email}: {self.commit.message}",
]
)
changedFiles = { item.a_path for item in self.repo.index.diff(None) }
changedFiles = {item.a_path for item in self.repo.index.diff(None)}
if changedFiles:
status_msg += f"Unstaged/uncommitted changes:|/ |g{'|/ '.join(changedFiles)}|n|/"
if len(self.repo.untracked_files) > 0:
@ -77,7 +86,9 @@ class GitCommand(MuxCommand):
Display current and available branches.
"""
remote_refs = self.repo.remote().refs
branch_msg = f"Current branch: |w{self.branch}|n. Branches available: {list_to_string(remote_refs)}"
branch_msg = (
f"Current branch: |w{self.branch}|n. Branches available: {list_to_string(remote_refs)}"
)
return branch_msg
def checkout(self):
@ -85,7 +96,9 @@ class GitCommand(MuxCommand):
Check out a specific branch.
"""
remote_refs = self.repo.remote().refs
to_branch = self.args.strip().removeprefix('origin/') # Slightly hacky, but git tacks on the origin/
to_branch = self.args.strip().removeprefix(
"origin/"
) # Slightly hacky, but git tacks on the origin/
if to_branch not in remote_refs:
self.caller.msg(f"Branch '{to_branch}' not available.")
@ -101,7 +114,7 @@ class GitCommand(MuxCommand):
return False
self.msg(f"Checked out |w{to_branch}|n successfully. Server restart initiated.")
return True
def pull(self):
"""
Attempt to pull new code.
@ -116,7 +129,9 @@ class GitCommand(MuxCommand):
self.caller.msg("No new code to pull, no need to reset.\n")
return False
else:
self.caller.msg(f"You have pulled new code. Server restart initiated.|/Head now at {self.repo.git.rev_parse(self.repo.head.commit.hexsha, short=True)}.|/Author: {self.repo.head.commit.author.name} ({self.repo.head.commit.author.email})|/{self.repo.head.commit.message.strip()}")
self.caller.msg(
f"You have pulled new code. Server restart initiated.|/Head now at {self.repo.git.rev_parse(self.repo.head.commit.hexsha, short=True)}.|/Author: {self.repo.head.commit.author.name} ({self.repo.head.commit.author.email})|/{self.repo.head.commit.message.strip()}"
)
return True
def func(self):
@ -139,18 +154,19 @@ class GitCommand(MuxCommand):
caller.msg("You can only git status, git branch, git checkout, or git pull.")
return
class CmdGitEvennia(GitCommand):
"""
Pull the latest code from the evennia core or checkout a different branch.
Usage:
git evennia status - View an overview of the evennia repository status.
git evennia branch - View available branches in evennia.
git evennia checkout <branch> - Checkout a different branch in evennia.
git evennia pull - Pull the latest evennia code.
For updating your local mygame repository, the same commands are available with 'git'.
If there are any conflicts encountered, the command will abort. The command will reload your game after pulling new code automatically, but for some changes involving persistent scripts etc, you may need to manually restart.
"""
@ -173,7 +189,7 @@ class CmdGit(GitCommand):
git pull - Pull the latest code from your current branch.
For updating evennia code, the same commands are available with 'git evennia'.
If there are any conflicts encountered, the command will abort. The command will reload your game after pulling new code automatically, but for changes involving persistent scripts etc, you may need to manually restart.
"""

View file

@ -11,6 +11,7 @@ import git
import mock
import datetime
class TestGitIntegration(EvenniaTest):
@mock.patch("git.Repo")
@mock.patch("git.Git")
@ -45,11 +46,15 @@ class TestGitIntegration(EvenniaTest):
test_cmd_git.caller = self.char1
test_cmd_git.args = "nonexistent_branch"
self.test_cmd_git = test_cmd_git
def test_git_status(self):
time_of_commit = datetime.datetime.fromtimestamp(self.test_cmd_git.commit.committed_date)
status_msg = '\n'.join([f"Branch: |w{self.test_cmd_git.branch}|n ({self.test_cmd_git.repo.git.rev_parse(self.test_cmd_git.commit.hexsha, short=True)}) ({time_of_commit})",
f"By {self.test_cmd_git.commit.author.email}: {self.test_cmd_git.commit.message}"])
status_msg = "\n".join(
[
f"Branch: |w{self.test_cmd_git.branch}|n ({self.test_cmd_git.repo.git.rev_parse(self.test_cmd_git.commit.hexsha, short=True)}) ({time_of_commit})",
f"By {self.test_cmd_git.commit.author.email}: {self.test_cmd_git.commit.message}",
]
)
self.assertEqual(status_msg, self.test_cmd_git.get_status())
def test_git_branch(self):
@ -62,8 +67,9 @@ class TestGitIntegration(EvenniaTest):
# Checkout no branch
self.test_cmd_git.checkout()
self.char1.msg.assert_called_with("Branch 'nonexistent_branch' not available.")
def test_git_pull(self):
self.test_cmd_git.pull()
self.char1.msg.assert_called_with(f"You have pulled new code. Server restart initiated.|/Head now at {self.repo.git.rev_parse(self.repo.head.commit.hexsha, short=True)}.|/Author: {self.repo.head.commit.author.name} ({self.repo.head.commit.author.email})|/{self.repo.head.commit.message.strip()}")
self.char1.msg.assert_called_with(
f"You have pulled new code. Server restart initiated.|/Head now at {self.repo.git.rev_parse(self.repo.head.commit.hexsha, short=True)}.|/Author: {self.repo.head.commit.author.name} ({self.repo.head.commit.author.email})|/{self.repo.head.commit.message.strip()}"
)