evennia/docs/source/Howtos/A-Sittable-Object.md

803 lines
28 KiB
Markdown
Raw Normal View History

2022-08-05 20:33:22 +02:00
[prev lesson](../Unimplemented.md) | [next lesson](../Unimplemented.md)
2020-07-27 22:04:07 +02:00
2021-10-21 21:04:14 +02:00
# Making a sittable object
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
In this lesson we will go through how to make a chair you can sit on. Sounds easy, right?
Well it is. But in the process of making the chair we will need to consider the various ways
to do it depending on how we want our game to work.
2020-07-27 21:09:13 +02:00
The goals of this lesson are as follows:
2021-10-21 21:04:14 +02:00
2020-07-27 21:09:13 +02:00
- We want a new 'sittable' object, a Chair in particular".
2021-10-21 21:04:14 +02:00
- We want to be able to use a command to sit in the chair.
2020-07-27 21:09:13 +02:00
- Once we are sitting in the chair it should affect us somehow. To demonstrate this we'll
2021-10-21 21:04:14 +02:00
set a flag "Resting" on the Character sitting in the Chair.
2020-07-27 21:09:13 +02:00
- When you sit down you should not be able to walk to another room without first standing up.
2021-10-21 21:04:14 +02:00
- A character should be able to stand up and move away from the chair.
2020-07-27 21:09:13 +02:00
2020-07-27 22:04:07 +02:00
There are two main ways to design the commands for sitting and standing up.
- You can store the commands on the chair so they are only available when a chair is in the room
- You can store the commands on the Character so they are always available and you must always specify
which chair to sit on.
2021-10-21 21:04:14 +02:00
2020-07-27 22:04:07 +02:00
Both of these are very useful to know about, so in this lesson we'll try both. But first
2021-10-21 21:04:14 +02:00
we need to handle some basics.
2020-07-27 22:04:07 +02:00
2020-07-27 21:09:13 +02:00
## Don't move us when resting
2021-10-21 21:04:14 +02:00
When you are sitting in a chair you can't just walk off without first standing up.
2020-07-27 22:04:07 +02:00
This requires a change to our Character typeclass. Open `mygame/typeclasses/characters.py`:
2020-07-27 21:09:13 +02:00
```python
# ...
class Character(DefaultCharacter):
# ...
def at_pre_move(self, destination):
2020-07-27 21:09:13 +02:00
"""
Called by self.move_to when trying to move somewhere. If this returns
2021-10-21 21:04:14 +02:00
False, the move is immediately cancelled.
2020-07-27 21:09:13 +02:00
"""
if self.db.is_resting:
self.msg("You can't go anywhere while resting.")
return False
return True
```
2021-10-21 21:04:14 +02:00
When moving somewhere, [character.move_to](evennia.objects.objects.DefaultObject.move_to) is called. This in turn
will call `character.at_pre_move`. Here we look for an Attribute `is_resting` (which we will assign below)
2021-10-21 21:04:14 +02:00
to determine if we are stuck on the chair or not.
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
## Making the Chair itself
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
Next we need the Chair itself, or rather a whole family of "things you can sit on" that we will call
_sittables_. We can't just use a default Object since we want a sittable to contain some custom code. We need
a new, custom Typeclass. Create a new module `mygame/typeclasses/sittables.py` with the following content:
2020-07-27 21:09:13 +02:00
```python
from evennia import DefaultObject
class Sittable(DefaultObject):
def at_object_creation(self):
self.db.sitter = None
def do_sit(self, sitter):
"""
2021-10-21 21:04:14 +02:00
Called when trying to sit on/in this object.
2020-07-27 21:09:13 +02:00
Args:
sitter (Object): The one trying to sit down.
"""
current = self.db.sitter
if current:
if current == sitter:
2021-10-21 21:04:14 +02:00
sitter.msg("You are already sitting on {self.key}.")
2020-07-27 21:09:13 +02:00
else:
sitter.msg(f"You can't sit on {self.key} "
f"- {current.key} is already sitting there!")
2021-10-21 21:04:14 +02:00
return
2020-07-27 21:09:13 +02:00
self.db.sitting = sitter
sitter.db.is_resting = True
sitter.msg(f"You sit on {self.key}")
def do_stand(self, stander):
"""
2021-10-21 21:04:14 +02:00
Called when trying to stand from this object.
2020-07-27 21:09:13 +02:00
Args:
stander (Object): The one trying to stand up.
"""
2021-10-21 21:04:14 +02:00
current = self.db.sitter
2020-07-27 21:09:13 +02:00
if not stander == current:
stander.msg(f"You are not sitting on {self.key}.")
else:
self.db.sitting = None
2021-10-21 21:04:14 +02:00
stander.db.is_resting = False
2020-07-27 21:09:13 +02:00
stander.msg(f"You stand up from {self.key}")
```
2021-10-21 21:04:14 +02:00
Here we have a small Typeclass that handles someone trying to sit on it. It has two methods that we can simply
2020-07-27 21:09:13 +02:00
call from a Command later. We set the `is_resting` Attribute on the one sitting down.
2021-10-21 21:04:14 +02:00
One could imagine that one could have the future `sit` command check if someone is already sitting in the
2020-07-27 21:09:13 +02:00
chair instead. This would work too, but letting the `Sittable` class handle the logic around who can sit on it makes
2021-10-21 21:04:14 +02:00
logical sense.
2020-07-27 21:09:13 +02:00
2020-07-27 22:04:07 +02:00
We let the typeclass handle the logic, and also let it do all the return messaging. This makes it easy to churn out
2020-07-27 21:09:13 +02:00
a bunch of chairs for people to sit on. But it's not perfect. The `Sittable` class is general. What if you want to
make an armchair. You sit "in" an armchair rather than "on" it. We _could_ make a child class of `Sittable` named
2021-10-21 21:04:14 +02:00
`SittableIn` that makes this change, but that feels excessive. Instead we will make it so that Sittables can
2020-07-27 21:09:13 +02:00
modify this per-instance:
```python
from evennia import DefaultObject
class Sittable(DefaultObject):
def at_object_creation(self):
self.db.sitter = None
2021-10-21 21:04:14 +02:00
# do you sit "on" or "in" this object?
2020-07-27 21:09:13 +02:00
self.db.adjective = "on"
def do_sit(self, sitter):
"""
2021-10-21 21:04:14 +02:00
Called when trying to sit on/in this object.
2020-07-27 21:09:13 +02:00
Args:
sitter (Object): The one trying to sit down.
"""
adjective = self.db.adjective
current = self.db.sitter
if current:
if current == sitter:
2021-10-21 21:04:14 +02:00
sitter.msg(f"You are already sitting {adjective} {self.key}.")
2020-07-27 21:09:13 +02:00
else:
sitter.msg(
f"You can't sit {adjective} {self.key} "
f"- {current.key} is already sitting there!")
2021-10-21 21:04:14 +02:00
return
2020-07-27 21:09:13 +02:00
self.db.sitting = sitter
sitter.db.is_resting = True
sitter.msg(f"You sit {adjective} {self.key}")
def do_stand(self, stander):
"""
2021-10-21 21:04:14 +02:00
Called when trying to stand from this object.
2020-07-27 21:09:13 +02:00
Args:
stander (Object): The one trying to stand up.
"""
2021-10-21 21:04:14 +02:00
current = self.db.sitter
2020-07-27 21:09:13 +02:00
if not stander == current:
stander.msg(f"You are not sitting {self.db.adjective} {self.key}.")
else:
self.db.sitting = None
2021-10-21 21:04:14 +02:00
stander.db.is_resting = False
2020-07-27 21:09:13 +02:00
stander.msg(f"You stand up from {self.key}")
```
We added a new Attribute `adjective` which will probably usually be `in` or `on` but could also be `at` if you
2021-10-21 21:04:14 +02:00
want to be able to sit _at a desk_ for example. A regular builder would use it like this:
2020-07-27 21:09:13 +02:00
> create/drop armchair : sittables.Sittable
> set armchair/adjective = in
This is probably enough. But all those strings are hard-coded. What if we want some more dramatic flair when you
2021-10-21 21:04:14 +02:00
sit down?
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
You sit down and a whoopie cushion makes a loud fart noise!
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
For this we need to allow some further customization. Let's let the current strings be defaults that
we can replace.
2020-07-27 21:09:13 +02:00
```python
from evennia import DefaultObject
class Sittable(DefaultObject):
"""
2021-10-21 21:04:14 +02:00
An object one can sit on
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
Customizable Attributes:
2020-07-27 21:09:13 +02:00
adjective: How to sit (on, in, at etc)
Return messages (set as Attributes):
msg_already_sitting: Already sitting here
2021-10-21 21:04:14 +02:00
format tokens {adjective} and {key}
2020-07-27 21:09:13 +02:00
msg_other_sitting: Someone else is sitting here.
format tokens {adjective}, {key} and {other}
msg_sitting_down: Successfully sit down
format tokens {adjective}, {key}
msg_standing_fail: Fail to stand because not sitting.
format tokens {adjective}, {key}
msg_standing_up: Successfully stand up
format tokens {adjective}, {key}
"""
def at_object_creation(self):
self.db.sitter = None
2021-10-21 21:04:14 +02:00
# do you sit "on" or "in" this object?
2020-07-27 21:09:13 +02:00
self.db.adjective = "on"
def do_sit(self, sitter):
"""
2021-10-21 21:04:14 +02:00
Called when trying to sit on/in this object.
2020-07-27 21:09:13 +02:00
Args:
sitter (Object): The one trying to sit down.
"""
adjective = self.db.adjective
current = self.db.sitter
if current:
if current == sitter:
if self.db.msg_already_sitting:
sitter.msg(
self.db.msg_already_sitting.format(
adjective=self.db.adjective, key=self.key))
else:
sitter.msg(f"You are already sitting {adjective} {self.key}.")
else:
if self.db.msg_other_sitting:
sitter.msg(self.db.msg_already_sitting.format(
other=current.key, adjective=self.db.adjective, key=self.key))
else:
sitter.msg(f"You can't sit {adjective} {self.key} "
f"- {current.key} is already sitting there!")
2021-10-21 21:04:14 +02:00
return
2020-07-27 21:09:13 +02:00
self.db.sitting = sitter
sitter.db.is_resting = True
if self.db.msg_sitting_down:
sitter.msg(self.db.msg_sitting_down.format(adjective=adjective, key=self.key))
else:
sitter.msg(f"You sit {adjective} {self.key}")
def do_stand(self, stander):
"""
2021-10-21 21:04:14 +02:00
Called when trying to stand from this object.
2020-07-27 21:09:13 +02:00
Args:
stander (Object): The one trying to stand up.
"""
2021-10-21 21:04:14 +02:00
current = self.db.sitter
2020-07-27 21:09:13 +02:00
if not stander == current:
if self.db.msg_standing_fail:
stander.msg(self.db.msg_standing_fail.format(
adjective=self.db.adjective, key=self.key))
else:
stander.msg(f"You are not sitting {self.db.adjective} {self.key}")
else:
self.db.sitting = None
2021-10-21 21:04:14 +02:00
stander.db.is_resting = False
2020-07-27 21:09:13 +02:00
if self.db.msg_standing_up:
stander.msg(self.db.msg_standing_up.format(
adjective=self.db.adjective, key=self.key))
else:
stander.msg(f"You stand up from {self.key}")
```
2021-10-21 21:04:14 +02:00
Here we really went all out with flexibility. If you need this much is up to you.
We added a bunch of optional Attributes to hold alternative versions of all the messages.
There are some things to note:
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
- We don't actually initiate those Attributes in `at_object_creation`. This is a simple
optimization. The assumption is that _most_ chairs will probably not be this customized.
So initiating a bunch of Attributes to, say, empty strings would be a lot of useless database calls.
2020-07-27 22:04:07 +02:00
The drawback is that the available Attributes become less visible when reading the code. So we add a long
2021-10-21 21:04:14 +02:00
describing docstring to the end to explain all you can use.
2020-07-27 21:09:13 +02:00
- We use `.format` to inject formatting-tokens in the text. The good thing about such formatting
2021-10-21 21:04:14 +02:00
markers is that they are _optional_. They are there if you want them, but Python will not complain
if you don't include some or any of them. Let's see an example:
2020-07-27 21:09:13 +02:00
> reload # if you have new code
2021-10-21 21:04:14 +02:00
> create/drop armchair : sittables.Sittable
2020-07-27 21:09:13 +02:00
> set armchair/adjective = in
> set armchair/msg_sitting_down = As you sit down {adjective} {key}, life feels easier.
> set armchair/msg_standing_up = You stand up from {key}. Life resumes.
2021-10-21 21:04:14 +02:00
The `{key}` and `{adjective}` are examples of optional formatting markers. Whenever the message is
returned, the format-tokens within will be replaced with `armchair` and `in` respectively. Should we
2020-07-27 22:04:07 +02:00
rename the chair later, this will show in the messages automatically (since `{key}` will change).
2020-07-27 21:09:13 +02:00
We have no Command to use this chair yet. But we can try it out with `py`:
> py self.search("armchair").do_sit(self)
2021-10-21 21:04:14 +02:00
As you sit down in armchair, life feels easier.
> self.db.resting
2020-07-27 21:09:13 +02:00
True
> py self.search("armchair").do_stand(self)
2021-10-21 21:04:14 +02:00
You stand up from armchair. Life resumes
> self.db.resting
False
If you follow along and get a result like this, all seems to be working well!
2020-07-27 21:09:13 +02:00
2020-07-27 22:04:07 +02:00
## Command variant 1: Commands on the chair
2020-07-27 21:09:13 +02:00
2020-07-27 22:04:07 +02:00
This way to implement `sit` and `stand` puts new cmdsets on the Sittable itself.
2021-10-21 21:04:14 +02:00
As we've learned before, commands on objects are made available to others in the room.
This makes the command easy but instead adds some complexity in the management of the CmdSet.
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
This is how it will look if `armchair` is in the room:
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
> sit
As you sit down in armchair, life feels easier.
2020-07-27 21:09:13 +02:00
2020-07-27 22:04:07 +02:00
What happens if there are sittables `sofa` and `barstool` also in the room? Evennia will automatically
2021-10-21 21:04:14 +02:00
handle this for us and allow us to specify which one we want:
2020-07-27 21:09:13 +02:00
> sit
More than one match for 'sit' (please narrow target):
sit-1 (armchair)
sit-2 (sofa)
sit-3 (barstool)
> sit-1
As you sit down in armchair, life feels easier.
2021-10-21 21:04:14 +02:00
2020-07-27 22:04:07 +02:00
To keep things separate we'll make a new module `mygame/commands/sittables.py`:
2021-10-21 21:04:14 +02:00
```{sidebar} Separate Commands and Typeclasses?
2020-07-27 21:09:13 +02:00
2020-07-27 22:04:07 +02:00
You can organize these things as you like. If you wanted you could put the sit-command + cmdset
2021-10-21 21:04:14 +02:00
together with the `Sittable` typeclass in `mygame/typeclasses/sittables.py`. That has the advantage of
keeping everything related to sitting in one place. But there is also some organizational merit to
keeping all Commands in one place as we do here.
2020-07-27 21:09:13 +02:00
```
```python
from evennia import Command, CmdSet
2021-10-21 21:04:14 +02:00
class CmdSit(Command):
2020-07-27 21:09:13 +02:00
"""
2021-10-21 21:04:14 +02:00
Sit down.
2020-07-27 21:09:13 +02:00
"""
key = "sit"
def func(self):
self.obj.do_sit(self.caller)
class CmdStand(Command):
"""
Stand up.
"""
key = "stand"
def func(self):
self.obj.do_stand(self.caller)
class CmdSetSit(CmdSet):
priority = 1
def at_cmdset_creation(self):
self.add(CmdSit)
self.add(CmdStand)
```
2021-10-21 21:04:14 +02:00
As seen, the commands are nearly trivial. `self.obj` is the object to which we added the cmdset with this
Command (so for example a chair). We just call the `do_sit/stand` on that object and the `Sittable` will
2020-07-27 21:09:13 +02:00
do the rest.
Why that `priority = 1` on `CmdSetSit`? This makes same-named Commands from this cmdset merge with a bit higher
2021-10-21 21:04:14 +02:00
priority than Commands from the Character-cmdset. Why this is a good idea will become clear shortly.
2020-07-27 21:09:13 +02:00
We also need to make a change to our `Sittable` typeclass. Open `mygame/typeclasses/sittables.py`:
2021-10-21 21:04:14 +02:00
2020-07-27 21:09:13 +02:00
```python
from evennia import DefaultObject
2021-10-21 21:04:14 +02:00
from commands.sittables import CmdSetSit # <- new
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
class Sittable(DefaultObject):
2020-07-27 21:09:13 +02:00
"""
(docstring)
2021-10-21 21:04:14 +02:00
"""
2020-07-27 21:09:13 +02:00
def at_object_creation(self):
self.db.sitter = None
2021-10-21 21:04:14 +02:00
# do you sit "on" or "in" this object?
2020-07-27 21:09:13 +02:00
self.db.adjective = "on"
self.cmdset.add_default(CmdSetSit) # <- new
2021-10-21 21:04:14 +02:00
```
Any _new_ Sittables will now have your `sit` Command. Your existing `armchair` will not,
since `at_object_creation` will not re-run for already existing objects. We can update it manually:
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
> reload
> update armchair
2020-07-27 21:09:13 +02:00
We could also update all existing sittables (all on one line):
2021-10-21 21:04:14 +02:00
> py from typeclasses.sittables import Sittable ;
2020-07-27 21:09:13 +02:00
[sittable.at_object_creation() for sittable in Sittable.objects.all()]
2021-10-21 21:04:14 +02:00
> The above shows an example of a _list comprehension_. Think of it as an efficient way to construct a new list
all in one line. You can read more about list comprehensions
2020-07-27 22:04:07 +02:00
[here in the Python docs](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions).
2021-10-21 21:04:14 +02:00
2020-07-27 21:09:13 +02:00
We should now be able to use `sit` while in the room with the armchair.
2021-10-21 21:04:14 +02:00
> sit
2020-07-27 22:04:07 +02:00
As you sit down in armchair, life feels easier.
2021-10-21 21:04:14 +02:00
> stand
2020-07-27 22:04:07 +02:00
You stand up from armchair.
2021-10-21 21:04:14 +02:00
One issue with placing the `sit` (or `stand`) Command "on" the chair is that it will not be available when in a
room without a Sittable object:
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
> sit
2020-07-27 21:09:13 +02:00
Command 'sit' is not available. ...
2021-10-21 21:04:14 +02:00
This is practical but not so good-looking; it makes it harder for the user to know a `sit` action is at all
possible. Here is a trick for fixing this. Let's add _another_ Command to the bottom
2020-07-27 22:04:07 +02:00
of `mygame/commands/sittables.py`:
2020-07-27 21:09:13 +02:00
```python
2021-10-21 21:04:14 +02:00
# ...
2020-07-27 21:09:13 +02:00
class CmdNoSitStand(Command):
"""
Sit down or Stand up
"""
key = "sit"
aliases = ["stand"]
def func(self):
if self.cmdname == "sit":
self.msg("You have nothing to sit on.")
else:
self.msg("You are not sitting down.")
```
2021-10-21 21:04:14 +02:00
Here we have a Command that is actually two - it will answer to both `sit` and `stand` since we
added `stand` to its `aliases`. In the command we look at `self.cmdname`, which is the string
_actually used_ to call this command. We use this to return different messages.
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
We don't need a separate CmdSet for this, instead we will add this
2020-07-27 22:04:07 +02:00
to the default Character cmdset. Open `mygame/commands/default_cmdsets.py`:
2020-07-27 21:09:13 +02:00
```python
2021-10-21 21:04:14 +02:00
# ...
2020-07-27 22:04:07 +02:00
from commands import sittables
2020-07-27 21:09:13 +02:00
class CharacterCmdSet(CmdSet):
"""
(docstring)
"""
def at_cmdset_creation(self):
# ...
2020-07-27 22:04:07 +02:00
self.add(sittables.CmdNoSitStand)
2020-07-27 21:09:13 +02:00
```
2021-10-21 21:04:14 +02:00
To test we'll build a new location without any comfy armchairs and go there:
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
> reload
> tunnel n = kitchen
north
> sit
2020-07-27 21:09:13 +02:00
You have nothing to sit on.
2021-10-21 21:04:14 +02:00
> south
sit
2020-07-27 21:09:13 +02:00
As you sit down in armchair, life feels easier.
2021-10-21 21:04:14 +02:00
We now have a fully functioning `sit` action that is contained with the chair itself. When no chair is around, a
default error message is shown.
How does this work? There are two cmdsets at play, both of which have a `sit` Command. As you may remember we
set the chair's cmdset to `priority = 1`. This is where that matters. The default Character cmdset has a
2020-07-27 22:04:07 +02:00
priority of 0. This means that whenever we enter a room with a Sittable thing, the `sit` command
2021-10-21 21:04:14 +02:00
from _its_ cmdset will take _precedence_ over the Character cmdset's version. So we are actually picking
2020-07-27 22:04:07 +02:00
_different_ `sit` commands depending on circumstance! The user will never be the wiser.
2021-10-21 21:04:14 +02:00
So this handles `sit`. What about `stand`? That will work just fine:
2020-07-27 21:09:13 +02:00
> stand
2021-10-21 21:04:14 +02:00
You stand up from armchair.
2020-07-27 21:09:13 +02:00
> north
2021-10-21 21:04:14 +02:00
> stand
You are not sitting down.
We have one remaining problem with `stand` though - what happens when you are sitting down and try to
`stand` in a room with more than one chair:
2020-07-27 21:09:13 +02:00
> stand
More than one match for 'stand' (please narrow target):
stand-1 (armchair)
stand-2 (sofa)
stand-3 (barstool)
2021-10-21 21:04:14 +02:00
Since all the sittables have the `stand` Command on them, you'll get a multi-match error. This _works_ ... but
2020-07-27 21:09:13 +02:00
you could pick _any_ of those sittables to "stand up from". That's really weird and non-intuitive. With `sit` it
2021-10-21 21:04:14 +02:00
was okay to get a choice - Evennia can't know which chair we intended to sit on. But we know which chair we
sit on so we should only get _its_ `stand` command.
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
We will fix this with a `lock` and a custom `lock function`. We want a lock on the `stand` Command that only
2020-07-27 21:09:13 +02:00
makes it available when the caller is actually sitting on the chair the `stand` command is on.
First let's add the lock so we see what we want. Open `mygame/commands/sittables.py`:
```python
# ...
class CmdStand(Command):
"""
Stand up.
"""
key = "stand"
lock = "cmd:sitsonthis()" # < this is new
2021-10-21 21:04:14 +02:00
2020-07-27 21:09:13 +02:00
def func(self):
self.obj.do_stand(self.caller)
# ...
```
2022-08-05 20:33:22 +02:00
We define a [Lock](../Components/Locks.md) on the command. The `cmd:` is in what situation Evennia will check
2021-10-21 21:04:14 +02:00
the lock. The `cmd` means that it will check the lock when determining if a user has access to this command or not.
What will be checked is the `sitsonthis` _lock function_ which doesn't exist yet.
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
Open `mygame/server/conf/lockfuncs.py` to add it!
2020-07-27 21:09:13 +02:00
```python
"""
(module lockstring)
"""
2021-10-21 21:04:14 +02:00
# ...
2020-07-27 21:09:13 +02:00
def sitsonthis(accessing_obj, accessed_obj, *args, **kwargs):
2020-07-27 22:04:07 +02:00
"""
2021-10-21 21:04:14 +02:00
True if accessing_obj is sitting on/in the accessed_obj.
2020-07-27 22:04:07 +02:00
"""
2020-07-27 21:09:13 +02:00
return accessed_obj.db.sitting == accessing_obj
2021-10-21 21:04:14 +02:00
# ...
2020-07-27 21:09:13 +02:00
```
Evennia knows that all functions in `mygame/server/conf/lockfuncs` should be possible to use in a lock definition.
2021-10-21 21:04:14 +02:00
The arguments are required and Evennia will pass all relevant objects to them:
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
```{sidebar} Lockfuncs
2020-07-27 22:04:07 +02:00
Evennia provides a large number of default lockfuncs, such as checking permission-levels,
if you are carrying or are inside the accessed object etc. There is no concept of 'sitting'
in default Evennia however, so this we need to specify ourselves.
```
2021-10-21 21:04:14 +02:00
- `accessing_obj` is the one trying to access the lock. So us, in this case.
2020-07-27 21:09:13 +02:00
- `accessed_obj` is the entity we are trying to gain a particular type of access to. So the chair.
2021-10-21 21:04:14 +02:00
- `args` is a tuple holding any arguments passed to the lockfunc. Since we use `sitsondthis()` this will
2020-07-27 21:09:13 +02:00
be empty (and if we add anything, it will be ignored).
- `kwargs` is a tuple of keyword arguments passed to the lockfuncs. This will be empty as well in our example.
2021-10-21 21:04:14 +02:00
If you are superuser, it's important that you `quell` yourself before trying this out. This is because the superuser
2020-07-27 21:09:13 +02:00
bypasses all locks - it can never get locked out, but it means it will also not see the effects of a lock like this.
2021-10-21 21:04:14 +02:00
> reload
> quell
> stand
You stand up from armchair
None of the other sittables' `stand` commands passed the lock and only the one we are actually sitting on did.
2020-07-27 21:09:13 +02:00
Adding a Command to the chair object like this is powerful and a good technique to know. It does come with some
2021-10-21 21:04:14 +02:00
caveats though that one needs to keep in mind.
2020-07-27 21:09:13 +02:00
We'll now try another way to add the `sit/stand` commands.
2021-10-21 21:04:14 +02:00
## Command variant 2: Command on Character
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
Before we start with this, delete the chairs you've created (`del armchair` etc) and then do the following
changes:
2020-07-27 21:09:13 +02:00
- In `mygame/typeclasses/sittables.py`, comment out the line `self.cmdset.add_default(CmdSetSit)`.
2021-10-21 21:04:14 +02:00
- In `mygame/commands/default_cmdsets.py`, comment out the line `self.add(sittables.CmdNoSitStand)`.
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
This disables the on-object command solution so we can try an alternative. Make sure to `reload` so the
changes are known to Evennia.
2020-07-27 21:09:13 +02:00
In this variation we will put the `sit` and `stand` commands on the `Character` instead of on the chair. This
2021-10-21 21:04:14 +02:00
makes some things easier, but makes the Commands themselves more complex because they will not know which
chair to sit on. We can't just do `sit` anymore. This is how it will work.
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
> sit <chair>
2020-07-27 21:09:13 +02:00
You sit on chair.
2021-10-21 21:04:14 +02:00
> stand
2020-07-27 21:09:13 +02:00
You stand up from chair.
2021-10-21 21:04:14 +02:00
Open `mygame/commands.sittables.py` again. We'll add a new sit-command. We name the class `CmdSit2` since
we already have `CmdSit` from the previous example. We put everything at the end of the module to
keep it separate.
2020-07-27 21:09:13 +02:00
```python
2021-10-21 21:04:14 +02:00
from evennia import Command, CmdSet
2020-07-27 21:09:13 +02:00
from evennia import InterruptCommand # <- this is new
class CmdSit(Command):
# ...
# ...
2021-10-21 21:04:14 +02:00
# new from here
2020-07-27 21:09:13 +02:00
class CmdSit2(Command):
"""
Sit down.
2021-10-21 21:04:14 +02:00
Usage:
2020-07-27 21:09:13 +02:00
sit <sittable>
2021-10-21 21:04:14 +02:00
"""
2020-07-27 21:09:13 +02:00
key = "sit"
2021-10-21 21:04:14 +02:00
2020-07-27 21:09:13 +02:00
def parse(self):
self.args = self.args.strip()
if not self.args:
self.caller.msg("Sit on what?")
raise InterruptCommand
def func(self):
# self.search handles all error messages etc.
sittable = self.caller.search(self.args)
if not sittable:
return
try:
sittable.do_sit(self.caller)
except AttributeError:
self.caller.msg("You can't sit on that!")
```
2021-10-21 21:04:14 +02:00
With this Command-variation we need to search for the sittable. A series of methods on the Command
2020-07-27 21:09:13 +02:00
are run in sequence:
1. `Command.at_pre_command` - this is not used by default
2. `Command.parse` - this should parse the input
3. `Command.func` - this should implement the actual Command functionality
4. `Command.at_post_func` - this is not used by default
2021-10-21 21:04:14 +02:00
So if we just `return` in `.parse`, `.func` will still run, which is not what we want. To immediately
2020-07-27 21:09:13 +02:00
abort this sequence we need to `raise InterruptCommand`.
2021-10-21 21:04:14 +02:00
```{sidebar} Raising exceptions
2020-07-27 21:09:13 +02:00
2021-10-21 21:04:14 +02:00
Raising an exception allows for immediately interrupting the current program flow. Python
automatically raises error-exceptions when detecting problems with the code. It will be
2020-07-27 21:09:13 +02:00
raised up through the sequence of called code (the 'stack') until it's either `caught` with
a `try ... except` or reaches the outermost scope where it'll be logged or displayed.
```
2021-10-21 21:04:14 +02:00
`InterruptCommand` is an _exception_ that the Command-system catches with the understanding that we want
to do a clean abort. In the `.parse` method we strip any whitespaces from the argument and
sure there actuall _is_ an argument. We abort immediately if there isn't.
2020-07-27 21:09:13 +02:00
We we get to `.func` at all, we know that we have an argument. We search for this and abort if we there was
2021-10-21 21:04:14 +02:00
a problem finding the target.
2020-07-27 21:09:13 +02:00
> We could have done `raise InterruptCommand` in `.func` as well, but `return` is a little shorter to write
> and there is no harm done if `at_post_func` runs since it's empty.
2021-10-21 21:04:14 +02:00
Next we call the found sittable's `do_sit` method. Note that we wrap this call like this:
2020-07-27 21:09:13 +02:00
```python
try:
2021-10-21 21:04:14 +02:00
# code
2020-07-27 21:09:13 +02:00
except AttributeError:
# stuff to do if AttributeError exception was raised
```
2021-10-21 21:04:14 +02:00
The reason is that `caller.search` has no idea we are looking for a Sittable. The user could have tried
2020-07-27 21:09:13 +02:00
`sit wall` or `sit sword`. These don't have a `do_sit` method _but we call it anyway and handle the error_.
This is a very "Pythonic" thing to do. The concept is often called "leap before you look" or "it's easier to
ask for forgiveness than for permission". If `sittable.do_sit` does not exist, Python will raise an `AttributeError`.
2021-10-21 21:04:14 +02:00
We catch this with `try ... except AttributeError` and convert it to a proper error message.
2020-07-27 21:09:13 +02:00
While it's useful to learn about `try ... except`, there is also a way to leverage Evennia to do this without
`try ... except`:
```python
2021-10-21 21:04:14 +02:00
# ...
2020-07-27 21:09:13 +02:00
def func(self):
# self.search handles all error messages etc.
sittable = self.caller.search(
2021-10-21 21:04:14 +02:00
self.args,
2020-07-27 21:09:13 +02:00
typeclass="typeclasses.sittables.Sittable")
if not sittable:
return
sittable.do_sit(self.caller)
```
2021-10-21 21:04:14 +02:00
```{sidebar} Continuing across multiple lines
2020-07-27 21:09:13 +02:00
Note how the `.search()` method's arguments are spread out over multiple
2021-10-21 21:04:14 +02:00
lines. This works for all lists, tuples and other listings and is
2020-07-27 21:09:13 +02:00
a good way to avoid very long and hard-to-read lines.
```
2021-10-21 21:04:14 +02:00
The `caller.search` method has an keyword argument `typeclass` that can take either a python-path to a
2020-07-27 21:09:13 +02:00
typeclass, the typeclass itself, or a list of either to widen the allowed options. In this case we know
for sure that the `sittable` we get is actually a `Sittable` class and we can call `sittable.do_sit` without
2021-10-21 21:04:14 +02:00
needing to worry about catching errors.
2020-07-27 21:09:13 +02:00
Let's do the `stand` command while we are at it. Again, since the Command is external to the chair we don't
2021-10-21 21:04:14 +02:00
know which object we are sitting in and have to search for it.
2020-07-27 21:09:13 +02:00
```python
class CmdStand2(Command):
"""
Stand up.
2021-10-21 21:04:14 +02:00
Usage:
2020-07-27 21:09:13 +02:00
stand
2021-10-21 21:04:14 +02:00
"""
2020-07-27 21:09:13 +02:00
key = "stand"
2021-10-21 21:04:14 +02:00
2020-07-27 21:09:13 +02:00
def func(self):
2021-10-21 21:04:14 +02:00
caller = self.caller
2020-07-27 21:09:13 +02:00
# find the thing we are sitting on/in, by finding the object
2021-10-21 21:04:14 +02:00
# in the current location that as an Attribute "sitter" set
2020-07-27 21:09:13 +02:00
# to the caller
2020-07-27 22:04:07 +02:00
sittable = caller.search(
2021-10-21 21:04:14 +02:00
caller,
2020-07-27 21:09:13 +02:00
candidates=caller.location.contents,
2021-10-21 21:04:14 +02:00
attribute_name="sitter",
2020-07-27 21:09:13 +02:00
typeclass="typeclasses.sittables.Sittable")
# if this is None, the error was already reported to user
if not sittable:
2021-10-21 21:04:14 +02:00
return
2020-07-27 21:09:13 +02:00
sittable.do_stand(caller)
2021-10-21 21:04:14 +02:00
2020-07-27 21:09:13 +02:00
```
2021-10-21 21:04:14 +02:00
This forced us to to use the full power of the `caller.search` method. If we wanted to search for something
2022-08-30 23:03:39 +02:00
more complex we would likely need to break out a [Django query](Beginner-Tutorial/Part1/Beginner-Tutorial-Django-queries.md) to do it. The key here is that
2021-10-21 21:04:14 +02:00
we know that the object we are looking for is a `Sittable` and that it must have an Attribute named `sitter`
which should be set to us, the one sitting on/in the thing. Once we have that we just call `.do_stand` on it
and let the Typeclass handle the rest.
2020-07-27 22:04:07 +02:00
All that is left now is to make this available to us. This type of Command should be available to us all the time
so we can put it in the default Cmdset` on the Character. Open `mygame/default_cmdsets.py`
```python
2021-10-21 21:04:14 +02:00
# ...
2020-07-27 22:04:07 +02:00
from commands import sittables
class CharacterCmdSet(CmdSet):
"""
(docstring)
"""
def at_cmdset_creation(self):
# ...
self.add(sittables.CmdSit2)
self.add(sittables.CmdStand2)
```
2021-10-21 21:04:14 +02:00
Now let's try it out:
2020-07-27 22:04:07 +02:00
2021-10-21 21:04:14 +02:00
> reload
2020-07-27 22:04:07 +02:00
> create/drop sofa : sittables.Sittable
> sit sofa
You sit down on sofa.
2021-10-21 21:04:14 +02:00
> stand
2020-07-27 22:04:07 +02:00
You stand up from sofa.
## Conclusions
2021-10-21 21:04:14 +02:00
In this lesson we accomplished quite a bit:
2020-07-27 22:04:07 +02:00
- We modified our `Character` class to avoid moving when sitting down.
- We made a new `Sittable` typeclass
2021-10-21 21:04:14 +02:00
- We tried two ways to allow a user to interact with sittables using `sit` and `stand` commands.
2020-07-27 22:04:07 +02:00
2021-10-21 21:04:14 +02:00
Eagle-eyed readers will notice that the `stand` command sitting "on" the chair (variant 1) would work just fine
together with the `sit` command sitting "on" the Character (variant 2). There is nothing stopping you from
mixing them, or even try a third solution that better fits what you have in mind.
2020-07-27 22:04:07 +02:00
2022-08-05 20:33:22 +02:00
[prev lesson](../Unimplemented.md) | [next lesson](../Unimplemented.md)