-
Notifications
You must be signed in to change notification settings - Fork 26
Match API Object
This represents an instance of a running game, including all the moves that have been played to reach the current state.
| Method | Description |
|---|---|
userTurn() |
Requests the user to enter a move |
abortUserTurn() |
Aborts a previous call to userTurn(), causing this pending call to fail |
machineSearch() |
Requests the best move from the artificial intelligence |
abortMachineSearch() |
Aborts a previous call to machineSearch(), causing this pending call to fail |
playMove() |
Applies a move to the match, running visual animations if any |
applyMove() |
Applies a move to the match, without running visual animations |
attachElement() |
Provides a user interface to the match through the given DOM element |
detachElement() |
Detaches the match from a previously attached element |
setViewOptions() |
Sets the options of the user interface |
getViewOptions() |
Returns the options of the user interface |
getFinished() |
Returns the current game ending status of the match |
getTurn() |
Returns who is the player to play next move |
getMoveString() |
Returns a game-normalized string representing the given move |
rollback() |
Changes the match state to a previous situation |
save() |
Returns a string that represents the exact state of the match |
load() |
Sets the state of the match from a previous save |
pickMove() |
Returns the Jocly move best matching the given string |
otherPlayer() |
Returns the player other than the one as input |
getPlayedMoves() |
Returns the moves played in the match |
getPossibleMoves() |
Returns the moves that could currently be played |
getConfig() |
Returns the game static configuration |
viewAs() |
Changes the player perspective of the board view |
viewControl() |
Runs various secondary view features |
resetView() |
Stop animations in progress and redisplay the board if necessary |
getBoardState() |
Returns a representation of the current state of the board |
getInitialBoardState() |
Returns a representation of the initial state of the board |
Requests the user to enter a move.
On completion, this method returns an object with the properties:
-
move: the played move under the form of a javascript object. You should not try to interpret the properties in this object as they are completely dependant game implementation -
finished,winner: as described ingetFinished()
Once this method resolves, the move has been applied to the match and saved in the list of played moves.
Example:
match.userTurn()
.then( (result) => {
if(!result.finished)
// play next move
})Aborts a previous call to userTurn(), causing this pending call to fail.
-
failOnNotUserTurn: normally, if you callabortUserTurn()while there is no user input in progress, the call resolves silently. IffailOnNotUserTurnis set totrue, the call is rejected.
Generally, there is no need to call this method since the actual user turn ends when the user completes the input. However, the function may be used in case for instance the user ran out of time.
On completion, this method does not return any value.
Example:
var timer = setTimeout( () => {
match.abortUserTurn();
}, 5000)
match.userTurn()
.then( (result) => {
clearTimeout(timer);
// ...
})
.catch( (error) => {
// error should be "Aborted"
})Requests the best move from the artificial intelligence.
-
options: an optional javascript object with properties:-
level: an object describing the parameter for the machine level. By default, it is the first level defined in the game model configuration -
threaded: a boolean indicating whether the artificial should run in a separate thread (javascript Worker). This parameter is ignored on node.js
-
On completion, this method returns an object with the same properties as the ones from userTurn().
Once this method resolves, the move has not been applied to the match, in fact the match state has not changed. You need to call either playMove() or applyMove().
Example:
match.machineSearch()
.then ( (result) => {
match.playMove(result.move)
.then( () => {
if(!result.finished) {
// proceed to next move
}
})
})Aborts a previous call to machineSearch(), causing this pending call to fail.
-
failOnNotMachineSearch: normally, if you callabortMachineSearch()while there is no machine searching in progress, the call resolves silently. IffailOnNotMachineSearchis set totrue, the call is rejected.
One reason for aborting a machine search is for instance to change the artificial intelligence level. Since a given Match object can only run a single machine search at once, the previous search must be aborted before starting a new search.
On completion, this method does not return any value.
Example:
var timer = setTimeout( () => {
// abort the engine search if it did resolve within 1 second
match.abortMachineSearch();
}, 1000)
match.machineSearch()
.then( (result) => {
clearTimeout(timer);
// ...
})
.catch( (error) => {
// error should be "Aborted"
})Applies a move to the match, running visual animations if any.
-
move: the move to be played
The method runs animations that may have been defined in the game implementation before resolving. If the move is not valid, the method rejects the returned promise.
Returns a javascript object describing the outcome of the move:
-
finished,winner: as described ingetFinished()
Example:
match.machineSearch()
.then ( (result) => {
match.playMove(result.move)
.then( (result2) => {
if(!result2.finished) {
// proceed to next move
}
})
})Applies a move to the match, without running visual animations.
-
move: the move to be played
The method does not run animations that may have been defined in the game implementation before resolving. If the move is not valid, the method rejects the returned promise.
Returns a javascript object describing the outcome of the move:
-
finished,winner: as described ingetFinished()
Example:
match.machineSearch()
.then ( (result) => {
match.applyMove(result.move)
.then( (result2) => {
if(!result2.finished) {
// proceed to next move
}
})
})Provides a user interface to the match through the given DOM element.
-
element: a DOM element (like aDIV) to attach the game to -
options: an optional object with properties:-
viewOptions: an optional object, as specified insetViewOptions()
-
When a match has just been created from [[Jocly.createMatch()|Jocly API Object#createMatch]], it does not provide any user interface. attachElement() must be used to display the board and accept user input. Only one element can be attached to a match. When used from node.js, this method fails.
Example:
Jocly.createMatch('classic-chess',(match) => {
var element = document.getElementById("game-area");
match.attachElement(element)
.then( () => {
// proceed with playing the game
})
})Detaches the match from a previously attached element.
The initial state of the element is restored. This method fails when used from node.js.
Example:
// attach the match to an element
match.detachElement()
.then( () => {
})Sets the options of the user interface.
-
options: a javascript object with properties:-
skin: the name of the view skin (as defined in the game view configuration) -
notation: boolean, should notation appear on the board (if supported by the game implementation) -
showMoves: boolean, during user input, should possible moves displayed (if supported by the game implementation) -
sounds: boolean, should sounds be played (if supported by the game implementation) -
autoComplete: boolean, should moves automatically be completed during the user input if there is no choice left (if supported by the game implementation). Note that at least one user action (click) is required -
anaglyph: boolean, should the board be displayed in anaglyph mode (requires red/cyan glasses to view). This only works for 3D skins -
viewAs: eitherJocly.PLAYER_AorJocly.PLAYER_B, which side the board is to be viewed from
-
Only the parameters specified in options are updated. If the match is not attached to an element, the method fails. setViewOptions is not supported on node.js.
Example:
match.setViewOptions({
skin: "skin3d",
sounds: false
})
.then( () => {
})Returns the options of the user interface.
-
options: seesetViewOptions()for details onoptionsproperties. Some options may not be supported by a particular game implementation, for instanceautoComplete, in this case, the property is not present in the object returned fromgetViewOptions()
If the match is not attached to an element, the method fails. setViewOptions is not supported on node.js.
Example:
match.getViewOptions()
.then( (options) => {
console.info("View options:",options);
})Returns the current game ending status of the match.
The returned object has properties:
-
finished: a boolean indicating whether this move ended the game -
winner: in casefinishedistrue, this property indicates who won:-
Jocly.PLAYER_A: player A (the first player in the game, i.e White in Chess) -
Jocly.PLAYER_B: player B (the second player, i.e Black in Chess) -
Jocly.DRAW: draw
-
Example:
match.getFinished()
.then( (result) => {
if(result.finished) {
if(result.winner == Jocly.PLAYER_A)
alert("A wins");
else if(result.winner == Jocly.PLAYER_B)
alert("B wins");
else if(result.winner == Jocly.DRAW)
alert("Draw");
}
})Returns who is the player to play next move.
The returned value can be:
-
Jocly.PLAYER_A: next move must come from player A (i.e the user who made the first move in the match, e.g White at Chess) -
Jocly.PLAYER_B: next move must come from player B (i.e the user who made the second move in the match, e.g Black at Chess)
Example:
match.getTurn()
.then( (who) => {
if(who==1) {
// get move from player A
} else {
// get move from player B
}
})Returns a game-normalized string representing the given move.
-
move: a javascript object representing a Jocly move, or an array containing move objects -
format: a game-dependent optional string defining the desired format
Jocly moves returned by userTurn() or machineSearch() are obscure objects, i.e their properties are game-dependant and should not be interpreted with the application. But many games have their own move notation, e.g in Chess, e2-e4 means King's pawn moves 2 square ahead). The getMoveString() returns the game-normalized string value given a Jocly move object.
If the input parameter is an array of move objects, the return is an array of string-transformed moves transformed.
Example:
match.machineSearch()
.then( (result) => {
match.getMoveString(result.move)
.then( (moveString) => {
console.info("Computer plays",moveString);
})
})
});Changes the match state to a previous situation.
-
index: an integer specifying a previous state. Ifindexis positive (including 0), it represents the number of moves since the beginning of the match,0represents the initial state. If negative,indexis the number of moves to step back, e.i-1steps back 1 move prior to the current state
If the match is attached to an element, the user interface will display the new state of the board.
Example:
match.rollback(-1)
.then( () => {
// we just cancelled the last move
});Returns a string that represents the exact state of the match.
The returned string can be saved for a future call to load().
Example:
match.save()
.then( (matchData) => {
// save the object through whatever mean
});Sets the state of the match from a previous save.
-
matchData: a javascript object obtained fromsave()
Restores the state of the match when matchData was obtained from save()
Example:
var match_data;
match.save()
.then( (matchData) => {
match_data = matchData;
});
// then later
match.load(match_data)
.then( () => {
// move on with restored state
});Frees all resources associated to the match.
Once a match object is no longer needed, it is a good idea to destroy it explicitly instead of leaving the garbage collector doing the job for you. A good reason for doing this is that the match object may be attached to a WebGL context and those browser objects are limited (generally 16 contexts per tab), and shortage may cause other games not to display.
Example:
match.destroy()
.then( () => {
// the match object has been freed
});Returns the Jocly move best matching the given string.
-
moveString: a string representing a move, obtained from an external engine or move history
An external move source, like the output of a game engine or a PGN file, may provide strings representing moves. Those strings cannot be digested immediately by Jocly which requires game-dependant obscure objects. pickMove() returns the closest Jocly move object corresponding to the given string, amongst the possible moves in the current state. The method fails if no move was close enough to the input string or if ambiguities could not be resolved.
Example:
// assuming match has been created from 'classic-chess'
match.pickMove('e4')
.then( (move) => {
match.applyMove(move)
// ...
});Returns the player other than the one as input.
Given player is either Jocly.PLAYER_A or Jocly.PLAYER_B, returns the other player.
Example:
match.getTurn()
.then( (player) => {
match.otherPlayer(player)
.then( (other) => {
// if player == Jocly.PLAYER_A then other == Jocly.PLAYER_B
// if player == Jocly.PLAYER_B then other == Jocly.PLAYER_A
})
});Returns the moves played in this match.
The returned value is an array of Jocly obscure move objects.
Example:
match.getPlayedMoves()
.then( (moves) => {
match.getMoveString(moves)
.then( (humanReadableMoves) => {
console.info("Moves played:",humanReadableMoves)
})
});Returns the moves that could currently be played.
The returned value is an array of Jocly obscure move objects.
Example:
match.getPossibleMoves()
.then( (moves) => {
match.getMoveString(moves)
.then( (humanReadableMoves) => {
console.info("You can play:",humanReadableMoves)
})
});Returns the configuration of the game.
When a Jocly game is designed, it comes with a configuration object holding a number of properties. This configuration is not intended to be modified by the application. Some configuration properties are common to all Jocly games and some are game-specific. The later are not documented here and should only be used by applications dedicated to some particular games.
The return object has properties:
-
model: configuration for the model (the game 'mechanic', not the user interface)-
levels: an array of level object. A level object can be passed as propertylevelof the argument passed tomachineSearch()to specify the quality of the artificial intelligence. All level objects have a propertylabelfor displaying to the user. -
title-en: the human-readable name of the game (in English)
-
-
view: configuration for the view (the user interface)-
switchable: boolean indicating whether the board can be displayed from either player's point of view -
skins: an array of available skin objects. Each skin object has properties:-
name: the machine-name of the skin. This is the value to pass as propertyskininsetViewOptions() -
title: the human-readable name of the skin -
3d: a boolean indicating whether this skin uses WebGL
-
-
useAutoComplete: a boolean indicating whether the game supports move auto-completion -
useNotation: a boolean indicating whether the game supports displaying notation -
useShowMoves: a boolean indicating whether the game supports showing available moves
-
Example:
match.getConfig()
.then( (config) => {
console.info("Game is",config.model["title-en"])
});Warning: this method is now obsolete. Use
setViewOptions()to switch the board view perspective.
Changes the player perspective of the board view.
-
player: eitherJocly.PLAYER_AorJocly.PLAYER_B
Many games, but not all, offer the ability to see the board from either player point of view. Method viewAs() allows to choose which player'side to display the board. The method only has effect if parameter config.view.switchable obtained from getconfig() is true.
Example:
match.viewAs(Jocly.PLAYER_B)
.then( () => {
// the board is now viewed as per Player B (i.e *Black* at Chess) point of view
});Runs various secondary view features
-
command: a string representing the requested view action -
...: depends oncommand
Since this method addresses the view of the game (and not the model), it rejects when called in node.js or a from match that has not been attached to a DOM element.
Available commands:
-
enterAnaglyph: Obsolete: usesetViewOptions()to enter/exit anaglyph mode.
When running a 3D skin, calling this command passes the view in anaglyph mode. It requires red-cyan glasses to view stereoscopic 3D effect -
exitAnaglyph: Obsolete: usesetViewOptions()to enter/exit anaglyph mode.
Exits the anaglyph mode that was initiated fromenterAnaglyph -
setPanorama: set a 360 image to surround the scene or replace the existing image. The argument is an object containing propertypictureUrl, the URL of a 360 image, orpictureData, the data URL of a 360 image, or none of these, in this case the current panorama image is removed. Use propertyrotateto specify the rotation angle in degrees around the vertical axis -
stopAnimations: aborts any animation in progress -
takeSnapshot: returns the current board view as a PNG image, under base64 data URL format -
getCamera: returns the current camera position and target -
setCamera: various camera operations. The argument is an object containing propertytypethat defines the operation:-
move: change the camera position and/or target. The argument must have properties:-
camera: an object with propertiesx,y,z,targetX,targetYandtargetZ, as returned byviewControl("getCamera") -
speed: the number of seconds to perform the movement (default is0`, i.e instant change) -
smooth: the R parameter in Kalman filter (default0.001)
-
-
spin: spin around the vertical axis of the camera target (generally the center of the board)-
direction: eithercw(clockwise) orccw(counter-clockwise) -
speed: the time in seconds for an entire spin (default is30)
-
-
stop: stop immediately anymoveorspinoperation in progress
-
Stop animations in progress and redisplay the board if necessary
-
force: iftrue, the board is redisplay even if there were no animation in progress
This method is used to reset the view by stopping all running animations. This is useful for instance if you are executing a playMove() and need to abort the operation without leaving an unclean board display.
Returns a representation of the current state of the board
-
format: a game-dependent optional string representing the state of the board
This method can be used to generate a static board snapshot. For instance, in Chess, it can be used to obtain a FEN representation for a game engine protocol or to save to a PGN file.
Returns a representation of the initial state of the board
-
format: a game-dependent optional string representing the state of the board
The returned object has properties:
-
turn: eitherJocly.PLAYER_AorJocly.PLAYER_B, the first player to move -
boardState: a string representing the board state
In general, a Jocly Match object is only defined by the moves that have been played since the beginning, assuming we started from a standard position. However, it may happen that a match is defined by a given initial position and a list of moves. This is the case for instance when the Match object is built from a PGN file containing a FEN tag.