Ren'Py has support for saving game state, loading game state, and rolling back to a previous game state. Although implemented in a slightly different fashion, rollback can be thought of as saving the game at the start of each statement that interacts with the user, and loading saves when the user rolls back.
Note
While we usually attempt to keep save compatibility between releases, this compatibility is not guaranteed. We may decide to break save-compatibility if doing so provides a sufficiently large benefit.
Ren'Py attempts to save the game state. This includes both internal state and Python state.
The internal state consists of all aspects of Ren'Py that are intented to change once the game has started, and includes:
The Python state consists of the variables in the store that have changed since the game began, and all objects reachable from those variables. Note that it's the change to the variables that matters – changes to fields in objects will not cause those objects to be saved.
Variables set using the default statement will always be saved.
In this example:
define a = 1
define o = object()
default c = 17
label start:
$ b = 1
$ o.value = 42
only b and c will be saved. A will not be saved because it does not change once the game begins. O is not saved because it does not change – the object it refers to changes, but the variable itself does not.
Python variables that are not changed after the game begins will not be saved. This can be a major problem if a variable that is not saved and one that is refer to the same object. (Alias the object.) In this example:
init python:
a = object()
a.f = 1
label start:
$ b = a
$ b.f = 2
"a.f=[a.f] b.f=[b.f]"
a and b are aliased. Saving and loading may break this aliasing, causing a and b to refer to different objects. Since this can be very confusing, it's best to avoid aliasing saved and unsaved variables. (This is rare to encounter directly, but might come up when an unsaved variable and saved field alias.)
There are several other kinds of state that isn't saved:
init
blocks, and left alone
once the game has started.Saves occur at the start of a Ren'Py statement in the outermost interaction context.
What's important here is to note that saving occurs at the start of a statement. If a load or rollback occurs in the middle of a statement that interacts multiple times, the state will be the state that was active when the statement began.
This can be a problem in Python-defined statements. In:
python:
i = 0
while i < 10:
i += 1
narrator("The count is now [i].")
if the user saves and loads in the middle, the loop will begin anew. Using Ren'Py script – rather than Python – to loop avoids this problem.:
$ i = 0
while i < 10:
$ i += 1
"The count is now [i]."
Ren'Py uses the Python pickle system to save game state. This module can save:
There are certain types that cannot be pickled:
async
and await
.This may not be an exhaustive list.
Objects that can't be pickled can still be used, provided that their use
is combined to namespaces that aren't saved by Ren'Py (like init variables,
namespaces inside functions, or python hide
blocks.)
For example, using a file object like:
$ monika_file = open(config.gamedir + "/monika.chr", "w")
$ monika_file.write("Do not delete.\r\n")
$ monika_file.close()
Won't work, as f
could be saved between any of the three Python statements.
Putting this in a python hide
block will work:
python hide:
monika_file = open(config.gamedir + "/monika.chr", "w")
monika_file.write("Do not delete.\r\n")
monika_file.close()
(Of course, using the python with
statement would be cleaner.)
python hide:
with open(config.gamedir + "/monika.chr", "w") as monika_file:
monika_file.write("Do not delete.\r\n")
Coroutines, like those made with async
, await
, or the asyncio
are similar. If you have:
init python:
import asyncio
async def sleep_func():
await asyncio.sleep(1)
await asyncio.sleep(1)
then:
$ sleep_task = sleep_func()
$ asyncio.run(sleep_task)
will have problems, since sleep_task can't be saved. But if it's not assigned to a variable:
$ asyncio.run(sleep_func())
will run fine.
There is one variable that is used by the high-level save system:
save_name
= ... linkThis is a string that is stored with each save. It can be used to give a name to the save, to help users tell them apart.
More per-save data customization can be done with the Json supplementary
data system, see config.save_json_callbacks
.
There are a number of high-level save actions and functions defined in the screen actions. In addition, there are the following low-level save and load actions.
renpy.
can_load
(filename, test=False) linkReturns true if filename exists as a save slot, and False otherwise.
renpy.
copy_save
(old, new) linkCopies the save at old to new. (Does nothing if old does not exist.)
renpy.
list_saved_games
(regexp=u'.', fast=False) linkLists the save games. For each save game, returns a tuple containing:
renpy.
list_slots
(regexp=None) linkReturns a list of non-empty save slots. If regexp exists, only slots that begin with regexp are returned. The slots are sorted in string-order.
renpy.
load
(filename) linkLoads the game state from the save slot filename. If the file is loaded successfully, this function never returns.
renpy.
newest_slot
(regexp=None) linkReturns the name of the newest save slot (the save slot with the most recent modification time), or None if there are no (matching) saves.
If regexp exists, only slots that begin with regexp are returned.
renpy.
rename_save
(old, new) linkRenames a save from old to new. (Does nothing if old does not exist.)
renpy.
save
(filename, extra_info='') linkSaves the game state to a save slot.
save_name
.renpy.take_screenshot()
should be called before this function.
renpy.
slot_json
(slotname) linkReturns the json information for slotname, or None if the slot is empty.
Much like the d
argument to the config.save_json_callback
function, it will be returned as a dictionary. More precisely, the
dictionary will contain the same data as it did when the game was saved.
renpy.
slot_mtime
(slotname) linkReturns the modification time for slot, or None if the slot is empty.
renpy.
slot_screenshot
(slotname) linkReturns a display that can be used as the screenshot for slotname, or None if the slot is empty.
renpy.
take_screenshot
(scale=None, background=False) linkCauses a screenshot to be taken. This screenshot will be saved as part of a save game.
renpy.
unlink_save
(filename) linkDeletes the save slot with the given name.
When a game is loaded, the state of the game is reset (using the rollback system described below) to the state of the game when the current statement began executing.
In some cases, this may not be desirable. For example, when a screen allows editing of a value, we may want to retain that value when the game is loaded. When renpy.retain_after_load is called, data will not be reverted when a game is saved and loaded before the end of the next checkpointed interaction.
Note that while data is not changed, control is reset to the start of the current statement. That statement will execute again, with the new data in place at the start of the statement.
For example:
screen edit_value:
hbox:
text "[value]"
textbutton "+" action SetVariable("value", value + 1)
textbutton "-" action SetVariable("value", value - 1)
textbutton "+" action Return(True)
label start:
$ value = 0
$ renpy.retain_after_load()
call screen edit_value
renpy.
retain_after_load
() linkCauses data modified between the current statement and the statement containing the next checkpoint to be retained when a load occurs.
Rollback allows the user to revert the game to an earlier state in much the same way as undo/redo systems that are available in most modern applications. While the system takes care of maintaining the visuals and game variables during rollback events, there are several things that should be considered while creating a game.
Rollback affects variables that have been changed after the init phase, and objects of revertable types reachable from those variables. The short version is that lists, dicts, and sets created in Ren'Py script are revertable as are instances of classes defined in Ren'Py scripts. Data created inside Python or inside Ren'Py usually isn't revertable.
In more detail, inside the stores
that Python embedded inside Ren'Py scripts run in, the object, list, dict, and
set types have been replaced with equivalent types that are revertable. Objects
that inherit from these types are also revertable. The renpy.Displayable
type inherits from the revertable object type.
To make the use of revertable objects more convenient, Ren'Py modifies Python found inside Ren'Py script files in the following way.
In addition:
Calling into Python code will not generally produce a revertable object. Some cases where you'll get an object that may not participate in rollback are:
If such data needs to participate in rollback, it may make sense to convert it to a type that does partipate. For example:
# Calling list inside Python-in-Ren'Py converts a non-revertable list
# into a revertable one.
$ attrs = list(renpy.get_attributes("eileen"))
Most Ren'Py statements automatically support rollback and roll forward. If
you call ui.interact()
directly, you'll need to add support for rollback
and roll-forward yourself. This can be done using the following structure:
# This is None if we're not rolling back, or else the value that was
# passed to checkpoint last time if we're rolling forward.
roll_forward = renpy.roll_forward_info()
# Set up the screen here...
# Interact with the user.
rv = ui.interact(roll_forward=roll_forward)
# Store the result of the interaction.
renpy.checkpoint(rv)
It's important that your game does not interact with the user after renpy.checkpoint has been called. (If you do, the user may not be able to rollback.)
renpy.
can_rollback
() linkReturns true if we can rollback.
renpy.
checkpoint
(data=None) linkMakes the current statement a checkpoint that the user can rollback to. Once this function has been called, there should be no more interaction with the user in the current statement.
This will also clear the current screenshot used by saved games.
renpy.roll_forward_info()
when the
game is being rolled back.renpy.
get_identifier_checkpoints
(identifier) linkGiven a rollback_identifier from a HistoryEntry object, returns the number
of checkpoints that need to be passed to renpy.rollback()
to reach
that identifier. Returns None of the identifier is not in the rollback
history.
renpy.
in_rollback
() linkReturns true if the game has been rolled back.
renpy.
roll_forward_info
() linkWhen in rollback, returns the data that was supplied to renpy.checkpoint()
the last time this statement executed. Outside of rollback, returns None.
renpy.
rollback
(force=False, checkpoints=1, defer=False, greedy=True, label=None, abnormal=True) linkRolls the state of the game back to the last checkpoint.
renpy.
suspend_rollback
(flag) linkRollback will skip sections of the game where rollback has been suspended.
Warning
Blocking rollback is a user-unfriendly thing to do. If a user mistakenly clicks on an unintended choice, he or she will be unable to correct their mistake. Since rollback is equivalent to saving and loading, your users will be forced to save more often, breaking game engagement.
It is possible to disable rollback in part or in full. If rollback is
not wanted at all, it can simply be turned off through the
config.rollback_enabled
option.
More common is a partial block of rollback. This can be achieved by the
renpy.block_rollback()
function. When called, it will instruct
Ren'Py not to roll back before that point. For example:
label final_answer:
"Is that your final answer?"
menu:
"Yes":
jump no_return
"No":
"We have ways of making you talk."
"You should contemplate them."
"I'll ask you one more time..."
jump final_answer
label no_return:
$ renpy.block_rollback()
"So be it. There's no turning back now."
When the label no_return is reached, Ren'Py won't allow a rollback back to the menu.
Fixing rollback provides for an intermediate choice between
unconstrained rollback and blocking rollback entirely. Rollback is
allowed, but the user is not allowed to make changes to their
decisions. Fixing rollback is done with the renpy.fix_rollback()
function, as shown in the following example:
label final_answer:
"Is that your final answer?"
menu:
"Yes":
jump no_return
"No":
"We have ways of making you talk."
"You should contemplate them."
"I'll ask you one more time..."
jump final_answer
label no_return:
$ renpy.fix_rollback()
"So be it. There's no turning back now."
Now, after the fix_rollback function is called, it will still be possible for the user to roll back to the menu. However, it will not be possible to make a different choice.
There are some caveats to consider when designing a game for
fix_rollback. Ren'Py will automatically take care of locking any data
that is given to checkpoint()
. However, due to the generic nature
of Ren'Py, it is possible to write scripts that bypass this and
change things in ways that may have unpredictable results. Most notably,
call screen
doesn't work well with fixed rollback. It is up
to the creator to block rollback at problematic locations.
The internal user interaction options for menus, renpy.input()
and renpy.imagemap()
are designed to fully work with fix_rollback.
Because fix_rollback changes the functionality of menus and imagemaps,
it is advisable to reflect this in the appearance. To do this, it is
important to understand how the widget states of the menu buttons are
changed. There are two modes that can be selected through the
config.fix_rollback_without_choice
option.
The default option will set the chosen option to "selected", thereby activating the style properties with the "selected_" prefix. All other buttons will be made insensitive and show using the properties with the "insensitive_" prefix. Effectively this leaves the menu with a single selectable choice.
When the config.fix_rollback_without_choice
option is set to
False, all buttons are made insensitive. This means that the chosen
option will use the "selected_insensitive_" prefix for the style
properties while the other buttons use properties with the
"insensitive_" prefix.
When writing custom Python routines that must play nice with the
fix_rollback system there are a few simple things to know. First of all
the renpy.in_fixed_rollback()
function can be used to determine whether
the game is currently in fixed rollback state. Second, when in
fixed rollback state, ui.interact()
will always return the
supplied roll_forward data regardless of what action was performed. This
effectively means that when the ui.interact()
/renpy.checkpoint()
functions are used, most of the work is done.
To simplify the creation of custom screens, two actions are
provided to help with the most common uses. The ui.ChoiceReturn()
action
returns the value when the button it is attached to is clicked. The
ui.ChoiceJump()
action can be used to jump to a script label. However, this
action only works properly when the screen is called trough a
call screen
statement.
Example:
screen demo_imagemap:
imagemap:
ground "imagemap_ground.jpg"
hover "imagemap_hover.jpg"
selected_idle "imagemap_selected_idle.jpg"
selected_hover "imagemap_hover.jpg"
hotspot (8, 200, 78, 78) action ui.ChoiceJump("swimming", "go_swimming", block_all=False)
hotspot (204, 50, 78, 78) action ui.ChoiceJump("science", "go_science_club", block_all=False)
hotspot (452, 79, 78, 78) action ui.ChoiceJump("art", "go_art_lessons", block_all=False)
hotspot (602, 316, 78, 78) action ui.ChoiceJump("home", "go_home", block_all=False)
Example:
python:
roll_forward = renpy.roll_forward_info()
if roll_forward not in ("Rock", "Paper", "Scissors"):
roll_forward = None
ui.hbox()
ui.imagebutton("rock.png", "rock_hover.png", selected_insensitive="rock_hover.png", clicked=ui.ChoiceReturn("rock", "Rock", block_all=True))
ui.imagebutton("paper.png", "paper_hover.png", selected_insensitive="paper_hover.png", clicked=ui.ChoiceReturn("paper", "Paper", block_all=True))
ui.imagebutton("scissors.png", "scissors_hover.png", selected_insensitive="scissors_hover.png", clicked=ui.ChoiceReturn("scissors", "Scissors", block_all=True))
ui.close()
if renpy.in_fixed_rollback():
ui.saybehavior()
choice = ui.interact(roll_forward=roll_forward)
renpy.checkpoint(choice)
$ renpy.fix_rollback()
m "[choice]!"
renpy.
block_rollback
() linkPrevents the game from rolling back to before the current statement.
renpy.
fix_rollback
() linkPrevents the user from changing decisions made before the current statement.
renpy.
in_fixed_rollback
() linkReturns true if rollback is currently occurring and the current context is before an executed renpy.fix_rollback() statement.
ui.
ChoiceJump
(label, value, location=None, block_all=None, sensitive=True, args=None, kwargs=None) linkA menu choice action that returns value, while managing the button state in a manner consistent with fixed rollback. (See block_all for a description of the behavior.)
If false, the button is given the selected role if it was the chosen choice, and insensitive if it was not selected.
If true, the button is always insensitive during fixed rollback.
If None, the value is taken from the config.fix_rollback_without_choice
variable.
When true is given to all items in a screen, it will
become unclickable (rolling forward will still work). This can
be changed by calling ui.saybehavior()
before the call
to ui.interact()
.
ui.
ChoiceReturn
(label, value, location=None, block_all=None, sensitive=True, args=None, kwargs=None) linkA menu choice action that returns value, while managing the button state in a manner consistent with fixed rollback. (See block_all for a description of the behavior.)
If false, the button is given the selected role if it was the chosen choice, and insensitive if it was not selected.
If true, the button is always insensitive during fixed rollback.
If None, the value is taken from the config.fix_rollback_without_choice
variable.
When true is given to all items in a screen, it will
become unclickable (rolling forward will still work). This can
be changed by calling ui.saybehavior()
before the call
to ui.interact()
.
NoRollback
linkInstances of this class, and classes inheriting from this class, do not participate in rollback. Objects reachable through an instance of a NoRollback class only participate in rollback if they are reachable through other paths.
SlottedNoRollback
linkInstances of classes inheriting from this class do not participate
in rollback. The difference between this and NoRollback
is that
this class does not have an associated dictionary, hence can be used
with __slots__
to reduce memory usage.
Objects reachable through an instance of a NoRollback class only participate in rollback if they are reachable through other paths.
For example:
init python:
class MyClass(NoRollback):
def __init__(self):
self.value = 0
label start:
$ o = MyClass()
"Welcome!"
$ o.value += 1
"o.value is [o.value]. It will increase each time you rolllback and then click ahead."