Merge pull request #3447 from InspectorCaracal/achievements-contrib

Achievements contrib
This commit is contained in:
Griatch 2024-06-14 09:26:44 +02:00 committed by GitHub
commit 70b57174dd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 835 additions and 0 deletions

View file

@ -0,0 +1,245 @@
# Achievements
A simple, but reasonably comprehensive, system for tracking achievements. Achievements are defined using ordinary Python dicts, reminiscent of the core prototypes system, and while it's expected you'll use it only on Characters or Accounts, they can be tracked for any typeclassed object.
The contrib provides several functions for tracking and accessing achievements, as well as a basic in-game command for viewing achievement status.
## Installation
This contrib requires creation one or more module files containing your achievement data, which you then add to your settings file to make them available.
> See the section below on "Creating Achievements" for what to put in this module.
```python
# in server/conf/settings.py
ACHIEVEMENT_CONTRIB_MODULES = ["world.achievements"]
```
To allow players to check their achievements, you'll also want to add the `achievements` command to your default Character and/or Account command sets.
```python
# in commands/default_cmdsets.py
from evennia.contrib.game_systems.achievements.achievements import CmdAchieve
class CharacterCmdSet(default_cmds.CharacterCmdSet):
key = "DefaultCharacter"
def at_cmdset_creation(self):
# ...
self.add(CmdAchieve)
```
**Optional** - The achievements contrib stores individual progress data on the `achievements` attribute by default, visible via `obj.db.attributes`. You can change this by assigning an attribute (key, category) tuple to the setting `ACHIEVEMENT_CONTRIB_ATTRIBUTE`
Example:
```py
# in settings.py
ACHIEVEMENT_CONTRIB_ATTRIBUTE = ("progress_data", "achievements")
```
## Creating achievements
An achievement is represented by a simple python dictionary defined at the module level in your achievements module(s).
Each achievement requires certain specific keys to be defined to work properly, along with several optional keys that you can use to override defaults.
> Note: Any additional keys not described here are included in the achievement data when you access those acheivements through the contrib, so you can easily add your own extended features.
#### Required keys
- **name** (str): The searchable name for the achievement. Doesn't need to be unique.
- **category** (str): The category, or general type, of condition which can progress this achievement. Usually this will be a player action or result. e.g. you would use a category of "defeat" on an achievement for killing 10 rats.
- **tracking** (str or list): The specific subset of condition which can progress this achievement. e.g. you would use a tracking value of "rat" on an achievement for killing 10 rats. An achievement can also track multiple things, for example killing 10 rats or snakes. For that situation, assign a list of all the values to check against, e.g. `["rat", "snake"]`
#### Optional keys
- **key** (str): *Default value if unset: the variable name.* The unique, case-insensitive key identifying this achievement.
> Note: If any achievements have the same unique key, only *one* will be loaded. It is case-insensitive, but punctuation is respected - "ten_rats", "Ten_Rats" and "TEN_RATS" will conflict, but "ten_rats" and "ten rats" will not.
- **desc** (str): A longer description of the achievement. Common uses for this would be flavor text or hints on how to complete it.
- **count** (int): *Default value if unset: 1* The number of tallies this achievement's requirements need to build up in order to complete the achievement. e.g. killing 10 rats would have a `"count"` value of `10`. For achievements using the "separate" tracking type, *each* item being tracked must tally up to this number to be completed.
- **tracking_type** (str): *Default value if unset: `"sum"`* There are two valid tracking types: "sum" (which is the default) and "separate". `"sum"` will increment a single counter every time any of the tracked items match. `"separate"` will have a counter for each individual item in the tracked items. ("See the Example Achievements" section for a demonstration of the difference.)
- **prereqs** (str or list): The *keys* of any achievements which must be completed before this achievement can start tracking progress.
### Example achievements
A simple achievement which you can get just for logging in the first time. This achievement has no prerequisites and it only needs to be fulfilled once to complete.
```python
# This achievement has the unique key of "first_login_achieve"
FIRST_LOGIN_ACHIEVE = {
"name": "Welcome!", # the searchable, player-friendly display name
"desc": "We're glad to have you here.", # the longer description
"category": "login", # the type of action this tracks
"tracking": "first", # the specific login action
}
```
An achievement for killing a total of 10 rats, and another for killing 10 *dire* rats which requires the "kill 10 rats" achievement to be completed first. The dire rats achievement won't begin tracking *any* progress until the first achievement is completed.
```python
# This achievement has the unique key of "ten_rats" instead of "achieve_ten_rats"
ACHIEVE_TEN_RATS = {
"key": "ten_rats",
"name": "The Usual",
"desc": "Why do all these inns have rat problems?",
"category": "defeat",
"tracking": "rat",
"count": 10,
}
ACHIEVE_DIRE_RATS = {
"name": "Once More, But Bigger",
"desc": "Somehow, normal rats just aren't enough any more.",
"category": "defeat",
"tracking": "dire rat",
"count": 10,
"prereqs": "ACHIEVE_TEN_RATS",
}
```
An achievement for buying a total of 5 of apples, oranges, *or* pears. The "sum" tracking types means that all items are tallied together - so it can be completed by buying 5 apples, or 5 pears, or 3 apples, 1 orange and 1 pear, or any other combination of those three fruits that totals to 5.
```python
FRUIT_FAN_ACHIEVEMENT = {
"name": "A Fan of Fruit", # note, there is no desc here - that's allowed!
"category": "buy",
"tracking": ("apple", "orange", "pear"),
"count": 5,
"tracking_type": "sum", # this is the default, but it's included here for clarity
}
```
An achievement for buying 5 *each* of apples, oranges, and pears. The "separate" tracking type means that each of the tracked items is tallied independently of the other items - so you will need 5 apples, 5 oranges, and 5 pears.
```python
FRUIT_BASKET_ACHIEVEMENT = {
"name": "Fruit Basket",
"desc": "One kind of fruit just isn't enough.",
"category": "buy",
"tracking": ("apple", "orange", "pear"),
"count": 5,
"tracking_type": "separate",
}
```
## Usage
The two main things you'll need to do in order to use the achievements contrib in your game are **tracking achievements** and **getting achievement information**. The first is done with the function `track_achievements`; the second can be done with `search_achievement` or `get_achievement`.
### Tracking achievements
#### `track_achievements`
In any actions or functions in your game's mechanics which you might want to track in an achievement, add a call to `track_achievements` to update that player's achievement progress.
Using the "kill 10 rats" example achievement from earlier, you might have some code that triggers when a character is defeated: for the sake of example, we'll pretend we have an `at_defeated` method on the base Object class that gets called when the Object is defeated.
Adding achievement tracking to it could then look something like this:
```python
# in typeclasses/objects.py
from contrib.game_systems.achievements import track_achievements
class Object(ObjectParent, DefaultObject):
# ....
def at_defeated(self, victor):
"""called when this object is defeated in combat"""
# we'll use the "mob_type" tag-category as the tracked info
# this way we can have rats named "black rat" and "brown rat" that are both rats
mob_type = self.tags.get(category="mob_type")
# only one mob was defeated, so we include a count of 1
track_achievements(victor, category="defeated", tracking=mob_type, count=1)
```
If a player defeats something tagged `rat` with a tag category of `mob_type`, it'd now count towards the rat-killing achievement.
You can also have the tracking information hard-coded into your game, for special or unique situations. The achievement described earlier, `FIRST_LOGIN_ACHIEVE`, for example, would be tracked like this:
```py
# in typeclasses/accounts.py
from contrib.game_systems.achievements import track_achievements
class Account(DefaultAccount):
# ...
def at_first_login(self, **kwargs):
# this function is only called on the first time the account logs in
# so we already know and can just tell the tracker that this is the first
track_achievements(self, category="login", tracking="first")
```
The `track_achievements` function does also return a value: an iterable of keys for any achievements which were newly completed by that update. You can ignore this value, or you can use it to e.g. send a message to the player with their latest achievements.
### Getting achievements
The main method for getting a specific achievement's information is `get_achievement`, which takes an already-known achievement key and returns the data for that one achievement.
For handling more variable and player-friendly input, however, there is also `search_achievement`, which does partial matching on not just the keys, but also the display names and descriptions for the achievements.
#### `get_achievement`
A utility function for retrieving a specific achievement's data from the achievement's unique key. It cannot be used for searching, but if you already have an achievement's key - for example, from the results of `track_achievements` - you can retrieve its data this way.
#### Example:
```py
from evennia.contrib.game_systems.achievements import get_achievement
def toast(achiever, completed_list):
if completed_list:
# `completed_data` will be a list of dictionaries - unrecognized keys return empty dictionaries
completed_data = [get_achievement(key) for key in args]
names = [data.get('name') for data in completed]
achiever.msg(f"|wAchievement Get!|n {iter_to_str(name for name in names if name)}"))
```
#### `search_achievement`
A utility function for searching achievements by name or description. It handles partial matching and returns a dictionary of matching achievements. The provided `achievement` command for in-game uses this function to find matching achievements from user inputs.
#### Example:
The first example does a search for "fruit", which returns the fruit medley achievement as it contains "fruit" in the key and name.
The second example searches for "usual", which returns the ten rats achievement due to its display name.
```py
>>> from evennia.contrib.game_systems.achievements import search_achievement
>>> search_achievement("fruit")
{'fruit_basket_achievement': {'name': 'Fruit Basket', 'desc': "One kind of fruit just isn't enough.", 'category': 'buy', 'tracking': ('apple', 'orange', 'pear'), 'count': 5, 'tracking_type': 'separate'}}
>>> search_achievement("usual")
{'ten_rats': {'key': 'ten_rats', 'name': 'The Usual', 'desc': 'Why do all these inns have rat problems?', 'category': 'defeat', 'tracking': 'rat', 'count': 10}}
```
### The `achievements` command
The contrib's provided command, `CmdAchieve`, aims to be usable as-is, with multiple switches to filter achievements by various progress statuses and the ability to search by achievement names.
To make it easier to customize for your own game (e.g. displaying some of that extra achievement data you might have added), the format and style code is split out from the command logic into the `format_achievement` method and the `template` attribute, both on `CmdAchieve`
#### Example output
```
> achievements
The Usual
Why do all these inns have rat problems?
70% complete
A Fan of Fruit
Not Started
```
```
> achievements/progress
The Usual
Why do all these inns have rat problems?
70% complete
```
```
> achievements/done
There are no matching achievements.
```

View file

@ -0,0 +1,8 @@
from .achievements import (
get_achievement,
search_achievement,
all_achievements,
track_achievements,
get_achievement_progress,
CmdAchieve,
)

View file

@ -0,0 +1,404 @@
"""
Achievements
This provides a system for adding and tracking player achievements in your game.
Achievements are defined as dicts, loosely similar to the prototypes system.
An example of an achievement dict:
ACHIEVE_DIRE_RATS = {
"name": "Once More, But Bigger",
"desc": "Somehow, normal rats just aren't enough any more.",
"category": "defeat",
"tracking": "dire rat",
"count": 10,
"prereqs": "ACHIEVE_TEN_RATS",
}
The recognized fields for an achievement are:
- key (str): The unique, case-insensitive key identifying this achievement. The variable name is
used by default.
- name (str): The name of the achievement. This is not the key and does not need to be unique.
- desc (str): The longer description of the achievement. Common uses for this would be flavor text
or hints on how to complete it.
- category (str): The category of conditions which this achievement tracks. It will most likely be
an action and you will most likely specify it based on where you're checking from.
e.g. killing 10 rats might have a category of "defeat", which you'd then check from your code
that runs when a player defeats something.
- tracking (str or list): The specific condition this achievement tracks. e.g. for the above example of
10 rats, the tracking field would be "rat".
- tracking_type: The options here are "sum" and "separate". "sum" means that matching any tracked
item will increase the total. "separate" means all tracked items are counted individually.
This is only useful when tracking is a list. The default is "sum".
- count (int): The total tallies the tracked item needs for this to be completed. e.g. for the rats
example, it would be 10. The default is 1
- prereqs (str or list): An optional achievement key or list of keys that must be completed before
this achievement is available.
To add achievement tracking, put `track_achievements` in your relevant hooks.
Example:
def at_defeated(self, victor):
# called when this object is defeated in combat
# we'll use the "mob_type" tag category as the tracked information for achievements
mob_type = self.tags.get(category="mob_type")
track_achievements(victor, category="defeated", tracking=mob_type, count=1)
"""
from collections import Counter
from django.conf import settings
from evennia.utils import logger
from evennia.utils.utils import all_from_module, is_iter, make_iter, string_partial_matching
from evennia.utils.evmore import EvMore
from evennia.commands.default.muxcommand import MuxCommand
# this is either a string of the attribute name, or a tuple of strings of the attribute name and category
_ACHIEVEMENT_ATTR = make_iter(getattr(settings, "ACHIEVEMENT_CONTRIB_ATTRIBUTE", "achievements"))
_ATTR_KEY = _ACHIEVEMENT_ATTR[0]
_ATTR_CAT = _ACHIEVEMENT_ATTR[1] if len(_ACHIEVEMENT_ATTR) > 1 else None
# load the achievements data
_ACHIEVEMENT_DATA = {}
if modules := getattr(settings, "ACHIEVEMENT_CONTRIB_MODULES", None):
for module_path in make_iter(modules):
module_achieves = {
val.get("key", key).lower(): val
for key, val in all_from_module(module_path).items()
if isinstance(val, dict) and not key.startswith("_")
}
if any(key in _ACHIEVEMENT_DATA for key in module_achieves.keys()):
logger.log_warn(
"There are conflicting achievement keys! Only the last achievement registered to the key will be recognized."
)
_ACHIEVEMENT_DATA |= module_achieves
else:
logger.log_warn("No achievement modules have been added to settings.")
def _read_player_data(achiever):
"""
helper function to get a player's achievement data from the database.
Args:
achiever (Object or Account): The achieving entity
Returns:
dict: The deserialized achievement data.
"""
if data := achiever.attributes.get(_ATTR_KEY, default={}, category=_ATTR_CAT):
# detach the data from the db
data = data.deserialize()
# return the data
return data or {}
def _write_player_data(achiever, data):
"""
helper function to write a player's achievement data to the database.
Args:
achiever (Object or Account): The achieving entity
data (dict): The full achievement data for this entity.
Returns:
None
Notes:
This function will overwrite any existing achievement data for the entity.
"""
achiever.attributes.add(_ATTR_KEY, data, category=_ATTR_CAT)
def track_achievements(achiever, category=None, tracking=None, count=1, **kwargs):
"""
Update and check achievement progress.
Args:
achiever (Account or Character): The entity that's collecting achievement progress.
Keyword args:
category (str or None): The category of an achievement.
tracking (str or None): The specific item being tracked in the achievement.
Returns:
tuple: The keys of any achievements that were completed by this update.
"""
if not _ACHIEVEMENT_DATA:
# there are no achievements available, there's nothing to do
return tuple()
# get the achiever's progress data
progress_data = _read_player_data(achiever)
# filter all of the achievements down to the relevant ones
relevant_achievements = (
(key, val)
for key, val in _ACHIEVEMENT_DATA.items()
if (not category or category in make_iter(val.get("category", []))) # filter by category
and (
not tracking
or not val.get("tracking")
or tracking in make_iter(val.get("tracking", []))
) # filter by tracked item
and not progress_data.get(key, {}).get("completed") # filter by completion status
and all(
progress_data.get(prereq, {}).get("completed")
for prereq in make_iter(val.get("prereqs", []))
) # filter by prereqs
)
completed = []
# loop through all the relevant achievements and update the progress data
for achieve_key, achieve_data in relevant_achievements:
if target_count := achieve_data.get("count", 1):
# check if we need to track things individually or not
separate_totals = achieve_data.get("tracking_type", "sum") == "separate"
if achieve_key not in progress_data:
progress_data[achieve_key] = {}
if separate_totals and is_iter(achieve_data.get("tracking")):
# do the special handling for tallying totals separately
i = achieve_data["tracking"].index(tracking)
if "progress" not in progress_data[achieve_key]:
# initialize the item counts
progress_data[achieve_key]["progress"] = [
0 for _ in range(len(achieve_data["tracking"]))
]
# increment the matching index count
progress_data[achieve_key]["progress"][i] += count
# have we reached the target on all items? if so, we've completed it
if min(progress_data[achieve_key]["progress"]) >= target_count:
completed.append(achieve_key)
else:
progress_count = progress_data[achieve_key].get("progress", 0)
# update the achievement data
progress_data[achieve_key]["progress"] = progress_count + count
# have we reached the target? if so, we've completed it
if progress_data[achieve_key]["progress"] >= target_count:
completed.append(achieve_key)
else:
# no count means you just need to do the thing to complete it
completed.append(achieve_key)
for key in completed:
if key not in progress_data:
progress_data[key] = {}
progress_data[key]["completed"] = True
# write the updated progress back to the achievement attribute
_write_player_data(achiever, progress_data)
# return all the achievements we just completed
return tuple(completed)
def get_achievement(key):
"""
Get an achievement by its key.
Args:
key (str): The achievement key. This is the variable name the achievement dict is assigned to.
Returns:
dict or None: The achievement data, or None if it doesn't exist
"""
if not _ACHIEVEMENT_DATA:
# there are no achievements available, there's nothing to do
return None
if data := _ACHIEVEMENT_DATA.get(key.lower()):
return dict(data)
return None
def all_achievements():
"""
Returns a dict of all achievements in the game.
Returns:
dict
"""
# we do this to mitigate accidental in-memory modification of reference data
return dict((key, dict(val)) for key, val in _ACHIEVEMENT_DATA.items())
def get_achievement_progress(achiever, key):
"""
Retrieve the progress data on a particular achievement for a particular achiever.
Args:
achiever (Account or Character): The entity tracking achievement progress.
key (str): The achievement key
Returns:
dict: The progress data
"""
if progress_data := _read_player_data(achiever):
# get the specific key's data
return progress_data.get(key, {})
else:
# just return an empty dict
return {}
def search_achievement(search_term):
"""
Search for an achievement containing the search term. If no matches are found in the achievement names, it searches
in the achievement descriptions.
Args:
search_term (str): The string to search for.
Returns:
dict: A dict of key:data pairs of matching achievements.
"""
if not _ACHIEVEMENT_DATA:
# there are no achievements available, there's nothing to do
return {}
keys, names, descs = zip(
*((key, val["name"], val["desc"]) for key, val in _ACHIEVEMENT_DATA.items())
)
indices = string_partial_matching(names, search_term)
if not indices:
indices = string_partial_matching(descs, search_term)
return dict((keys[i], dict(_ACHIEVEMENT_DATA[keys[i]])) for i in indices)
class CmdAchieve(MuxCommand):
"""
view achievements
Usage:
achievements[/switches] [args]
Switches:
all View all achievements, including locked ones.
completed View achievements you've completed.
progress View achievements you have partially completed
Check your achievement statuses or browse the list. Providing a command argument
will search all your currently unlocked achievements for matches, and the switches
will filter the list to something other than "all unlocked". Combining a command
argument with a switch will search only in that list.
Examples:
achievements apples
achievements/all
achievements/progress rats
"""
key = "achievements"
aliases = (
"achievement",
"achieve",
"achieves",
)
switch_options = ("progress", "completed", "done", "all")
template = """\
|w{name}|n
{desc}
{status}
""".rstrip()
def format_achievement(self, achievement_data):
"""
Formats the raw achievement data for display.
Args:
achievement_data (dict): The data to format.
Returns
str: The display string to be sent to the caller.
"""
if achievement_data.get("completed"):
# it's done!
status = "|gCompleted!|n"
elif not achievement_data.get("progress"):
status = "|yNot Started|n"
else:
count = achievement_data.get("count",1)
# is this achievement tracking items separately?
if is_iter(achievement_data["progress"]):
# we'll display progress as how many items have been completed
completed = Counter(val >= count for val in achievement_data["progress"])[True]
pct = (completed * 100) // len(achievement_data['progress'])
else:
# we display progress as the percent of the total count
pct = (achievement_data["progress"] * 100) // count
status = f"{pct}% complete"
return self.template.format(
name=achievement_data.get("name", ""),
desc=achievement_data.get("desc", ""),
status=status,
)
def func(self):
if self.args:
# we're doing a name lookup
if not (achievements := search_achievement(self.args.strip())):
self.msg(f"Could not find any achievements matching '{self.args.strip()}'.")
return
else:
# we're checking against all achievements
if not (achievements := all_achievements()):
self.msg("There are no achievements in this game.")
return
# get the achiever's progress data
progress_data = _read_player_data(self.caller)
if self.caller != self.account:
progress_data |= _read_player_data(self.account)
# go through switch options
# we only show achievements that are in progress
if "progress" in self.switches:
# we filter our data to incomplete achievements, and combine the base achievement data into it
achievement_data = {
key: achievements[key] | data
for key, data in progress_data.items()
if not data.get("completed")
}
# we only show achievements that are completed
elif "completed" in self.switches or "done" in self.switches:
# we filter our data to finished achievements, and combine the base achievement data into it
achievement_data = {
key: achievements[key] | data
for key, data in progress_data.items()
if data.get("completed")
}
# we show ALL achievements
elif "all" in self.switches:
# we merge our progress data into the full dict of achievements
achievement_data = {
key: data | progress_data.get(key, {})
for key, data in achievements.items()
}
# we show all of the currently available achievements regardless of progress status
else:
achievement_data = {
key: data | progress_data.get(key, {})
for key, data in achievements.items()
if all(
progress_data.get(prereq, {}).get("completed")
for prereq in make_iter(data.get("prereqs", []))
)
}
if not achievement_data:
self.msg("There are no matching achievements.")
return
achievement_str = "\n".join(
self.format_achievement(data) for _, data in achievement_data.items()
)
EvMore(self.caller, achievement_str)

View file

@ -0,0 +1,178 @@
from evennia.utils.test_resources import BaseEvenniaTest, BaseEvenniaCommandTest
from mock import patch
from . import achievements
_dummy_achievements = {
"ACHIEVE_ONE": {
"name": "First Achievement",
"desc": "A first achievement for first achievers.",
"category": "login",
},
"COUNTING_ACHIEVE": {
"name": "The Count",
"desc": "One, two, three! Three counters! Ah ah ah!",
"category": "get",
"tracking": "thing",
"count": 3,
},
"COUNTING_TWO": {
"name": "Son of the Count",
"desc": "Four, five, six! Six counters!",
"category": "get",
"tracking": "thing",
"count": 3,
"prereqs": "COUNTING_ACHIEVE",
},
"SEPARATE_ITEMS": {
"name": "Apples and Pears",
"desc": "Get some apples and some pears.",
"category": "get",
"tracking": ("apple", "pear"),
"tracking_type": "separate",
"count": 3,
},
}
class TestAchievements(BaseEvenniaTest):
@patch(
"evennia.contrib.game_systems.achievements.achievements._ACHIEVEMENT_DATA",
_dummy_achievements,
)
def test_completion(self):
"""no defined count means a single match completes it"""
self.assertIn(
"ACHIEVE_ONE",
achievements.track_achievements(self.char1, category="login", track="first"),
)
@patch(
"evennia.contrib.game_systems.achievements.achievements._ACHIEVEMENT_DATA",
_dummy_achievements,
)
def test_counter_progress(self):
"""progressing a counter should update the achiever"""
# this should not complete any achievements; verify it returns the right empty result
self.assertEqual(achievements.track_achievements(self.char1, "get", "thing"), tuple())
# first, verify that the data is created
self.assertTrue(self.char1.attributes.has("achievements"))
self.assertEqual(self.char1.db.achievements["COUNTING_ACHIEVE"]["progress"], 1)
# verify that it gets updated
achievements.track_achievements(self.char1, "get", "thing")
self.assertEqual(self.char1.db.achievements["COUNTING_ACHIEVE"]["progress"], 2)
# also verify that `get_achievement_progress` returns the correct data
self.assertEqual(
achievements.get_achievement_progress(self.char1, "COUNTING_ACHIEVE"), {"progress": 2}
)
@patch(
"evennia.contrib.game_systems.achievements.achievements._ACHIEVEMENT_DATA",
_dummy_achievements,
)
def test_prereqs(self):
"""verify progress is not counted on achievements with unmet prerequisites"""
achievements.track_achievements(self.char1, "get", "thing")
# this should mark progress on COUNTING_ACHIEVE, but NOT on COUNTING_TWO
self.assertEqual(
achievements.get_achievement_progress(self.char1, "COUNTING_ACHIEVE"), {"progress": 1}
)
self.assertEqual(achievements.get_achievement_progress(self.char1, "COUNTING_TWO"), {})
# now we complete COUNTING_ACHIEVE...
self.assertIn(
"COUNTING_ACHIEVE", achievements.track_achievements(self.char1, "get", "thing", count=2)
)
# and track again to progress COUNTING_TWO
achievements.track_achievements(self.char1, "get", "thing")
self.assertEqual(
achievements.get_achievement_progress(self.char1, "COUNTING_TWO"), {"progress": 1}
)
@patch(
"evennia.contrib.game_systems.achievements.achievements._ACHIEVEMENT_DATA",
_dummy_achievements,
)
def test_separate_tracking(self):
"""achievements with 'tracking_type': 'separate' should count progress for each item"""
# getting one item only increments that one item
achievements.track_achievements(self.char1, "get", "apple")
progress = achievements.get_achievement_progress(self.char1, "SEPARATE_ITEMS")
self.assertEqual(progress["progress"], [1, 0])
# the other item then increments that item
achievements.track_achievements(self.char1, "get", "pear")
progress = achievements.get_achievement_progress(self.char1, "SEPARATE_ITEMS")
self.assertEqual(progress["progress"], [1, 1])
# completing one does not complete the achievement
self.assertEqual(
achievements.track_achievements(self.char1, "get", "apple", count=2), tuple()
)
# completing the second as well DOES complete the achievement
self.assertIn(
"SEPARATE_ITEMS", achievements.track_achievements(self.char1, "get", "pear", count=2)
)
@patch(
"evennia.contrib.game_systems.achievements.achievements._ACHIEVEMENT_DATA",
_dummy_achievements,
)
def test_search_achievement(self):
"""searching for achievements by name"""
results = achievements.search_achievement("count")
self.assertEqual(["COUNTING_ACHIEVE", "COUNTING_TWO"], list(results.keys()))
class TestAchieveCommand(BaseEvenniaCommandTest):
@patch(
"evennia.contrib.game_systems.achievements.achievements._ACHIEVEMENT_DATA",
_dummy_achievements,
)
def test_switches(self):
# print only achievements that have no prereqs
expected_output = "\n".join(
f"{data['name']}\n{data['desc']}\nNot Started"
for key, data in _dummy_achievements.items()
if not data.get("prereqs")
)
self.call(achievements.CmdAchieve(), "", expected_output)
# print all achievements
expected_output = "\n".join(
f"{data['name']}\n{data['desc']}\nNot Started"
for key, data in _dummy_achievements.items()
)
self.call(achievements.CmdAchieve(), "/all", expected_output)
# these should both be empty
self.call(achievements.CmdAchieve(), "/progress", "There are no matching achievements.")
self.call(achievements.CmdAchieve(), "/done", "There are no matching achievements.")
# update one and complete one, then verify they show up correctly
achievements.track_achievements(self.char1, "login")
achievements.track_achievements(self.char1, "get", "thing")
self.call(
achievements.CmdAchieve(),
"/progress",
"The Count\nOne, two, three! Three counters! Ah ah ah!\n33% complete",
)
self.call(
achievements.CmdAchieve(),
"/done",
"First Achievement\nA first achievement for first achievers.\nCompleted!",
)
@patch(
"evennia.contrib.game_systems.achievements.achievements._ACHIEVEMENT_DATA",
_dummy_achievements,
)
def test_search(self):
# by default, only returns matching items that are trackable
self.call(
achievements.CmdAchieve(),
" count",
"The Count\nOne, two, three! Three counters! Ah ah ah!\nNot Started",
)
# with switches, returns matching items from the switch set
self.call(
achievements.CmdAchieve(),
"/all count",
"The Count\nOne, two, three! Three counters! Ah ah ah!\nNot Started\n"
+ "Son of the Count\nFour, five, six! Six counters!\nNot Started",
)