CPEngine

org.cosplay.CPEngine$
object CPEngine

CosPlay game engine.

Game engine is used mostly for game lifecycle like starting and stopping as well as debugging, logging, and managing global utility and miscellaneous features.

CosPlay games follow relatively straightforward game organization:

Note that these methods have two versions:

  • One that throws CPException exception in case of any errors for the classic exception-based error handling.
  • Another with Eff suffix in the name that returns scala.util.Try-monad allowing for composable effect-based error handling.

You can use either approach but you can't mix them up. Effect-based approach, however, forces a more rigorous error handling requiring to handle errors at each call.

CosPlay game organization using classic exception-based error handling:

import org.cosplay.*

object Game:
  def main(args: Array[String]): Unit =
      // Initialize the engine.
      CPEngine.init(
           CPGameInfo(name = "My Game"),
           System.console() == null || args.contains("emuterm")
      )

      // Create game scenes & their scene objects.
      val sc1 = new CPScene(...)
      val sc2 = new CPScene(...)

      // Start the game & wait for exit.
      try CPEngine.startGame(sc1, sc2)
      finally CPEngine.dispose()

      sys.exit(0)

Here's the same game structure using effect-based error handling (calling sys.exit() with an appropriate exit code at each step):

import org.cosplay.*

object Game:
  def main(args: Array[String]): Unit =
      // Initialize the engine.
      CPEngine.initEff(
           CPGameInfo(name = "My Game"),
           System.console() == null || args.contains("emuterm")
      ).recover(_ => sys.exit(1)).get

      // Create game scenes & their scene objects.
      val sc1 = new CPScene(...)
      val sc2 = new CPScene(...)

      // Start the game & wait for exit.
      CPEngine.startGameEff(sc1, sc2).recover(_ => sys.exit(2)).get

      // Dispose game engine.
      CPEngine.disposeEff().fold(_ => sys.exit(3), _ => sys.exit(0))

Notes:

  • Game start in a standard Scala way. It is recommended to use main(...) function for better compatibility.
  • Create CPGameInfo object that describes the game and its properties.
  • Initialize game engine by calling CPEngine.init/CPEngine.initEff method passing it game descriptor and terminal emulation flag.
  • Create all necessary scenes, scene objects and assets. You can organize these objects in any desirable way - CosPlay does not impose any restrictions or limitation on how it is should be done. Note also that scene and scene objects can be added, removed or modified later throughout the game lifecycle.
  • Once you have all initially required scenes constructed - you can start the game by calling one of the CPEngine.startGame/CPEngine.startGameEff methods.
  • Make sure to call CPEngine.dispose/CPEngine.disposeEff method upon exit from CPEngine.startGame/CPEngine.startGameEff method.

Extensions and Shortcuts

Throughout the CosPlay code, exampled and built-in games there are several extensions and syntactic shortcuts used to simplify frequently used code idioms:

Shortcut Replaced By
x.? Option(x)
x.seq Seq(x)
val x = nil[Int] val x: List[Int] = Nil
val x = none[Int] val x: Option[Int] = None

These extensions are introduced in the global scope and can be used by any code that is using CosPlay.

System Properties

CosPlay game engine supports the following system properties that control various aspects of its operation. Note that these properties must be set before method CPEngine.init/CPEngine.initEff is called:

System Property Value Type Description
COSPLAY_GAME_ID String Internal unique game ID.
COSPLAY_EMUTERM_FONT_NAME String Applies to the built-in terminal emulator only. Specifies the font name to use.
COSPLAY_EMUTERM_FONT_SIZE Int Applies to the built-in terminal emulator only. Specifies the font size to use.
COSPLAY_EMUTERM_CH_WIDTH_OFFSET Int Applies to the built-in terminal emulator only. Specifies character width offset. Can be positive or negative. Default is zero.
COSPLAY_EMUTERM_CH_HEIGHT_OFFSET Int Applies to the built-in terminal emulator only. Specifies character height offset. Can be positive or negative. Default is zero.
COSPLAY_EMUTERM_ANTIALIAS Applies to the built-in terminal emulator only. If system property is present - the font rendering will use antialiasing. By default, no antialiasing is used.
COSPLAY_FORCE_8BIT_COLOR Boolean Forces the automatic conversion from 24-bit color to 8-bit color. Only needed when running in the native terminal that does not support 24-bit color. Default value is false.
COSPLAY_TERM_CLASSNAME String Fully qualified class name for the custom terminal emulator implementation. Class must implement org.cosplay.CPTerminal trait.

Reserved Keyboard Keys

There are three reserved key strokes that are used by the game engine itself and therefore NOT available to the game. These keystrokes are intercepted before frame update and not propagated to the scene object context:

  • 'CTRL+Q' - toggles in-game FPS overlay (see CPEngine.enableCtrlFps method)
  • 'CTRL+L' - opens GUI-based loc viewer & debugger (see CPEngine.enableCtrlLog method)
  • 'F12' - saves current frame screenshot as *.xp image to the current working folder.

Attributes

Note

See developer guide at https://cosplayengine.com

Example

See all examples under org.cosplay.examples package. Each example has a complete demonstration of working with game engine including initialization and game start.

Source
CPEngine.scala
Graph
Supertypes
class Object
trait Matchable
class Any
Self type
CPEngine.type

Members list

Value members

Concrete methods

def addInput(in: CPInput): Unit

Adds external input devices.

Adds external input devices.

Value parameters

in

External input device to add.

Attributes

Source
CPEngine.scala

Adds the rendering stats listener.

Adds the rendering stats listener.

Value parameters

f

Listener to add.

Attributes

Source
CPEngine.scala
def debugStep(kbKey: Option[CPKeyboardKey]): Unit

Debug steps through the game on frame at a time. Note that the game must be paused. Engine must be initialized before this call otherwise exception is thrown.

Debug steps through the game on frame at a time. Note that the game must be paused. Engine must be initialized before this call otherwise exception is thrown.

Value parameters

kbKey

Optional keyboard key event to emulate for this debug step. If provided, the real keyboard event, if any, will be ignored.

Attributes

Source
CPEngine.scala
def dispose(): Unit

Disposes the game engine. This method must be called upon exit from the startGame method. Engine must be initialized before this call otherwise exception is thrown.

Disposes the game engine. This method must be called upon exit from the startGame method. Engine must be initialized before this call otherwise exception is thrown.

Attributes

See also
Source
CPEngine.scala
def disposeEff(): Try[Unit]

Disposes the game engine. This method must be called upon exit from the startGameEff method. Engine must be initialized before this call otherwise exception is thrown. Effect-based version of dispose method allowing end-user to use pattern matching for error handling. This method does not throw any exceptions.

Disposes the game engine. This method must be called upon exit from the startGameEff method. Engine must be initialized before this call otherwise exception is thrown. Effect-based version of dispose method allowing end-user to use pattern matching for error handling. This method does not throw any exceptions.

Attributes

Returns

Try-monad.

See also
Source
CPEngine.scala
def enableCtrlFps(f: Boolean): Unit

Enables or disables opening built-in FPS window by pressing 'Ctrl-q'. Production games may want to disable that capability. Default value is true.

Enables or disables opening built-in FPS window by pressing 'Ctrl-q'. Production games may want to disable that capability. Default value is true.

Value parameters

f

Whether to enable or disable opening built-in FPS window by pressing 'Ctrl-q'.

Attributes

Source
CPEngine.scala
def enableCtrlLog(f: Boolean): Unit

Enables or disables opening the GUI-based debugger log by pressing 'Ctrl-l'. Production games may want to disable that capability. Default value is true.

Enables or disables opening the GUI-based debugger log by pressing 'Ctrl-l'. Production games may want to disable that capability. Default value is true.

Value parameters

f

Whether to enable or disable opening the GUI-based debugger log by pressing 'Ctrl-l'.

Attributes

Source
CPEngine.scala
def exitGame(): Unit

Exits the game. Calling this method will cause startGame or startGameEff method to exit on the next frame. Note that this method can only be called from a thread different from the one used to call startGame or startGameEff method. If the game wasn't started yet, this method is a no-op. Engine must be initialized before this call otherwise exception is thrown.

Exits the game. Calling this method will cause startGame or startGameEff method to exit on the next frame. Note that this method can only be called from a thread different from the one used to call startGame or startGameEff method. If the game wasn't started yet, this method is a no-op. Engine must be initialized before this call otherwise exception is thrown.

Attributes

Source
CPEngine.scala

Gets the game information supplied to init method.

Gets the game information supplied to init method.

Attributes

Source
CPEngine.scala

Gets current rendering statistics, if available.

Gets current rendering statistics, if available.

Attributes

See also
Source
CPEngine.scala
def homeFile(path: String): Try[File]

Creates file with given relative path in the engine's special, system-specific, game-specific root location. The actual absolute path of the returned file is OS-dependent and shouldn't be relied on or used.

Creates file with given relative path in the engine's special, system-specific, game-specific root location. The actual absolute path of the returned file is OS-dependent and shouldn't be relied on or used.

Value parameters

path

Relative path of the file. Path may include sub-directories and should use Unix style '/' for path separator.

Attributes

Source
CPEngine.scala
def init(gameInfo: CPGameInfo, emuTerm: Boolean): Unit

Initializes the game engine.

Initializes the game engine.

Value parameters

emuTerm

Whether or not to use built-in terminal emulator. If not provided, the default value will be result of this expression:

System.console() == null
gameInfo

Game information.

Attributes

Throws
CPException

Thrown in case of any errors.

See also
Source
CPEngine.scala
def initEff(gameInfo: CPGameInfo, emuTerm: Boolean): Try[Unit]

Initializes the game engine. Effect-based version of init method allowing end-user to use pattern matching for error handling. This method does not throw any exceptions.

Initializes the game engine. Effect-based version of init method allowing end-user to use pattern matching for error handling. This method does not throw any exceptions.

Value parameters

emuTerm

Whether or not to use built-in terminal emulator. If not provided, the default value will be result of this expression:

System.console() == null
gameInfo

Game information.

Attributes

Returns

Try-monad.

See also
Source
CPEngine.scala
def isCtrlFps: Boolean

Checks whether or not opening built-in FPS window pressing 'Ctrl-q' is enabled. Default value is true.

Checks whether or not opening built-in FPS window pressing 'Ctrl-q' is enabled. Default value is true.

Attributes

Source
CPEngine.scala
def isCtrlLog: Boolean

Checks whether or not opening the GUI-based debugger log by pressing 'Ctrl-l' is enabled. Default value is true.

Checks whether or not opening the GUI-based debugger log by pressing 'Ctrl-l' is enabled. Default value is true.

Attributes

Source
CPEngine.scala
def isGamePaused: Boolean

Tests whether or not the game is paused. Engine must be initialized before this call otherwise exception is thrown.

Tests whether or not the game is paused. Engine must be initialized before this call otherwise exception is thrown.

Attributes

Source
CPEngine.scala
def isInit: Boolean

Returns whether or not game engine is initialized.

Returns whether or not game engine is initialized.

Attributes

Source
CPEngine.scala
def openLog(): Unit

Opens GUI-based log window by bringing it upfront. Can also be open by pressing Ctrl-l in the game. Engine must be initialized before this call otherwise exception is thrown.

Opens GUI-based log window by bringing it upfront. Can also be open by pressing Ctrl-l in the game. Engine must be initialized before this call otherwise exception is thrown.

Attributes

See also
Source
CPEngine.scala
def pauseGame(): Unit

Pauses the game. Engine must be initialized before this call otherwise exception is thrown.

Pauses the game. Engine must be initialized before this call otherwise exception is thrown.

Attributes

Source
CPEngine.scala
def removeInput(in: CPInput): Unit

Removes external input devices.

Removes external input devices.

Value parameters

in

External input device to remove.

Attributes

Source
CPEngine.scala

Removes the rendering stats listener.

Removes the rendering stats listener.

Value parameters

f

Listener to remove.

Attributes

Source
CPEngine.scala
def resumeGame(): Unit

Resumes the game. Engine must be initialized before this call otherwise exception is thrown.

Resumes the game. Engine must be initialized before this call otherwise exception is thrown.

Attributes

Source
CPEngine.scala
def rootLog(): CPLog

Gets root log for the game engine.

Gets root log for the game engine.

NOTE: unlike most other methods in the game engine, you can use this method before engine is initialized. In such case the log entries will be buffered until the engine is initialized.

Attributes

Source
CPEngine.scala
def sendMessage(id: String, msgs: AnyRef*): Unit

Sends direct message(s) to the scene object of the currently playing scene. Note that to exchange data between scenes you should use game cache. Sent messages will be available to the recipient scene objects starting with the next frame. Messages will be stored until they are retrieved or the scene is changed.

Sends direct message(s) to the scene object of the currently playing scene. Note that to exchange data between scenes you should use game cache. Sent messages will be available to the recipient scene objects starting with the next frame. Messages will be stored until they are retrieved or the scene is changed.

Although this method looks identical to CPSceneObjectContext.sendMessage method, it allows to send messages to the scene objects from outside of the game loop.

Value parameters

id

Scene object ID from the current scene.

msgs

Messages to send.

Attributes

See also
Source
CPEngine.scala
def showFpsOverlay(show: Boolean): Unit

Shows or hides the built-in FPS overlay in the right top corner. Can also be turned on or off by pressing Ctrl-q in the game. Engine must be initialized before this call otherwise exception is thrown.

Shows or hides the built-in FPS overlay in the right top corner. Can also be turned on or off by pressing Ctrl-q in the game. Engine must be initialized before this call otherwise exception is thrown.

Value parameters

show

Show/hide built-in FPS flag.

Attributes

See also
Source
CPEngine.scala
def startDebug(): Unit

Shortcut for the following two calls:

Shortcut for the following two calls:

   pauseGame()
   openLog()

This is a convenient call to programmatically start the debugging session. Engine must be initialized before this call otherwise exception is thrown.

Attributes

Source
CPEngine.scala
def startGame(scs: CPScene*): Unit

Starts the game. Games start with the first scene in the list. Engine must be initialized before this call otherwise exception is thrown.

Starts the game. Games start with the first scene in the list. Engine must be initialized before this call otherwise exception is thrown.

Value parameters

scs

Non-empty set of scene comprising the game. Note that scenes can be dynamically added or removed.

Attributes

Throws
CPException

Thrown in case of any errors.

See also
Source
CPEngine.scala
def startGame(startSc: String, scs: CPScene*): Unit

Starts the game. Games start with the given start scene. Engine must be initialized before this call otherwise exception is thrown.

Starts the game. Games start with the given start scene. Engine must be initialized before this call otherwise exception is thrown.

Value parameters

scs

Non-empty set of scene comprising the game. Note that scenes can be dynamically added or removed.

startSc

ID of the scene to start the game with.

Attributes

Throws
CPException

Thrown in case of any errors.

See also
Source
CPEngine.scala
def startGameEff(scs: CPScene*): Try[Unit]

This is effect-based version of startGame method allowing end-user to use pattern matching for error handling. Starts the game. Games start with the first scene in the list. Engine must be initialized before this call otherwise exception is thrown. This method does not throw any exceptions.

This is effect-based version of startGame method allowing end-user to use pattern matching for error handling. Starts the game. Games start with the first scene in the list. Engine must be initialized before this call otherwise exception is thrown. This method does not throw any exceptions.

Value parameters

scs

Non-empty set of scene comprising the game. Note that scenes can be dynamically added or removed.

Attributes

See also
Source
CPEngine.scala
def startGameEff(startSc: String, scs: CPScene*): Try[Unit]

This is effect-based version of startGame method allowing end-user to use pattern matching for error handling. Starts the game. Games start with the given start scene ID. Engine must be initialized before this call otherwise exception is thrown. This method does not throw any exceptions.

This is effect-based version of startGame method allowing end-user to use pattern matching for error handling. Starts the game. Games start with the given start scene ID. Engine must be initialized before this call otherwise exception is thrown. This method does not throw any exceptions.

Value parameters

scs

Non-empty set of scene comprising the game. Note that scenes can be dynamically added or removed.

startSc

ID of the scene to start the game with.

Attributes

See also
Source
CPEngine.scala
def tempFile(): Try[File]

Creates file in the engine's special, system-specific, temporary file location. The actual absolute path of the returned file is OS-dependent and shouldn't be relied on or used. Returned file wil be automatically deleted upon exiting the game engine.

Creates file in the engine's special, system-specific, temporary file location. The actual absolute path of the returned file is OS-dependent and shouldn't be relied on or used. Returned file wil be automatically deleted upon exiting the game engine.

Attributes

Source
CPEngine.scala

Concrete fields

val fps: Int

Target FPS of the game engine. If the actual frame rate exceeds this value the game engine will throttle the execution and release spare cycle to the user logic. Default value is 30.

Target FPS of the game engine. If the actual frame rate exceeds this value the game engine will throttle the execution and release spare cycle to the user logic. Default value is 30.

Attributes

Source
CPEngine.scala
val frameMicros: Long

Microseconds per frame assuming target FPS.

Microseconds per frame assuming target FPS.

Attributes

Source
CPEngine.scala
val frameMillis: Long

Milliseconds per frame assuming target FPS.

Milliseconds per frame assuming target FPS.

Attributes

Source
CPEngine.scala
val frameNanos: Long

Nanoseconds per frame assuming target FPS.

Nanoseconds per frame assuming target FPS.

Attributes

Source
CPEngine.scala