License | BSD-3-Clause |
---|---|
Safe Haskell | Safe-Inferred |
Language | Haskell2010 |
Definition of the record holding all the game-related state, and various related utility functions.
Synopsis
- data ViewCenterRule
- = VCLocation (Cosmic Location)
- | VCRobot RID
- data REPLStatus
- data WinStatus
- = Ongoing
- | Won Bool
- | Unwinnable Bool
- data WinCondition
- data ObjectiveCompletion = ObjectiveCompletion {}
- _NoWinCondition :: Prism' WinCondition ()
- _WinConditions :: Prism' WinCondition (WinStatus, ObjectiveCompletion)
- newtype Announcement = ObjectiveCompleted Objective
- data RunStatus
- type Seed = Int
- data Step
- data SingleStep
- data GameState
- creativeMode :: Lens' GameState Bool
- gameStep :: Lens' GameState Step
- winCondition :: Lens' GameState WinCondition
- winSolution :: Lens' GameState (Maybe ProcessedTerm)
- gameAchievements :: Lens' GameState (Map GameplayAchievement Attainment)
- announcementQueue :: Lens' GameState (Seq Announcement)
- runStatus :: Lens' GameState RunStatus
- paused :: Getter GameState Bool
- robotMap :: Lens' GameState (IntMap Robot)
- robotsByLocation :: Lens' GameState (Map SubworldName (Map Location IntSet))
- robotsAtLocation :: Cosmic Location -> GameState -> [Robot]
- robotsWatching :: Lens' GameState (Map (Cosmic Location) (Set RID))
- robotsInArea :: Cosmic Location -> Int32 -> GameState -> [Robot]
- baseRobot :: Traversal' GameState Robot
- activeRobots :: Getter GameState IntSet
- waitingRobots :: Getter GameState (Map TickNumber [RID])
- availableRecipes :: Lens' GameState (Notifications (Recipe Entity))
- availableCommands :: Lens' GameState (Notifications Const)
- messageNotifications :: Getter GameState (Notifications LogEntry)
- allDiscoveredEntities :: Lens' GameState Inventory
- gensym :: Lens' GameState Int
- seed :: Lens' GameState Seed
- randGen :: Lens' GameState StdGen
- adjList :: Getter GameState (Array Int Text)
- nameList :: Getter GameState (Array Int Text)
- initiallyRunCode :: Lens' GameState (Maybe ProcessedTerm)
- entityMap :: Lens' GameState EntityMap
- recipesOut :: Lens' GameState (IntMap [Recipe Entity])
- recipesIn :: Lens' GameState (IntMap [Recipe Entity])
- recipesReq :: Lens' GameState (IntMap [Recipe Entity])
- currentScenarioPath :: Lens' GameState (Maybe FilePath)
- knownEntities :: Lens' GameState [Text]
- worldNavigation :: Lens' GameState (Navigation (Map SubworldName) Location)
- multiWorld :: Lens' GameState (MultiWorld Int Entity)
- worldScrollable :: Lens' GameState Bool
- viewCenterRule :: Lens' GameState ViewCenterRule
- viewCenter :: Getter GameState (Cosmic Location)
- needsRedraw :: Lens' GameState Bool
- replStatus :: Lens' GameState REPLStatus
- replNextValueIndex :: Lens' GameState Integer
- replWorking :: Getter GameState Bool
- replActiveType :: Getter REPLStatus (Maybe Polytype)
- inputHandler :: Lens' GameState (Maybe (Text, Value))
- messageQueue :: Lens' GameState (Seq LogEntry)
- lastSeenMessageTime :: Lens' GameState TickNumber
- focusedRobotID :: Getter GameState RID
- ticks :: Lens' GameState TickNumber
- robotStepsPerTick :: Lens' GameState Int
- data Notifications a = Notifications {
- _notificationsCount :: Int
- _notificationsContent :: [a]
- notificationsCount :: forall a. Lens' (Notifications a) Int
- notificationsContent :: forall a a. Lens (Notifications a) (Notifications a) [a] [a]
- type LaunchParams a = ParameterizableLaunchParams CodeToRun a
- type ValidatedLaunchParams = LaunchParams Identity
- data GameStateConfig = GameStateConfig {}
- initGameState :: GameStateConfig -> GameState
- scenarioToGameState :: Scenario -> ValidatedLaunchParams -> GameStateConfig -> IO GameState
- data CodeToRun = CodeToRun SolutionSource ProcessedTerm
- newtype Sha1 = Sha1 String
- data SolutionSource
- parseCodeFile :: (Has (Throw SystemFailure) sig m, Has (Lift IO) sig m) => FilePath -> m CodeToRun
- applyViewCenterRule :: ViewCenterRule -> IntMap Robot -> Maybe (Cosmic Location)
- recalcViewCenter :: GameState -> GameState
- modifyViewCenter :: (Cosmic Location -> Cosmic Location) -> GameState -> GameState
- viewingRegion :: GameState -> (Int32, Int32) -> Cosmic BoundsRectangle
- unfocus :: GameState -> GameState
- focusedRobot :: GameState -> Maybe Robot
- data RobotRange
- focusedRange :: GameState -> Maybe RobotRange
- clearFocusedRobotLogUpdated :: Has (State GameState) sig m => m ()
- addRobot :: Has (State GameState) sig m => Robot -> m ()
- addRobotToLocation :: Has (State GameState) sig m => RID -> Cosmic Location -> m ()
- addTRobot :: Has (State GameState) sig m => TRobot -> m Robot
- emitMessage :: Has (State GameState) sig m => LogEntry -> m ()
- wakeWatchingRobots :: Has (State GameState) sig m => Cosmic Location -> m ()
- sleepUntil :: Has (State GameState) sig m => RID -> TickNumber -> m ()
- sleepForever :: Has (State GameState) sig m => RID -> m ()
- wakeUpRobotsDoneSleeping :: Has (State GameState) sig m => m ()
- deleteRobot :: Has (State GameState) sig m => RID -> m ()
- removeRobotFromLocationMap :: Has (State GameState) sig m => Cosmic Location -> RID -> m ()
- activateRobot :: Has (State GameState) sig m => RID -> m ()
- toggleRunStatus :: RunStatus -> RunStatus
- messageIsRecent :: GameState -> LogEntry -> Bool
- messageIsFromNearby :: Cosmic Location -> LogEntry -> Bool
- getRunCodePath :: CodeToRun -> Maybe FilePath
Game state record and related types
data ViewCenterRule Source #
The ViewCenterRule
specifies how to determine the center of the
world viewport.
VCLocation (Cosmic Location) | The view should be centered on an absolute position. |
VCRobot RID | The view should be centered on a certain robot. |
Instances
data REPLStatus Source #
A data type to represent the current status of the REPL.
REPLDone (Maybe (Typed Value)) | The REPL is not doing anything actively at the moment. We persist the last value and its type though. INVARIANT: the Value stored here is not a VResult. |
REPLWorking (Typed (Maybe Value)) | A command entered at the REPL is currently being run. The
|
Instances
Ongoing | There are one or more objectives remaining that the player has not yet accomplished. |
Won Bool | The player has won. The boolean indicates whether they have already been congratulated. |
Unwinnable Bool | The player has completed certain "goals" that preclude (via negative prerequisites) the completion of all of the required goals. The boolean indicates whether they have already been informed. |
Instances
FromJSON WinStatus Source # | |
ToJSON WinStatus Source # | |
Defined in Swarm.Game.State | |
Generic WinStatus Source # | |
Show WinStatus Source # | |
type Rep WinStatus Source # | |
Defined in Swarm.Game.State type Rep WinStatus = D1 ('MetaData "WinStatus" "Swarm.Game.State" "swarm-0.4-ISnx5FXhZ2Y66vKOx5hQmE" 'False) (C1 ('MetaCons "Ongoing" 'PrefixI 'False) (U1 :: Type -> Type) :+: (C1 ('MetaCons "Won" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedStrict) (Rec0 Bool)) :+: C1 ('MetaCons "Unwinnable" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedStrict) (Rec0 Bool)))) |
data WinCondition Source #
NoWinCondition | There is no winning condition. |
WinConditions WinStatus ObjectiveCompletion | NOTE: It is possible to continue to achieve "optional" objectives even after the game has been won (or deemed unwinnable). |
Instances
data ObjectiveCompletion Source #
ObjectiveCompletion | |
|
Instances
_NoWinCondition :: Prism' WinCondition () Source #
newtype Announcement Source #
TODO: #1044 Could also add an ObjectiveFailed constructor...
Instances
ToJSON Announcement Source # | |
Defined in Swarm.Game.Scenario.Objective toJSON :: Announcement -> Value # toEncoding :: Announcement -> Encoding # toJSONList :: [Announcement] -> Value # toEncodingList :: [Announcement] -> Encoding # | |
Generic Announcement Source # | |
Defined in Swarm.Game.Scenario.Objective type Rep Announcement :: Type -> Type # from :: Announcement -> Rep Announcement x # to :: Rep Announcement x -> Announcement # | |
Show Announcement Source # | |
Defined in Swarm.Game.Scenario.Objective showsPrec :: Int -> Announcement -> ShowS # show :: Announcement -> String # showList :: [Announcement] -> ShowS # | |
type Rep Announcement Source # | |
Defined in Swarm.Game.Scenario.Objective type Rep Announcement = D1 ('MetaData "Announcement" "Swarm.Game.Scenario.Objective" "swarm-0.4-ISnx5FXhZ2Y66vKOx5hQmE" 'True) (C1 ('MetaCons "ObjectiveCompleted" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Objective))) |
A data type to keep track of the pause mode.
Running | The game is running. |
ManualPause | The user paused the game, and it should stay pause after visiting the help. |
AutoPause | The game got paused while visiting the help, and it should unpause after returning back to the game. |
Instances
FromJSON RunStatus Source # | |
ToJSON RunStatus Source # | |
Defined in Swarm.Game.State | |
Generic RunStatus Source # | |
Show RunStatus Source # | |
Eq RunStatus Source # | |
type Rep RunStatus Source # | |
Defined in Swarm.Game.State type Rep RunStatus = D1 ('MetaData "RunStatus" "Swarm.Game.State" "swarm-0.4-ISnx5FXhZ2Y66vKOx5hQmE" 'False) (C1 ('MetaCons "Running" 'PrefixI 'False) (U1 :: Type -> Type) :+: (C1 ('MetaCons "ManualPause" 'PrefixI 'False) (U1 :: Type -> Type) :+: C1 ('MetaCons "AutoPause" 'PrefixI 'False) (U1 :: Type -> Type))) |
Game step mode - we use the single step mode when debugging robot CESK
machine.
data SingleStep Source #
Type for remebering which robots will be run next in a robot step mode.
Once some robots have run, we need to store RID to know which ones should go next.
At SBefore
no robots were run yet, so it is safe to transition to and from WorldTick
.
tick ┌────────────────────────────────────┐ │ │ │ step │ │ ┌────┐ │ ▼ ▼ │ │ ┌───────┐ step ┌───────┴───┐ step ┌────┴─────┐ │SBefore├──────►│SSingle RID├──────►│SAfter RID│ └──┬────┘ └───────────┘ └────┬─────┘ │ ▲ player ▲ │ ▼ │ switch └───────────────────┘ ┌────┴────┐ view RID > oldRID │WorldTick│ └─────────┘
The main record holding the state for the game itself (as distinct from the UI). See the lenses below for access to its fields.
GameState fields
creativeMode :: Lens' GameState Bool Source #
Is the user in creative mode (i.e. able to do anything without restriction)?
winCondition :: Lens' GameState WinCondition Source #
How to determine whether the player has won.
winSolution :: Lens' GameState (Maybe ProcessedTerm) Source #
How to win (if possible). This is useful for automated testing and to show help to cheaters (or testers).
gameAchievements :: Lens' GameState (Map GameplayAchievement Attainment) Source #
Map of in-game achievements that were attained
announcementQueue :: Lens' GameState (Seq Announcement) Source #
A queue of global announcements. Note that this is distinct from the "messageQueue", which is for messages emitted by robots.
Note that we put the newest entry to the right.
robotMap :: Lens' GameState (IntMap Robot) Source #
All the robots that currently exist in the game, indexed by ID.
robotsByLocation :: Lens' GameState (Map SubworldName (Map Location IntSet)) Source #
The names of all robots that currently exist in the game, indexed by
location (which we need both for e.g. the Salvage
command as
well as for actually drawing the world). Unfortunately there is
no good way to automatically keep this up to date, since we don't
just want to completely rebuild it every time the robotMap
changes. Instead, we just make sure to update it every time the
location of a robot changes, or a robot is created or destroyed.
Fortunately, there are relatively few ways for these things to
happen.
robotsAtLocation :: Cosmic Location -> GameState -> [Robot] Source #
Get a list of all the robots at a particular location.
robotsWatching :: Lens' GameState (Map (Cosmic Location) (Set RID)) Source #
Get a list of all the robots that are "watching" by location.
robotsInArea :: Cosmic Location -> Int32 -> GameState -> [Robot] Source #
Get all the robots within a given Manhattan distance from a location.
activeRobots :: Getter GameState IntSet Source #
The names of the robots that are currently not sleeping.
waitingRobots :: Getter GameState (Map TickNumber [RID]) Source #
The names of the robots that are currently sleeping, indexed by wake up time. Note that this may not include all sleeping robots, particularly those that are only taking a short nap (e.g. wait 1).
availableRecipes :: Lens' GameState (Notifications (Recipe Entity)) Source #
The list of available recipes.
availableCommands :: Lens' GameState (Notifications Const) Source #
The list of available commands.
messageNotifications :: Getter GameState (Notifications LogEntry) Source #
Get the notification list of messages from the point of view of focused robot.
allDiscoveredEntities :: Lens' GameState Inventory Source #
The list of entities that have been discovered.
seed :: Lens' GameState Seed Source #
The initial seed that was used for the random number generator, and world generation.
adjList :: Getter GameState (Array Int Text) Source #
Read-only list of words, for use in building random robot names.
nameList :: Getter GameState (Array Int Text) Source #
Read-only list of words, for use in building random robot names.
initiallyRunCode :: Lens' GameState (Maybe ProcessedTerm) Source #
Code that is run upon scenario start, before any REPL interaction.
entityMap :: Lens' GameState EntityMap Source #
The catalog of all entities that the game knows about.
recipesOut :: Lens' GameState (IntMap [Recipe Entity]) Source #
All recipes the game knows about, indexed by outputs.
recipesIn :: Lens' GameState (IntMap [Recipe Entity]) Source #
All recipes the game knows about, indexed by inputs.
recipesReq :: Lens' GameState (IntMap [Recipe Entity]) Source #
All recipes the game knows about, indexed by requirement/catalyst.
currentScenarioPath :: Lens' GameState (Maybe FilePath) Source #
The filepath of the currently running scenario.
This is useful as an index to scenarios
collection,
see scenarioItemByPath
.
knownEntities :: Lens' GameState [Text] Source #
The names of entities that should be considered "known", that is, robots know what they are without having to scan them.
worldNavigation :: Lens' GameState (Navigation (Map SubworldName) Location) Source #
Includes a Map
of named locations and an
"Edge list" (graph) that maps portal entrances to exits
multiWorld :: Lens' GameState (MultiWorld Int Entity) Source #
The current state of the world (terrain and entities only; robots
are stored in the robotMap
). Int
is used instead of
TerrainType
because we need to be able to store terrain values in
unboxed tile arrays.
worldScrollable :: Lens' GameState Bool Source #
Whether the world map is supposed to be scrollable or not.
viewCenterRule :: Lens' GameState ViewCenterRule Source #
The current rule for determining the center of the world view. It updates also, viewCenter and focusedRobotName to keep everything synchronize.
viewCenter :: Getter GameState (Cosmic Location) Source #
The current center of the world view. Note that this cannot be
modified directly, since it is calculated automatically from the
viewCenterRule
. To modify the view center, either set the
viewCenterRule
, or use modifyViewCenter
.
replStatus :: Lens' GameState REPLStatus Source #
The current status of the REPL.
replActiveType :: Getter REPLStatus (Maybe Polytype) Source #
Either the type of the command being executed, or of the last command
inputHandler :: Lens' GameState (Maybe (Text, Value)) Source #
The currently installed input handler and hint text.
messageQueue :: Lens' GameState (Seq LogEntry) Source #
A queue of global messages.
Note that we put the newest entry to the right.
lastSeenMessageTime :: Lens' GameState TickNumber Source #
Last time message queue has been viewed (used for notification).
focusedRobotID :: Getter GameState RID Source #
The current robot in focus.
It is only a Getter
because this value should be updated only when
the viewCenterRule
is specified to be a robot.
Technically it's the last robot ID specified by viewCenterRule
,
but that robot may not be alive anymore - to be safe use focusedRobot
.
robotStepsPerTick :: Lens' GameState Int Source #
The maximum number of CESK machine steps a robot may take during a single tick.
Notifications
data Notifications a Source #
A data type to keep track of discovered recipes and commands
Instances
notificationsCount :: forall a. Lens' (Notifications a) Int Source #
notificationsContent :: forall a a. Lens (Notifications a) (Notifications a) [a] [a] Source #
Launch parameters
type LaunchParams a = ParameterizableLaunchParams CodeToRun a Source #
type ValidatedLaunchParams = LaunchParams Identity Source #
In this stage in the UI pipeline, both fields have already been validated, and Nothing means that the field is simply absent.
GameState initialization
data GameStateConfig Source #
Record to pass information needed to create an initial
GameState
record when starting a scenario.
GameStateConfig | |
|
initGameState :: GameStateConfig -> GameState Source #
Create an initial, fresh game state record when starting a new scenario.
scenarioToGameState :: Scenario -> ValidatedLaunchParams -> GameStateConfig -> IO GameState Source #
Create an initial game state corresponding to the given scenario.
data SolutionSource Source #
ScenarioSuggested | |
PlayerAuthored FilePath Sha1 | Includes the SHA1 of the program text for the purpose of corroborating solutions on a leaderboard. |
parseCodeFile :: (Has (Throw SystemFailure) sig m, Has (Lift IO) sig m) => FilePath -> m CodeToRun Source #
Utilities
applyViewCenterRule :: ViewCenterRule -> IntMap Robot -> Maybe (Cosmic Location) Source #
Given a current mapping from robot names to robots, apply a
ViewCenterRule
to derive the location it refers to. The result
is Maybe
because the rule may refer to a robot which does not
exist.
recalcViewCenter :: GameState -> GameState Source #
Recalculate the veiw center (and cache the result in the
viewCenter
field) based on the current viewCenterRule
. If
the viewCenterRule
specifies a robot which does not exist,
simply leave the current viewCenter
as it is. Set needsRedraw
if the view center changes.
modifyViewCenter :: (Cosmic Location -> Cosmic Location) -> GameState -> GameState Source #
Modify the viewCenter
by applying an arbitrary function to the
current value. Note that this also modifies the viewCenterRule
to match. After calling this function the viewCenterRule
will
specify a particular location, not a robot.
viewingRegion :: GameState -> (Int32, Int32) -> Cosmic BoundsRectangle Source #
Given a width and height, compute the region, centered on the
viewCenter
, that should currently be in view.
unfocus :: GameState -> GameState Source #
Unfocus by modifying the view center rule to look at the current location instead of a specific robot, and also set the focused robot ID to an invalid value. In classic mode this causes the map view to become nothing but static.
focusedRobot :: GameState -> Maybe Robot Source #
Find out which robot has been last specified by the
viewCenterRule
, if any.
data RobotRange Source #
Type for describing how far away a robot is from the base, which determines what kind of communication can take place.
Close | Close; communication is perfect. |
MidRange Double | Mid-range; communication is possible but lossy. |
Far | Far; communication is not possible. |
Instances
Eq RobotRange Source # | |
Defined in Swarm.Game.State (==) :: RobotRange -> RobotRange -> Bool # (/=) :: RobotRange -> RobotRange -> Bool # | |
Ord RobotRange Source # | |
Defined in Swarm.Game.State compare :: RobotRange -> RobotRange -> Ordering # (<) :: RobotRange -> RobotRange -> Bool # (<=) :: RobotRange -> RobotRange -> Bool # (>) :: RobotRange -> RobotRange -> Bool # (>=) :: RobotRange -> RobotRange -> Bool # max :: RobotRange -> RobotRange -> RobotRange # min :: RobotRange -> RobotRange -> RobotRange # |
focusedRange :: GameState -> Maybe RobotRange Source #
Check how far away the focused robot is from the base. Nothing
is returned if there is no focused robot; otherwise, return a
RobotRange
value as follows.
- If we are in creative or scroll-enabled mode, the focused robot is
always considered
Close
. - Otherwise, there is a "minimum radius" and "maximum radius".
- If the robot is within the minimum radius, it is
Close
. - If the robot is between the minimum and maximum radii, it
is
MidRange
, with aDouble
value ranging linearly from 0 to 1 proportional to the distance from the minimum to maximum radius. For example, 'MidRange 0.5' would indicate a robot exactly halfway between the minimum and maximum radii. - If the robot is beyond the maximum radius, it is
Far
. - By default, the minimum radius is 16, and maximum is 64.
- If the focused robot has an
antenna
installed, it doubles both radii. - If the base has an
antenna
installed, it also doubles both radii.
clearFocusedRobotLogUpdated :: Has (State GameState) sig m => m () Source #
Clear the robotLogUpdated
flag of the focused robot.
addRobot :: Has (State GameState) sig m => Robot -> m () Source #
Add a robot to the game state, adding it to the main robot map, the active robot set, and to to the index of robots by location.
addRobotToLocation :: Has (State GameState) sig m => RID -> Cosmic Location -> m () Source #
Helper function for updating the "robotsByLocation" bookkeeping
addTRobot :: Has (State GameState) sig m => TRobot -> m Robot Source #
Add a concrete instance of a robot template to the game state: first, generate a unique ID number for it. Then, add it to the main robot map, the active robot set, and to to the index of robots by location. Return the updated robot.
emitMessage :: Has (State GameState) sig m => LogEntry -> m () Source #
Add a message to the message queue.
wakeWatchingRobots :: Has (State GameState) sig m => Cosmic Location -> m () Source #
Iterates through all of the currently "wait"-ing robots, and moves forward the wake time of the ones that are watching this location.
NOTE: Clearing TickNumber map entries from "internalWaitingRobots" upon wakeup is handled by "wakeUpRobotsDoneSleeping" in State.hs
sleepUntil :: Has (State GameState) sig m => RID -> TickNumber -> m () Source #
Takes a robot out of the activeRobots set and puts it in the waitingRobots queue.
sleepForever :: Has (State GameState) sig m => RID -> m () Source #
Takes a robot out of the activeRobots set.
wakeUpRobotsDoneSleeping :: Has (State GameState) sig m => m () Source #
Removes robots whose wake up time matches the current game ticks count from the waitingRobots queue and put them back in the activeRobots set if they still exist in the keys of robotMap.
removeRobotFromLocationMap :: Has (State GameState) sig m => Cosmic Location -> RID -> m () Source #
Makes sure empty sets don't hang around in the
robotsByLocation
map. We don't want a key with an
empty set at every location any robot has ever
visited!
activateRobot :: Has (State GameState) sig m => RID -> m () Source #
Adds a robot to the activeRobots set.
toggleRunStatus :: RunStatus -> RunStatus Source #
Switch (auto or manually) paused game to running and running to manually paused.
Note that this function is not safe to use in the app directly, because the UI
also tracks time between ticks - use safeTogglePause
instead.