repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustNotEmptyCell.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific cell that must NOT be empty
*
* @author Dennis Soemers
*/
public class SingleMustNotEmptyCell extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The site that must be empty */
protected final int mustNotEmptySite;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustNotEmptySite
*/
public SingleMustNotEmptyCell(final int mustNotEmptySite)
{
this.mustNotEmptySite = mustNotEmptySite;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
return !state.containerStates()[0].emptyChunkSetCell().get(mustNotEmptySite);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return false;
}
@Override
public SiteType graphElementType()
{
return SiteType.Cell;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.set(mustNotEmptySite);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.Empty;
}
@Override
public int testedSite()
{
return mustNotEmptySite;
}
@Override
public int value()
{
return 1;
}
@Override
public boolean negated()
{
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not empty, we prove not empty
return (other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not empty, we disprove empty
return (other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not not empty, we prove empty
if (other.stateVectorType() == StateVectorTypes.Empty)
return !other.negated();
// If not not empty, we prove that it's not friend, not enemy, not piece 1, not piece 2, etc.
return (other.stateVectorType() != StateVectorTypes.Empty && other.value() > 0 && other.negated());
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not not empty, we disprove not empty
if (other.stateVectorType() == StateVectorTypes.Empty)
return other.negated();
// If not not empty, we disprove friend, enemy, piece 1, piece 2, etc.
return (other.stateVectorType() != StateVectorTypes.Empty && other.value() > 0 && !other.negated());
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + mustNotEmptySite;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustNotEmptyCell))
return false;
final SingleMustNotEmptyCell other = (SingleMustNotEmptyCell) obj;
return (mustNotEmptySite == other.mustNotEmptySite);
}
@Override
public String toString()
{
return "[Cell " + mustNotEmptySite + " must NOT be empty]";
}
//-------------------------------------------------------------------------
}
| 4,215 | 21.306878 | 102 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustNotEmptyEdge.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific edge that must NOT be empty
*
* @author Dennis Soemers
*/
public class SingleMustNotEmptyEdge extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The site that must be empty */
protected final int mustNotEmptySite;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustNotEmptySite
*/
public SingleMustNotEmptyEdge(final int mustNotEmptySite)
{
this.mustNotEmptySite = mustNotEmptySite;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
return !state.containerStates()[0].emptyChunkSetEdge().get(mustNotEmptySite);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return false;
}
@Override
public SiteType graphElementType()
{
return SiteType.Edge;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.set(mustNotEmptySite);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.Empty;
}
@Override
public int testedSite()
{
return mustNotEmptySite;
}
@Override
public int value()
{
return 1;
}
@Override
public boolean negated()
{
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not empty, we prove not empty
return (other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not empty, we disprove empty
return (other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not not empty, we prove empty
if (other.stateVectorType() == StateVectorTypes.Empty)
return !other.negated();
// If not not empty, we prove that it's not friend, not enemy, not piece 1, not piece 2, etc.
return (other.stateVectorType() != StateVectorTypes.Empty && other.value() > 0 && other.negated());
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not not empty, we disprove not empty
if (other.stateVectorType() == StateVectorTypes.Empty)
return other.negated();
// If not not empty, we disprove friend, enemy, piece 1, piece 2, etc.
return (other.stateVectorType() != StateVectorTypes.Empty && other.value() > 0 && !other.negated());
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + mustNotEmptySite;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustNotEmptyEdge))
return false;
final SingleMustNotEmptyEdge other = (SingleMustNotEmptyEdge) obj;
return (mustNotEmptySite == other.mustNotEmptySite);
}
@Override
public String toString()
{
return "[Edge " + mustNotEmptySite + " must NOT be empty]";
}
//-------------------------------------------------------------------------
}
| 4,215 | 21.306878 | 102 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustNotEmptyVertex.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific vertex that must NOT be empty
*
* @author Dennis Soemers
*/
public class SingleMustNotEmptyVertex extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The site that must be empty */
protected final int mustNotEmptySite;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustNotEmptySite
*/
public SingleMustNotEmptyVertex(final int mustNotEmptySite)
{
this.mustNotEmptySite = mustNotEmptySite;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
return !state.containerStates()[0].emptyChunkSetVertex().get(mustNotEmptySite);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return false;
}
@Override
public SiteType graphElementType()
{
return SiteType.Vertex;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.set(mustNotEmptySite);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.Empty;
}
@Override
public int testedSite()
{
return mustNotEmptySite;
}
@Override
public int value()
{
return 1;
}
@Override
public boolean negated()
{
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not empty, we prove not empty
return (other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not empty, we disprove empty
return (other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not not empty, we prove empty
if (other.stateVectorType() == StateVectorTypes.Empty)
return !other.negated();
// If not not empty, we prove that it's not friend, not enemy, not piece 1, not piece 2, etc.
return (other.stateVectorType() != StateVectorTypes.Empty && other.value() > 0 && other.negated());
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not not empty, we disprove not empty
if (other.stateVectorType() == StateVectorTypes.Empty)
return other.negated();
// If not not empty, we disprove friend, enemy, piece 1, piece 2, etc.
return (other.stateVectorType() != StateVectorTypes.Empty && other.value() > 0 && !other.negated());
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + mustNotEmptySite;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustNotEmptyVertex))
return false;
final SingleMustNotEmptyVertex other = (SingleMustNotEmptyVertex) obj;
return (mustNotEmptySite == other.mustNotEmptySite);
}
@Override
public String toString()
{
return "[Vertex " + mustNotEmptySite + " must NOT be empty]";
}
//-------------------------------------------------------------------------
}
| 4,233 | 21.402116 | 102 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustNotWhatCell.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific cell that must NOT contain a specific value
*
* @author Dennis Soemers
*/
public class SingleMustNotWhatCell extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The index of the word that we want to match */
protected final int wordIdx;
/** The mask that we want to apply to the word when matching */
protected final long mask;
/** The word that we should match after masking */
protected final long matchingWord;
/** The site we look at */
protected final int site;
/** The value we look for in chunkset */
protected final int value;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustNotWhatSite
* @param mustNotWhatValue
* @param chunkSize
*/
public SingleMustNotWhatCell(final int mustNotWhatSite, final int mustNotWhatValue, final int chunkSize)
{
// Using same logic as ChunkSet.setChunk() here to determine wordIdx, mask, and matchingWord
final int bitIndex = mustNotWhatSite * chunkSize;
wordIdx = bitIndex >> 6;
final int up = bitIndex & 63;
mask = ((0x1L << chunkSize) - 1) << up;
matchingWord = (((long)mustNotWhatValue) << up);
this.site = mustNotWhatSite;
this.value = mustNotWhatValue;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
return !state.containerStates()[0].matchesWhatCell(wordIdx, mask, matchingWord);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return false;
}
@Override
public SiteType graphElementType()
{
return SiteType.Cell;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.addMask(wordIdx, mask);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.What;
}
@Override
public int testedSite()
{
return site;
}
@Override
public int value()
{
return value;
}
@Override
public boolean negated()
{
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If the tested piece type is the only one owned by its player, we can
// infer not who for that owner
if (AtomicProposition.ownerOnlyOwns(game, value()))
{
// owner of piece doesn't own any other pieces, so can infer that Who is not equal to owner
return (other.stateVectorType() == StateVectorTypes.Who && other.negated() && other.value() == game.equipment().components()[value()].owner());
}
return false;
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If the tested piece type is the only one owned by its player, we can
// infer not who for that owner
if (other.stateVectorType() == StateVectorTypes.Who && AtomicProposition.ownerOnlyOwns(game, value()))
{
// owner of piece doesn't own any other pieces, so can disprove that Who is equal to owner
return (!other.negated() && other.value() == game.equipment().components()[value()].owner());
}
// Not containing a specific piece disproves that we contain that same specific piece
return (other.stateVectorType() == StateVectorTypes.What && other.value() == value());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// False means we DO contain a specific piece, so we prove that we contain it
if (other.stateVectorType() == StateVectorTypes.What)
return (!other.negated() && value() == other.value());
// If we DO contain this specific piece, and if it's the only one owned by its owner, we prove who = owner
if (other.stateVectorType() == StateVectorTypes.Who && AtomicProposition.ownerOnlyOwns(game, value()))
return (!other.negated() && other.value() == game.equipment().components()[value()].owner());
// False means we DO contain a specific piece, so we prove not empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// False means we DO contain a specific piece, so we disprove that we don't contain it
if (other.stateVectorType() == StateVectorTypes.What)
return (other.negated() && value() == other.value());
// If we DO contain this specific piece, and if it's the only one owned by its owner, we disprove who =/= owner
if (other.stateVectorType() == StateVectorTypes.Who && AtomicProposition.ownerOnlyOwns(game, value()))
return (other.negated() && other.value() == game.equipment().components()[value()].owner());
// False means we DO contain a specific piece, so we disprove empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (int) (mask ^ (mask >>> 32));
result = prime * result + (int) (matchingWord ^ (matchingWord >>> 32));
result = prime * result + wordIdx;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustNotWhatCell))
return false;
final SingleMustNotWhatCell other = (SingleMustNotWhatCell) obj;
return (mask == other.mask && matchingWord == other.matchingWord && wordIdx == other.wordIdx);
}
@Override
public String toString()
{
return "[Cell " + site + " must NOT contain " + value + "]";
}
//-------------------------------------------------------------------------
}
| 6,653 | 27.075949 | 146 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustNotWhatEdge.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific cell that must NOT contain a specific value
*
* @author Dennis Soemers
*/
public class SingleMustNotWhatEdge extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The index of the word that we want to match */
protected final int wordIdx;
/** The mask that we want to apply to the word when matching */
protected final long mask;
/** The word that we should match after masking */
protected final long matchingWord;
/** The site we look at */
protected final int site;
/** The value we look for in chunkset */
protected final int value;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustNotWhatSite
* @param mustNotWhatValue
* @param chunkSize
*/
public SingleMustNotWhatEdge(final int mustNotWhatSite, final int mustNotWhatValue, final int chunkSize)
{
// Using same logic as ChunkSet.setChunk() here to determine wordIdx, mask, and matchingWord
final int bitIndex = mustNotWhatSite * chunkSize;
wordIdx = bitIndex >> 6;
final int up = bitIndex & 63;
mask = ((0x1L << chunkSize) - 1) << up;
matchingWord = (((long)mustNotWhatValue) << up);
this.site = mustNotWhatSite;
this.value = mustNotWhatValue;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
return !state.containerStates()[0].matchesWhatEdge(wordIdx, mask, matchingWord);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return false;
}
@Override
public SiteType graphElementType()
{
return SiteType.Edge;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.addMask(wordIdx, mask);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.What;
}
@Override
public int testedSite()
{
return site;
}
@Override
public int value()
{
return value;
}
@Override
public boolean negated()
{
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If the tested piece type is the only one owned by its player, we can
// infer not who for that owner
if (AtomicProposition.ownerOnlyOwns(game, value()))
{
// owner of piece doesn't own any other pieces, so can infer that Who is not equal to owner
return (other.stateVectorType() == StateVectorTypes.Who && other.negated() && other.value() == game.equipment().components()[value()].owner());
}
return false;
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If the tested piece type is the only one owned by its player, we can
// infer not who for that owner
if (other.stateVectorType() == StateVectorTypes.Who && AtomicProposition.ownerOnlyOwns(game, value()))
{
// owner of piece doesn't own any other pieces, so can disprove that Who is equal to owner
return (!other.negated() && other.value() == game.equipment().components()[value()].owner());
}
// Not containing a specific piece disproves that we contain that same specific piece
return (other.stateVectorType() == StateVectorTypes.What && other.value() == value());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// False means we DO contain a specific piece, so we prove that we contain it
if (other.stateVectorType() == StateVectorTypes.What)
return (!other.negated() && value() == other.value());
// If we DO contain this specific piece, and if it's the only one owned by its owner, we prove who = owner
if (other.stateVectorType() == StateVectorTypes.Who && AtomicProposition.ownerOnlyOwns(game, value()))
return (!other.negated() && other.value() == game.equipment().components()[value()].owner());
// False means we DO contain a specific piece, so we prove not empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// False means we DO contain a specific piece, so we disprove that we don't contain it
if (other.stateVectorType() == StateVectorTypes.What)
return (other.negated() && value() == other.value());
// If we DO contain this specific piece, and if it's the only one owned by its owner, we disprove who =/= owner
if (other.stateVectorType() == StateVectorTypes.Who && AtomicProposition.ownerOnlyOwns(game, value()))
return (other.negated() && other.value() == game.equipment().components()[value()].owner());
// False means we DO contain a specific piece, so we disprove empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (int) (mask ^ (mask >>> 32));
result = prime * result + (int) (matchingWord ^ (matchingWord >>> 32));
result = prime * result + wordIdx;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustNotWhatEdge))
return false;
final SingleMustNotWhatEdge other = (SingleMustNotWhatEdge) obj;
return (mask == other.mask && matchingWord == other.matchingWord && wordIdx == other.wordIdx);
}
@Override
public String toString()
{
return "[Edge " + site + " must NOT contain " + value + "]";
}
//-------------------------------------------------------------------------
}
| 6,653 | 27.075949 | 146 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustNotWhatVertex.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific vertex that must NOT contain a specific value
*
* @author Dennis Soemers
*/
public class SingleMustNotWhatVertex extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The index of the word that we want to match */
protected final int wordIdx;
/** The mask that we want to apply to the word when matching */
protected final long mask;
/** The word that we should match after masking */
protected final long matchingWord;
/** The site we look at */
protected final int site;
/** The value we look for in chunkset */
protected final int value;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustNotWhatSite
* @param mustNotWhatValue
* @param chunkSize
*/
public SingleMustNotWhatVertex(final int mustNotWhatSite, final int mustNotWhatValue, final int chunkSize)
{
// Using same logic as ChunkSet.setChunk() here to determine wordIdx, mask, and matchingWord
final int bitIndex = mustNotWhatSite * chunkSize;
wordIdx = bitIndex >> 6;
final int up = bitIndex & 63;
mask = ((0x1L << chunkSize) - 1) << up;
matchingWord = (((long)mustNotWhatValue) << up);
this.site = mustNotWhatSite;
this.value = mustNotWhatValue;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
return !state.containerStates()[0].matchesWhatVertex(wordIdx, mask, matchingWord);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return false;
}
@Override
public SiteType graphElementType()
{
return SiteType.Vertex;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.addMask(wordIdx, mask);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.What;
}
@Override
public int testedSite()
{
return site;
}
@Override
public int value()
{
return value;
}
@Override
public boolean negated()
{
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If the tested piece type is the only one owned by its player, we can
// infer not who for that owner
if (AtomicProposition.ownerOnlyOwns(game, value()))
{
// owner of piece doesn't own any other pieces, so can infer that Who is not equal to owner
return (other.stateVectorType() == StateVectorTypes.Who && other.negated() && other.value() == game.equipment().components()[value()].owner());
}
return false;
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If the tested piece type is the only one owned by its player, we can
// infer not who for that owner
if (other.stateVectorType() == StateVectorTypes.Who && AtomicProposition.ownerOnlyOwns(game, value()))
{
// owner of piece doesn't own any other pieces, so can disprove that Who is equal to owner
return (!other.negated() && other.value() == game.equipment().components()[value()].owner());
}
// Not containing a specific piece disproves that we contain that same specific piece
return (other.stateVectorType() == StateVectorTypes.What && other.value() == value());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// False means we DO contain a specific piece, so we prove that we contain it
if (other.stateVectorType() == StateVectorTypes.What)
return (!other.negated() && value() == other.value());
// If we DO contain this specific piece, and if it's the only one owned by its owner, we prove who = owner
if (other.stateVectorType() == StateVectorTypes.Who && AtomicProposition.ownerOnlyOwns(game, value()))
return (!other.negated() && other.value() == game.equipment().components()[value()].owner());
// False means we DO contain a specific piece, so we prove not empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// False means we DO contain a specific piece, so we disprove that we don't contain it
if (other.stateVectorType() == StateVectorTypes.What)
return (other.negated() && value() == other.value());
// If we DO contain this specific piece, and if it's the only one owned by its owner, we disprove who =/= owner
if (other.stateVectorType() == StateVectorTypes.Who && AtomicProposition.ownerOnlyOwns(game, value()))
return (other.negated() && other.value() == game.equipment().components()[value()].owner());
// False means we DO contain a specific piece, so we disprove empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (int) (mask ^ (mask >>> 32));
result = prime * result + (int) (matchingWord ^ (matchingWord >>> 32));
result = prime * result + wordIdx;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustNotWhatVertex))
return false;
final SingleMustNotWhatVertex other = (SingleMustNotWhatVertex) obj;
return (mask == other.mask && matchingWord == other.matchingWord && wordIdx == other.wordIdx);
}
@Override
public String toString()
{
return "[Vertex " + site + " must NOT contain " + value + "]";
}
//-------------------------------------------------------------------------
}
| 6,672 | 27.156118 | 146 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustNotWhoCell.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific cell that must be not owned by a specific player
*
* @author Dennis Soemers
*/
public class SingleMustNotWhoCell extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The index of the word that we want to match */
protected final int wordIdx;
/** The mask that we want to apply to the word when matching */
protected final long mask;
/** The word that we should match after masking */
protected final long matchingWord;
/** The site we look at */
protected final int site;
/** The value we look for in chunkset */
protected final int value;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustNotWhoSite
* @param mustNotWhoValue
* @param chunkSize
*/
public SingleMustNotWhoCell(final int mustNotWhoSite, final int mustNotWhoValue, final int chunkSize)
{
// Using same logic as ChunkSet.setChunk() here to determine wordIdx, mask, and matchingWord
final int bitIndex = mustNotWhoSite * chunkSize;
wordIdx = bitIndex >> 6;
final int up = bitIndex & 63;
mask = ((0x1L << chunkSize) - 1) << up;
matchingWord = (((long)mustNotWhoValue) << up);
this.site = mustNotWhoSite;
this.value = mustNotWhoValue;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
assert
(
state.containerStates()[0].matchesWhoCell(wordIdx, mask, matchingWord)
==
(state.containerStates()[0].whoCell(site) == value)
);
return !state.containerStates()[0].matchesWhoCell(wordIdx, mask, matchingWord);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return false;
}
@Override
public SiteType graphElementType()
{
return SiteType.Cell;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.addMask(wordIdx, mask);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.Who;
}
@Override
public int testedSite()
{
return site;
}
@Override
public int value()
{
return value;
}
@Override
public boolean negated()
{
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not who is true, we also prove not what for any what owned by the player
if (other.stateVectorType() == StateVectorTypes.What && other.negated())
return (AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
return false;
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not who is true, we disprove what for any what owned by the player
if (other.stateVectorType() == StateVectorTypes.What && !other.negated())
return (AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
// Not containing a specific player disproves that we contain that same specific player
return (other.stateVectorType() == StateVectorTypes.Who && other.value() == value());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// False means we DO contain player we look for
if (other.stateVectorType() == StateVectorTypes.Who)
return (!other.negated() && value() == other.value());
// If the tested player only owns a single piece type, we also prove what for that piece type
if (other.stateVectorType() == StateVectorTypes.What && !other.negated())
return (AtomicProposition.playerOnlyOwns(game, value(), other.value()));
// We prove not-what for any what not owned by player
if (other.stateVectorType() == StateVectorTypes.What && other.negated())
return (!AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
// False means we DO contain a specific player, so we prove not empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// False means we DO contain player we look for
if (other.stateVectorType() == StateVectorTypes.Who)
return (other.negated() && value() == other.value());
// If player owns only a single piece type, we disprove not-what for that piece type
if (other.stateVectorType() == StateVectorTypes.What && other.negated())
return (AtomicProposition.playerOnlyOwns(game, value(), other.value()));
// We disprove what for any what not owned by this player
if (other.stateVectorType() == StateVectorTypes.What && !other.negated())
return (!AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
// False means we DO contain a specific player, so we disprove empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (int) (mask ^ (mask >>> 32));
result = prime * result + (int) (matchingWord ^ (matchingWord >>> 32));
result = prime * result + wordIdx;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustNotWhoCell))
return false;
final SingleMustNotWhoCell other = (SingleMustNotWhoCell) obj;
return (mask == other.mask && matchingWord == other.matchingWord && wordIdx == other.wordIdx);
}
@Override
public String toString()
{
return "[Cell " + site + " must NOT be owned by Player " + value + "]";
}
//-------------------------------------------------------------------------
}
| 6,713 | 26.516393 | 102 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustNotWhoEdge.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific edge that must be not owned by a specific player
*
* @author Dennis Soemers
*/
public class SingleMustNotWhoEdge extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The index of the word that we want to match */
protected final int wordIdx;
/** The mask that we want to apply to the word when matching */
protected final long mask;
/** The word that we should match after masking */
protected final long matchingWord;
/** The site we look at */
protected final int site;
/** The value we look for in chunkset */
protected final int value;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustNotWhoSite
* @param mustNotWhoValue
* @param chunkSize
*/
public SingleMustNotWhoEdge(final int mustNotWhoSite, final int mustNotWhoValue, final int chunkSize)
{
// Using same logic as ChunkSet.setChunk() here to determine wordIdx, mask, and matchingWord
final int bitIndex = mustNotWhoSite * chunkSize;
wordIdx = bitIndex >> 6;
final int up = bitIndex & 63;
mask = ((0x1L << chunkSize) - 1) << up;
matchingWord = (((long)mustNotWhoValue) << up);
this.site = mustNotWhoSite;
this.value = mustNotWhoValue;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
return !state.containerStates()[0].matchesWhoEdge(wordIdx, mask, matchingWord);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return false;
}
@Override
public SiteType graphElementType()
{
return SiteType.Edge;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.addMask(wordIdx, mask);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.Who;
}
@Override
public int testedSite()
{
return site;
}
@Override
public int value()
{
return value;
}
@Override
public boolean negated()
{
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not who is true, we also prove not what for any what owned by the player
if (other.stateVectorType() == StateVectorTypes.What && other.negated())
return (AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
return false;
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not who is true, we disprove what for any what owned by the player
if (other.stateVectorType() == StateVectorTypes.What && !other.negated())
return (AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
// Not containing a specific player disproves that we contain that same specific player
return (other.stateVectorType() == StateVectorTypes.Who && other.value() == value());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// False means we DO contain player we look for
if (other.stateVectorType() == StateVectorTypes.Who)
return (!other.negated() && value() == other.value());
// If the tested player only owns a single piece type, we also prove what for that piece type
if (other.stateVectorType() == StateVectorTypes.What && !other.negated())
return (AtomicProposition.playerOnlyOwns(game, value(), other.value()));
// We prove not-what for any what not owned by player
if (other.stateVectorType() == StateVectorTypes.What && other.negated())
return (!AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
// False means we DO contain a specific player, so we prove not empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// False means we DO contain player we look for
if (other.stateVectorType() == StateVectorTypes.Who)
return (other.negated() && value() == other.value());
// If player owns only a single piece type, we disprove not-what for that piece type
if (other.stateVectorType() == StateVectorTypes.What && other.negated())
return (AtomicProposition.playerOnlyOwns(game, value(), other.value()));
// We disprove what for any what not owned by this player
if (other.stateVectorType() == StateVectorTypes.What && !other.negated())
return (!AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
// False means we DO contain a specific player, so we disprove empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (int) (mask ^ (mask >>> 32));
result = prime * result + (int) (matchingWord ^ (matchingWord >>> 32));
result = prime * result + wordIdx;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustNotWhoEdge))
return false;
final SingleMustNotWhoEdge other = (SingleMustNotWhoEdge) obj;
return (mask == other.mask && matchingWord == other.matchingWord && wordIdx == other.wordIdx);
}
@Override
public String toString()
{
return "[Edge " + site + " must NOT be owned by Player " + value + "]";
}
//-------------------------------------------------------------------------
}
| 6,556 | 26.666667 | 102 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustNotWhoVertex.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific cell that must be not owned by a specific player
*
* @author Dennis Soemers
*/
public class SingleMustNotWhoVertex extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The index of the word that we want to match */
protected final int wordIdx;
/** The mask that we want to apply to the word when matching */
protected final long mask;
/** The word that we should match after masking */
protected final long matchingWord;
/** The site we look at */
protected final int site;
/** The value we look for in chunkset */
protected final int value;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustNotWhoSite
* @param mustNotWhoValue
* @param chunkSize
*/
public SingleMustNotWhoVertex(final int mustNotWhoSite, final int mustNotWhoValue, final int chunkSize)
{
// Using same logic as ChunkSet.setChunk() here to determine wordIdx, mask, and matchingWord
final int bitIndex = mustNotWhoSite * chunkSize;
wordIdx = bitIndex >> 6;
final int up = bitIndex & 63;
mask = ((0x1L << chunkSize) - 1) << up;
matchingWord = (((long)mustNotWhoValue) << up);
this.site = mustNotWhoSite;
this.value = mustNotWhoValue;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
return !state.containerStates()[0].matchesWhoVertex(wordIdx, mask, matchingWord);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return false;
}
@Override
public SiteType graphElementType()
{
return SiteType.Vertex;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.addMask(wordIdx, mask);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.Who;
}
@Override
public int testedSite()
{
return site;
}
@Override
public int value()
{
return value;
}
@Override
public boolean negated()
{
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not who is true, we also prove not what for any what owned by the player
if (other.stateVectorType() == StateVectorTypes.What && other.negated())
return (AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
return false;
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If not who is true, we disprove what for any what owned by the player
if (other.stateVectorType() == StateVectorTypes.What && !other.negated())
return (AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
// Not containing a specific player disproves that we contain that same specific player
return (other.stateVectorType() == StateVectorTypes.Who && other.value() == value());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// False means we DO contain player we look for
if (other.stateVectorType() == StateVectorTypes.Who)
return (!other.negated() && value() == other.value());
// If the tested player only owns a single piece type, we also prove what for that piece type
if (other.stateVectorType() == StateVectorTypes.What && !other.negated())
return (AtomicProposition.playerOnlyOwns(game, value(), other.value()));
// We prove not-what for any what not owned by player
if (other.stateVectorType() == StateVectorTypes.What && other.negated())
return (!AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
// False means we DO contain a specific player, so we prove not empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// False means we DO contain player we look for
if (other.stateVectorType() == StateVectorTypes.Who)
return (other.negated() && value() == other.value());
// If player owns only a single piece type, we disprove not-what for that piece type
if (other.stateVectorType() == StateVectorTypes.What && other.negated())
return (AtomicProposition.playerOnlyOwns(game, value(), other.value()));
// We disprove what for any what not owned by this player
if (other.stateVectorType() == StateVectorTypes.What && !other.negated())
return (!AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
// False means we DO contain a specific player, so we disprove empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (int) (mask ^ (mask >>> 32));
result = prime * result + (int) (matchingWord ^ (matchingWord >>> 32));
result = prime * result + wordIdx;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustNotWhoVertex))
return false;
final SingleMustNotWhoVertex other = (SingleMustNotWhoVertex) obj;
return (mask == other.mask && matchingWord == other.matchingWord && wordIdx == other.wordIdx);
}
@Override
public String toString()
{
return "[Vertex " + site + " must NOT be owned by Player " + value + "]";
}
//-------------------------------------------------------------------------
}
| 6,573 | 26.738397 | 104 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustWhatCell.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific cell that must contain a specific value
*
* @author Dennis Soemers
*/
public class SingleMustWhatCell extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The index of the word that we want to match */
protected final int wordIdx;
/** The mask that we want to apply to the word when matching */
protected final long mask;
/** The word that we should match after masking */
protected final long matchingWord;
/** The site we look at */
protected final int site;
/** The value we look for in chunkset */
protected final int value;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustWhatSite
* @param mustWhatValue
* @param chunkSize
*/
public SingleMustWhatCell(final int mustWhatSite, final int mustWhatValue, final int chunkSize)
{
// Using same logic as ChunkSet.setChunk() here to determine wordIdx, mask, and matchingWord
final int bitIndex = mustWhatSite * chunkSize;
wordIdx = bitIndex >> 6;
final int up = bitIndex & 63;
mask = ((0x1L << chunkSize) - 1) << up;
matchingWord = (((long)mustWhatValue) << up);
this.site = mustWhatSite;
this.value = mustWhatValue;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
return state.containerStates()[0].matchesWhatCell(wordIdx, mask, matchingWord);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return true;
}
@Override
public SiteType graphElementType()
{
return SiteType.Cell;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.addMask(wordIdx, mask);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.What;
}
@Override
public int testedSite()
{
return site;
}
@Override
public int value()
{
return value;
}
@Override
public boolean negated()
{
return false;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// True means we DO contain a specific piece, so we prove that we contain it and prove that we do NOT contain something else
if (other.stateVectorType() == StateVectorTypes.What)
{
if (other.negated())
return (value() != other.value());
else
return (value() == other.value());
}
// We prove who for owner of piece type, and not who for any other player
if (other.stateVectorType() == StateVectorTypes.Who)
{
if (other.negated())
return (other.value() != game.equipment().components()[value()].owner());
else
return (other.value() == game.equipment().components()[value()].owner());
}
// True means we DO contain a specific piece, so we prove not empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// True means we DO contain a specific piece, so we disprove that we don't contain it, and disprove containing any other piece
if (other.stateVectorType() == StateVectorTypes.What)
{
if (other.negated())
return (value() == other.value());
else
return (value() != other.value());
}
// We disprove not who for owner, and who for any other player
if (other.stateVectorType() == StateVectorTypes.Who)
{
if (other.negated())
return (other.value() == game.equipment().components()[value()].owner());
else
return (other.value() != game.equipment().components()[value()].owner());
}
// True means we DO contain a specific piece, so we disprove empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If this is the only piece type owned by its owner, we prove not-who for that owner
if (AtomicProposition.ownerOnlyOwns(game, value()))
return (other.stateVectorType() == StateVectorTypes.Who && other.negated() && other.value() == game.equipment().components()[value()].owner());
return false;
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If this is the only piece type owned by its owner, we disprove who for that owner
if (AtomicProposition.ownerOnlyOwns(game, value()))
return (other.stateVectorType() == StateVectorTypes.Who && !other.negated() && other.value() == game.equipment().components()[value()].owner());
return false;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (int) (mask ^ (mask >>> 32));
result = prime * result + (int) (matchingWord ^ (matchingWord >>> 32));
result = prime * result + wordIdx;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustWhatCell))
return false;
final SingleMustWhatCell other = (SingleMustWhatCell) obj;
return (mask == other.mask && matchingWord == other.matchingWord && wordIdx == other.wordIdx);
}
@Override
public String toString()
{
return "[Cell " + site + " must contain " + value + "]";
}
//-------------------------------------------------------------------------
}
| 6,421 | 24.895161 | 147 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustWhatEdge.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific edge that must contain a specific value
*
* @author Dennis Soemers
*/
public class SingleMustWhatEdge extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The index of the word that we want to match */
protected final int wordIdx;
/** The mask that we want to apply to the word when matching */
protected final long mask;
/** The word that we should match after masking */
protected final long matchingWord;
/** The site we look at */
protected final int site;
/** The value we look for in chunkset */
protected final int value;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustWhatSite
* @param mustWhatValue
* @param chunkSize
*/
public SingleMustWhatEdge(final int mustWhatSite, final int mustWhatValue, final int chunkSize)
{
// Using same logic as ChunkSet.setChunk() here to determine wordIdx, mask, and matchingWord
final int bitIndex = mustWhatSite * chunkSize;
wordIdx = bitIndex >> 6;
final int up = bitIndex & 63;
mask = ((0x1L << chunkSize) - 1) << up;
matchingWord = (((long)mustWhatValue) << up);
this.site = mustWhatSite;
this.value = mustWhatValue;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
return state.containerStates()[0].matchesWhatEdge(wordIdx, mask, matchingWord);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return true;
}
@Override
public SiteType graphElementType()
{
return SiteType.Edge;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.addMask(wordIdx, mask);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.What;
}
@Override
public int testedSite()
{
return site;
}
@Override
public int value()
{
return value;
}
@Override
public boolean negated()
{
return false;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// True means we DO contain a specific piece, so we prove that we contain it and prove that we do NOT contain something else
if (other.stateVectorType() == StateVectorTypes.What)
{
if (other.negated())
return (value() != other.value());
else
return (value() == other.value());
}
// We prove who for owner of piece type, and not who for any other player
if (other.stateVectorType() == StateVectorTypes.Who)
{
if (other.negated())
return (other.value() != game.equipment().components()[value()].owner());
else
return (other.value() == game.equipment().components()[value()].owner());
}
// True means we DO contain a specific piece, so we prove not empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// True means we DO contain a specific piece, so we disprove that we don't contain it, and disprove containing any other piece
if (other.stateVectorType() == StateVectorTypes.What)
{
if (other.negated())
return (value() == other.value());
else
return (value() != other.value());
}
// We disprove not who for owner, and who for any other player
if (other.stateVectorType() == StateVectorTypes.Who)
{
if (other.negated())
return (other.value() == game.equipment().components()[value()].owner());
else
return (other.value() != game.equipment().components()[value()].owner());
}
// True means we DO contain a specific piece, so we disprove empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If this is the only piece type owned by its owner, we prove not-who for that owner
if (AtomicProposition.ownerOnlyOwns(game, value()))
return (other.stateVectorType() == StateVectorTypes.Who && other.negated() && other.value() == game.equipment().components()[value()].owner());
return false;
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If this is the only piece type owned by its owner, we disprove who for that owner
if (AtomicProposition.ownerOnlyOwns(game, value()))
return (other.stateVectorType() == StateVectorTypes.Who && !other.negated() && other.value() == game.equipment().components()[value()].owner());
return false;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (int) (mask ^ (mask >>> 32));
result = prime * result + (int) (matchingWord ^ (matchingWord >>> 32));
result = prime * result + wordIdx;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustWhatEdge))
return false;
final SingleMustWhatEdge other = (SingleMustWhatEdge) obj;
return (mask == other.mask && matchingWord == other.matchingWord && wordIdx == other.wordIdx);
}
@Override
public String toString()
{
return "[Edge " + site + " must contain " + value + "]";
}
//-------------------------------------------------------------------------
}
| 6,421 | 24.895161 | 147 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustWhatVertex.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific vertex that must contain a specific value
*
* @author Dennis Soemers
*/
public class SingleMustWhatVertex extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The index of the word that we want to match */
protected final int wordIdx;
/** The mask that we want to apply to the word when matching */
protected final long mask;
/** The word that we should match after masking */
protected final long matchingWord;
/** The site we look at */
protected final int site;
/** The value we look for in chunkset */
protected final int value;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustWhatSite
* @param mustWhatValue
* @param chunkSize
*/
public SingleMustWhatVertex(final int mustWhatSite, final int mustWhatValue, final int chunkSize)
{
// Using same logic as ChunkSet.setChunk() here to determine wordIdx, mask, and matchingWord
final int bitIndex = mustWhatSite * chunkSize;
wordIdx = bitIndex >> 6;
final int up = bitIndex & 63;
mask = ((0x1L << chunkSize) - 1) << up;
matchingWord = (((long)mustWhatValue) << up);
this.site = mustWhatSite;
this.value = mustWhatValue;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
return state.containerStates()[0].matchesWhatVertex(wordIdx, mask, matchingWord);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return true;
}
@Override
public SiteType graphElementType()
{
return SiteType.Vertex;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.addMask(wordIdx, mask);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.What;
}
@Override
public int testedSite()
{
return site;
}
@Override
public int value()
{
return value;
}
@Override
public boolean negated()
{
return false;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// True means we DO contain a specific piece, so we prove that we contain it and prove that we do NOT contain something else
if (other.stateVectorType() == StateVectorTypes.What)
{
if (other.negated())
return (value() != other.value());
else
return (value() == other.value());
}
// We prove who for owner of piece type, and not who for any other player
if (other.stateVectorType() == StateVectorTypes.Who)
{
if (other.negated())
return (other.value() != game.equipment().components()[value()].owner());
else
return (other.value() == game.equipment().components()[value()].owner());
}
// True means we DO contain a specific piece, so we prove not empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// True means we DO contain a specific piece, so we disprove that we don't contain it, and disprove containing any other piece
if (other.stateVectorType() == StateVectorTypes.What)
{
if (other.negated())
return (value() == other.value());
else
return (value() != other.value());
}
// We disprove not who for owner, and who for any other player
if (other.stateVectorType() == StateVectorTypes.Who)
{
if (other.negated())
return (other.value() == game.equipment().components()[value()].owner());
else
return (other.value() != game.equipment().components()[value()].owner());
}
// True means we DO contain a specific piece, so we disprove empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If this is the only piece type owned by its owner, we prove not-who for that owner
if (AtomicProposition.ownerOnlyOwns(game, value()))
return (other.stateVectorType() == StateVectorTypes.Who && other.negated() && other.value() == game.equipment().components()[value()].owner());
return false;
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// If this is the only piece type owned by its owner, we disprove who for that owner
if (AtomicProposition.ownerOnlyOwns(game, value()))
return (other.stateVectorType() == StateVectorTypes.Who && !other.negated() && other.value() == game.equipment().components()[value()].owner());
return false;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (int) (mask ^ (mask >>> 32));
result = prime * result + (int) (matchingWord ^ (matchingWord >>> 32));
result = prime * result + wordIdx;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustWhatVertex))
return false;
final SingleMustWhatVertex other = (SingleMustWhatVertex) obj;
return (mask == other.mask && matchingWord == other.matchingWord && wordIdx == other.wordIdx);
}
@Override
public String toString()
{
return "[Vertex " + site + " must contain " + value + "]";
}
//-------------------------------------------------------------------------
}
| 6,439 | 24.967742 | 147 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustWhoCell.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific cell that must be owned by a specific player
*
* @author Dennis Soemers
*/
public class SingleMustWhoCell extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The index of the word that we want to match */
protected final int wordIdx;
/** The mask that we want to apply to the word when matching */
protected final long mask;
/** The word that we should match after masking */
protected final long matchingWord;
/** The site we look at */
protected final int site;
/** The value we look for in chunkset */
protected final int value;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustWhoSite
* @param mustWhoValue
* @param chunkSize
*/
public SingleMustWhoCell(final int mustWhoSite, final int mustWhoValue, final int chunkSize)
{
// Using same logic as ChunkSet.setChunk() here to determine wordIdx, mask, and matchingWord
final int bitIndex = mustWhoSite * chunkSize;
wordIdx = bitIndex >> 6;
final int up = bitIndex & 63;
mask = ((0x1L << chunkSize) - 1) << up;
matchingWord = (((long)mustWhoValue) << up);
this.site = mustWhoSite;
this.value = mustWhoValue;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
return state.containerStates()[0].matchesWhoCell(wordIdx, mask, matchingWord);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return true;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return false;
}
@Override
public SiteType graphElementType()
{
return SiteType.Cell;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.addMask(wordIdx, mask);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.Who;
}
@Override
public int testedSite()
{
return site;
}
@Override
public int value()
{
return value;
}
@Override
public boolean negated()
{
return false;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// True means we DO contain player we look for
if (other.stateVectorType() == StateVectorTypes.Who)
return (!other.negated() && value() == other.value());
// We prove not-what for any piece not owned by player, and also prove what if this player only owns a single piece type
if (other.stateVectorType() == StateVectorTypes.What)
{
if (other.negated())
return (game.equipment().components()[other.value()].owner() != value());
else
return AtomicProposition.playerOnlyOwns(game, value(), other.value());
}
// True means we DO contain a specific player, so we prove not empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// True means we DO contain player we look for
if (other.stateVectorType() == StateVectorTypes.Who)
return (other.negated() && value() == other.value());
// We disprove what for any piece not owned by player, and also disprove not-what for piece if player only owns a single piece type
if (other.stateVectorType() == StateVectorTypes.What)
{
if (other.negated())
return AtomicProposition.playerOnlyOwns(game, value(), other.value());
else
return (game.equipment().components()[other.value()].owner() != value());
}
// True means we DO contain a specific player, so we disprove empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// We prove not-who
if (other.stateVectorType() == StateVectorTypes.Who)
return (other.negated() && other.value() == value());
// We prove not-what for any what owned by this player
if (other.stateVectorType() == StateVectorTypes.What && other.negated())
return (AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
return false;
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// We disprove what for any what owned by this player
if (other.stateVectorType() == StateVectorTypes.What && !other.negated())
return (AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
return false;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (int) (mask ^ (mask >>> 32));
result = prime * result + (int) (matchingWord ^ (matchingWord >>> 32));
result = prime * result + wordIdx;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustWhoCell))
return false;
final SingleMustWhoCell other = (SingleMustWhoCell) obj;
return (mask == other.mask && matchingWord == other.matchingWord && wordIdx == other.wordIdx);
}
@Override
public String toString()
{
return "[Cell " + site + " must be owned by Player " + value + "]";
}
//-------------------------------------------------------------------------
}
| 6,254 | 24.847107 | 133 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustWhoEdge.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific edge that must be owned by a specific player
*
* @author Dennis Soemers
*/
public class SingleMustWhoEdge extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The index of the word that we want to match */
protected final int wordIdx;
/** The mask that we want to apply to the word when matching */
protected final long mask;
/** The word that we should match after masking */
protected final long matchingWord;
/** The site we look at */
protected final int site;
/** The value we look for in chunkset */
protected final int value;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustWhoSite
* @param mustWhoValue
* @param chunkSize
*/
public SingleMustWhoEdge(final int mustWhoSite, final int mustWhoValue, final int chunkSize)
{
// Using same logic as ChunkSet.setChunk() here to determine wordIdx, mask, and matchingWord
final int bitIndex = mustWhoSite * chunkSize;
wordIdx = bitIndex >> 6;
final int up = bitIndex & 63;
mask = ((0x1L << chunkSize) - 1) << up;
matchingWord = (((long)mustWhoValue) << up);
this.site = mustWhoSite;
this.value = mustWhoValue;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
return state.containerStates()[0].matchesWhoEdge(wordIdx, mask, matchingWord);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return true;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return false;
}
@Override
public SiteType graphElementType()
{
return SiteType.Edge;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.addMask(wordIdx, mask);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.Who;
}
@Override
public int testedSite()
{
return site;
}
@Override
public int value()
{
return value;
}
@Override
public boolean negated()
{
return false;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// True means we DO contain player we look for
if (other.stateVectorType() == StateVectorTypes.Who)
return (!other.negated() && value() == other.value());
// We prove not-what for any piece not owned by player, and also prove what if this player only owns a single piece type
if (other.stateVectorType() == StateVectorTypes.What)
{
if (other.negated())
return (game.equipment().components()[other.value()].owner() != value());
else
return AtomicProposition.playerOnlyOwns(game, value(), other.value());
}
// True means we DO contain a specific player, so we prove not empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// True means we DO contain player we look for
if (other.stateVectorType() == StateVectorTypes.Who)
return (other.negated() && value() == other.value());
// We disprove what for any piece not owned by player, and also disprove not-what for piece if player only owns a single piece type
if (other.stateVectorType() == StateVectorTypes.What)
{
if (other.negated())
return AtomicProposition.playerOnlyOwns(game, value(), other.value());
else
return (game.equipment().components()[other.value()].owner() != value());
}
// True means we DO contain a specific player, so we disprove empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// We prove not-who
if (other.stateVectorType() == StateVectorTypes.Who)
return (other.negated() && other.value() == value());
// We prove not-what for any what owned by this player
if (other.stateVectorType() == StateVectorTypes.What && other.negated())
return (AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
return false;
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// We disprove what for any what owned by this player
if (other.stateVectorType() == StateVectorTypes.What && !other.negated())
return (AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
return false;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (int) (mask ^ (mask >>> 32));
result = prime * result + (int) (matchingWord ^ (matchingWord >>> 32));
result = prime * result + wordIdx;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustWhoEdge))
return false;
final SingleMustWhoEdge other = (SingleMustWhoEdge) obj;
return (mask == other.mask && matchingWord == other.matchingWord && wordIdx == other.wordIdx);
}
@Override
public String toString()
{
return "[Edge " + site + " must be owned by Player " + value + "]";
}
//-------------------------------------------------------------------------
}
| 6,254 | 24.847107 | 133 |
java
|
Ludii
|
Ludii-master/Features/src/features/spatial/instances/SingleMustWhoVertex.java
|
package features.spatial.instances;
import game.Game;
import game.types.board.SiteType;
import main.collections.ChunkSet;
import other.state.State;
/**
* A test that check for a single specific vertex that must be owned by a specific player
*
* @author Dennis Soemers
*/
public class SingleMustWhoVertex extends AtomicProposition
{
//-------------------------------------------------------------------------
/** The index of the word that we want to match */
protected final int wordIdx;
/** The mask that we want to apply to the word when matching */
protected final long mask;
/** The word that we should match after masking */
protected final long matchingWord;
/** The site we look at */
protected final int site;
/** The value we look for in chunkset */
protected final int value;
//-------------------------------------------------------------------------
/**
* Constructor
* @param mustWhoSite
* @param mustWhoValue
* @param chunkSize
*/
public SingleMustWhoVertex(final int mustWhoSite, final int mustWhoValue, final int chunkSize)
{
// Using same logic as ChunkSet.setChunk() here to determine wordIdx, mask, and matchingWord
final int bitIndex = mustWhoSite * chunkSize;
wordIdx = bitIndex >> 6;
final int up = bitIndex & 63;
mask = ((0x1L << chunkSize) - 1) << up;
matchingWord = (((long)mustWhoValue) << up);
this.site = mustWhoSite;
this.value = mustWhoValue;
}
//-------------------------------------------------------------------------
@Override
public boolean matches(final State state)
{
assert
(
state.containerStates()[0].matchesWhoVertex(wordIdx, mask, matchingWord)
==
(state.containerStates()[0].whoVertex(site) == value)
);
return state.containerStates()[0].matchesWhoVertex(wordIdx, mask, matchingWord);
}
@Override
public boolean onlyRequiresSingleMustEmpty()
{
return false;
}
@Override
public boolean onlyRequiresSingleMustWho()
{
return true;
}
@Override
public boolean onlyRequiresSingleMustWhat()
{
return false;
}
@Override
public SiteType graphElementType()
{
return SiteType.Vertex;
}
@Override
public void addMaskTo(final ChunkSet chunkSet)
{
chunkSet.addMask(wordIdx, mask);
}
@Override
public StateVectorTypes stateVectorType()
{
return StateVectorTypes.Who;
}
@Override
public int testedSite()
{
return site;
}
@Override
public int value()
{
return value;
}
@Override
public boolean negated()
{
return false;
}
//-------------------------------------------------------------------------
@Override
public boolean provesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// True means we DO contain player we look for
if (other.stateVectorType() == StateVectorTypes.Who)
return (!other.negated() && value() == other.value());
// We prove not-what for any piece not owned by player, and also prove what if this player only owns a single piece type
if (other.stateVectorType() == StateVectorTypes.What)
{
if (other.negated())
return (game.equipment().components()[other.value()].owner() != value());
else
return AtomicProposition.playerOnlyOwns(game, value(), other.value());
}
// True means we DO contain a specific player, so we prove not empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && other.negated());
}
@Override
public boolean disprovesIfTrue(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// True means we DO contain player we look for
if (other.stateVectorType() == StateVectorTypes.Who)
return (other.negated() && value() == other.value());
// We disprove what for any piece not owned by player, and also disprove not-what for piece if player only owns a single piece type
if (other.stateVectorType() == StateVectorTypes.What)
{
if (other.negated())
return AtomicProposition.playerOnlyOwns(game, value(), other.value());
else
return (game.equipment().components()[other.value()].owner() != value());
}
// True means we DO contain a specific player, so we disprove empty
return (value() > 0 && other.stateVectorType() == StateVectorTypes.Empty && !other.negated());
}
@Override
public boolean provesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// We prove not-who
if (other.stateVectorType() == StateVectorTypes.Who)
return (other.negated() && other.value() == value());
// We prove not-what for any what owned by this player
if (other.stateVectorType() == StateVectorTypes.What && other.negated())
return (AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
return false;
}
@Override
public boolean disprovesIfFalse(final AtomicProposition other, final Game game)
{
if (graphElementType() != other.graphElementType())
return false;
if (testedSite() != other.testedSite())
return false;
// We disprove what for any what owned by this player
if (other.stateVectorType() == StateVectorTypes.What && !other.negated())
return (AtomicProposition.ownedComponentIDs(game, value()).contains(other.value()));
return false;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (int) (mask ^ (mask >>> 32));
result = prime * result + (int) (matchingWord ^ (matchingWord >>> 32));
result = prime * result + wordIdx;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof SingleMustWhoVertex))
return false;
final SingleMustWhoVertex other = (SingleMustWhoVertex) obj;
return (mask == other.mask && matchingWord == other.matchingWord && wordIdx == other.wordIdx);
}
@Override
public String toString()
{
return "[Vertex " + site + " must be owned by Player " + value + "]";
}
//-------------------------------------------------------------------------
}
| 6,433 | 24.839357 | 133 |
java
|
Ludii
|
Ludii-master/Generation/src/approaches/random/Generator.java
|
package approaches.random;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import compiler.Compiler;
import game.Game;
import grammar.Grammar;
import main.FileHandling;
import main.StringRoutines;
import main.grammar.Baptist;
import main.grammar.Description;
import main.grammar.Report;
import main.grammar.ebnf.EBNF;
import main.grammar.ebnf.EBNFClause;
import main.grammar.ebnf.EBNFClauseArg;
import main.grammar.ebnf.EBNFRule;
import main.options.UserSelections;
import other.context.Context;
import other.move.Move;
import other.trial.Trial;
import parser.Expander;
import parser.Parser;
//-----------------------------------------------------------------------------
/**
* Random ludeme generator.
*
* @author cambolbro
*/
public class Generator
{
/**
* First item in each entry is the relevant ludeme name, the second item
* is the list of strings that can be used in it wherever a <string>
* parameter is expected. Repeat strings that you want to occur more often.
*/
private final static String[][][] stringPool =
{
// Player
{
{ // Ludemes:
"player",
},
{ // Strings:
"A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "D",
}
},
// Piece
{
{ // Ludemes:
"piece", "hop", "slide", "fromTo", "place", "leap", "step",
"shoot", "promotion", "count",
},
{ // Strings:
"Disc", "Disc", "Disc", "Disc", "Disc0", "Disc0", "Disc1", "Disc1",
"Disc2", "Disc2", "Disc3", "Disc3", "Disc4", "Disc4", "Disc5", "Disc6",
"DiscA", "DiscB", "DiscA1", "DiscB1", "DiscA2", "DiscB2",
"Pawn", "Pawn", "Pawn0", "Pawn1", "Pawn2", "Pawn3", "Pawn4",
"King", "King0", "King1", "King2", "King3",
}
},
// Region
{
{ // Ludemes:
"regions", "region", "sites",
},
{ // Strings:
"Region", "Region0", "Region1", "Region2", "Region3", "Region4",
}
},
// Track
{
{ // Ludemes:
"track",
},
{ // Strings:
"Track", "Track0", "Track1", "Track2", "Track3", "Track4",
}
},
// Vote
{
{ // Ludemes:
"vote",
},
{ // Strings:
"Yes", "No", "Maybe",
}
},
// Propose
{
{ // Ludemes:
"propose",
},
{ // Strings:
"Win", "Draw", "Loss", "Tie", "Pass",
}
},
// Hints
{
{ // Ludemes:
"hints",
},
{ // Strings:
"Hints", "Hints0", "Hints1", "Hints2", "Hints3",
}
},
};
/** Maximum search depth. */
private final static int MAX_DEPTH = 100;
/** Point at which to stop random playouts. */
private final static int MAX_MOVES = 2000;
/** Maximum length for generated arrays. */
private final static int MAX_ARRAY_LENGTH = 10;
//-------------------------------------------------------------------------
/**
* @param ruleName Rule name.
* @param seed RNG seed.
* @return Ludemeplex description generated by completing this rule.
*/
public static String generate(final String ruleName, final long seed)
{
final Random rng = new Random(seed);
rng.nextInt(); // Burn first value, or will always get the same first
// nextInt(R) if the bound is small and a power of 2.
final List<EBNFRule> rules = findRules(ruleName);
if (rules.isEmpty())
{
System.out.println("** Rule " + ruleName + " could not be found.");
return null;
}
// System.out.println("Rules:");
// for (final EBNFRule rule : rules)
// System.out.println("- " + rule);
String ludeme = complete(rules.get(rng.nextInt(rules.size())), rng, 0);
ludeme = instantiatePrimitives(ludeme, rng);
// Format nicely
final Report report = new Report();
final Description description = new Description(ludeme);
Expander.expand(description, new UserSelections(new ArrayList<String>()), report, false);
if (report.isError())
return ludeme;
return description.expanded();
}
//-------------------------------------------------------------------------
/**
* @return Returns list of rules that match a given name.
*/
static List<EBNFRule> findRules(final String ruleName)
{
final List<EBNFRule> list = new ArrayList<EBNFRule>();
final EBNF ebnf = Grammar.grammar().ebnf();
String str = StringRoutines.toDromedaryCase(ruleName);
// Try exact match
EBNFRule rule = ebnf.rules().get(str);
if (rule != null)
{
list.add(rule);
return list;
}
// Try match with rule delimiters '<...>'
rule = ebnf.rules().get("<" + str + ">");
if (rule != null)
{
list.add(rule);
return list;
}
// Find any match
if (str.charAt(0) == '<')
str = str.substring(1);
if (str.charAt(str.length() - 1) == '>')
str = str.substring(0, str.length() - 1);
for (final EBNFRule ruleN : ebnf.rules().values())
{
String strN = ruleN.lhs();
if (strN.charAt(0) == '<')
strN = strN.substring(1);
if (strN.charAt(strN.length() - 1) == '>')
strN = strN.substring(0, strN.length() - 1);
while (strN.contains("."))
{
final int c = strN.indexOf(".");
strN = strN.substring(c + 1);
}
if (strN.equalsIgnoreCase(str))
list.add(ruleN);
}
return list;
}
//-------------------------------------------------------------------------
/**
* @return Complete ludemeplex string from a given rule.
*/
private static String complete(final EBNFRule rule, final Random rng, final int depth)
{
//System.out.println("\nCompleting: " + rule.lhs());
if (depth > MAX_DEPTH)
{
System.out.println("** Maximum depth " + MAX_DEPTH + " exceeded in complete() A.");
return "";
}
// Check for quick exit to limit recursion depth
if (rule.lhs().equals("<int>"))
{
if (rng.nextInt(2 + depth) != 0)
{
// Stop recursion and return terminal version
return "%int%";
}
}
else if (rule.lhs().equals("<boolean>"))
{
if (rng.nextInt(2 + depth) != 0)
{
// Stop recursion and return terminal version
return (rng.nextInt(2) != 0) ? "True" : "False";
}
}
else if (rule.lhs().equals("<float>"))
{
if (rng.nextInt(2 + depth) != 0)
{
// Stop recursion and return terminal version
return "%float%";
}
}
else if (rule.lhs().equals("<dim>"))
{
// **
// ** Note: Limit dim recursion or (board ...) ludemes are never completed!
// **
if (rng.nextInt(2 + depth) != 0)
{
// Stop recursion and return terminal version
return "%dim%";
}
}
if (rule.rhs() == null || rule.rhs().isEmpty())
{
System.out.println("** Rule has no clauses: " + rule);
return "";
}
// We must sort the clauses to ensure that multiple iterations, with the same rng seed, produce the same output
final List<EBNFClause> clauses = new ArrayList<>(rule.rhs());
Collections.sort(clauses, Comparator.comparing(EBNFClause::toString));
final EBNFClause clause = clauses.get(rng.nextInt(rule.rhs().size()));
// System.out.println("clause: " + clause + " " + (clause.isTerminal() ? "T" : "") + (clause.isRule() ? "R" : "") + (clause.isConstructor() ? "C" : ""));
if (clause.isTerminal())
{
final String clauseString = clause.toString();
if (clauseString.equals("string"))
{
return "%string%";
}
// Check for primitive arrays.
// NOTE: the length of the arrays is biased towards small lengths since rng.nextInt() is re-evaluated at every iteration.
else if (clauseString.equals("{<int>}"))
{
StringBuilder sb = new StringBuilder();
sb.append('{');
for (int i = 0; i < rng.nextInt(MAX_ARRAY_LENGTH - 1) + 1; i++)
{
sb.append("%int% ");
}
sb.append('}');
return sb.toString();
}
else if (clauseString.equals("{<float>}"))
{
StringBuilder sb = new StringBuilder();
sb.append('{');
for (int i = 0; i < rng.nextInt(MAX_ARRAY_LENGTH - 1) + 1; i++)
{
sb.append("%float% ");
}
sb.append('}');
return sb.toString();
}
else if (clauseString.equals("{<boolean>}"))
{
StringBuilder sb = new StringBuilder();
sb.append('{');
for (int i = 0; i < rng.nextInt(MAX_ARRAY_LENGTH - 1) + 1; i++)
{
sb.append((rng.nextInt(2) != 0) ? "True " : "False ");
}
sb.append('}');
return sb.toString();
}
else if (clauseString.equals("{<dim>}"))
{
StringBuilder sb = new StringBuilder();
sb.append('{');
for (int i = 0; i < rng.nextInt(MAX_ARRAY_LENGTH - 1) + 1; i++)
{
sb.append("%dim% ");
}
sb.append('}');
return sb.toString();
}
// Return complete clause immediately
return clauseString;
}
if (clause.isRule())
{
final List<EBNFRule> clauseRule = findRules(clause.token());
if (clauseRule.isEmpty())
{
System.out.println("** Clause has no rule match: " + clause.token());
return "?";
}
else if (clauseRule.size() > 1)
{
System.out.println("** Clause has more than one rule match: " + clause.token());
return "?";
}
if (depth + 1 >= MAX_DEPTH)
{
//System.out.println("** Maximum depth " + MAX_DEPTH + " reached in complete() B.");
return "";
}
return complete(clauseRule.get(rng.nextInt(clauseRule.size())), rng, depth + 1);
}
// Clause must be a constructor at this point
return handleConstructor(clause, rng, depth);
}
//-------------------------------------------------------------------------
static String handleConstructor(final EBNFClause clause, final Random rng, final int depth)
{
//System.out.println(depth);
if (depth > MAX_DEPTH)
{
System.out.println("** Maximum depth " + MAX_DEPTH + " exceeded in handleConstructor(). A");
return "";
}
String str = "(" + clause.token();
// Determine 'or' groups
final int MAX_OR_GROUPS = 10;
final BitSet[] orGroups = new BitSet[MAX_OR_GROUPS];
for (int n = 0; n < MAX_OR_GROUPS; n++)
orGroups[n] = new BitSet();
for (int a = 0; a < clause.args().size(); a++)
{
final EBNFClauseArg arg = clause.args().get(a);
orGroups[arg.orGroup()].set(a);
}
for (int n = 1; n < MAX_OR_GROUPS; n++)
while (orGroups[n].cardinality() > 1)
orGroups[n].set(rng.nextInt(clause.args().size()), false);
// Determine which args to use
final BitSet use = new BitSet();
for (int a = 0; a < clause.args().size(); a++)
for (int n = 0; n < MAX_OR_GROUPS; n++)
if (orGroups[n].get(a))
use.set(a);
// Turn off some optional arguments (the deeper, the more likely)
for (int a = 0; a < clause.args().size(); a++)
if (clause.args().get(a).isOptional() && rng.nextInt(2 + depth) != 0)
use.set(a, false);
for (int a = 0; a < clause.args().size(); a++)
{
final EBNFClauseArg arg = clause.args().get(a);
if (!use.get(a))
continue; // skip this arg
if (arg.parameterName() == null)
str += " ";
else
str += " " + arg.parameterName() + ":";
if (arg.nesting() == 0)
{
// Not an array
final String argStr = handleArg(arg, rng, depth);
if (argStr == "")
return ""; // maximum depth reached
str += argStr;
}
else
{
// Handle array (might have nested sub-arrays)
str += "{";
final int numItems = 1 + lowBiasedRandomInteger(rng, false) % 4;
for (int i = 0; i < numItems; i++)
{
if (arg.nesting() == 1)
{
// Single array
final String argStr = handleArg(arg, rng, depth);
if (argStr == "")
return ""; // maximum depth reached
str += " " + argStr;
}
else if (arg.nesting() == 2)
{
// Nested sub-arrays
str += " {";
final int numSubItems = 1 + lowBiasedRandomInteger(rng, false) % 4;
for (int j = 0; j < numSubItems; j++)
{
final String argStr = handleArg(arg, rng, depth);
if (argStr == "")
return ""; // maximum depth reached
str += " " + argStr;
}
str += " }";
}
else
{
//System.out.println("** Generator.handleConstructor(): Three dimensional arrays not support yet.");
}
}
str += " }";
}
}
str += ")";
return str;
}
static String handleArg(final EBNFClauseArg arg, final Random rng, final int depth)
{
if (depth > MAX_DEPTH)
{
System.out.println("** Maximum depth " + MAX_DEPTH + " exceeded in handleArg() A.");
return "";
}
if (EBNF.isTerminal(arg.token()))
{
// Simply instantiate here rather than recursing, to catch 'string'
// (also catches 'int', 'boolean' and 'float).
return arg.token(); //toString();
}
final List<EBNFRule> argRule = findRules(arg.token());
if (argRule.isEmpty())
{
System.out.println("** Clause arg has no rule match: " + arg.token());
return "?";
}
else if (argRule.size() > 1)
{
System.out.println("** Clause arg has more than one rule match: " + arg.token());
return "?";
}
if (depth + 1 >= 1000)
{
System.out.println("** Safe generation depth " + depth + " exceeded in handleArg() B.");
return "";
}
return complete(argRule.get(0), rng, depth + 1);
}
//-------------------------------------------------------------------------
static String instantiatePrimitives(final String input, final Random rng)
{
String str = instantiateStrings(input.trim(), rng);
str = instantiateIntegers(str, rng);
str = instantiateFloats(str, rng);
str = instantiateDims(str, rng);
return str;
}
static String instantiateStrings(final String input, final Random rng)
{
String str = input.trim();
// Instantiate 'string' placeholders
int c = 0;
while (true)
{
// Find next occurrence of 'string'
c = str.indexOf("%string%", c + 1);
if (c < 0)
break;
final String owner = enclosingLudemeName(str, c);
//System.out.println("owner='" + owner + "'");
String replacement = null;
if
(
owner.equalsIgnoreCase("game")
||
owner.equalsIgnoreCase("match")
||
owner.equalsIgnoreCase("subgame")
)
{
// Create a name for this game
replacement = Baptist.baptist().name(str.hashCode(), 4);
}
if (replacement == null)
{
// Look for a ludeme from the stringPool
for (int group = 0; group < stringPool.length && replacement == null; group++)
for (int n = 0; n < stringPool[group][0].length && replacement == null; n++)
if (owner.equalsIgnoreCase(stringPool[group][0][n]))
replacement = stringPool[group][1][rng.nextInt(stringPool[group][1].length)];
}
if (replacement == null)
{
// Create random coordinate
replacement = (char)('A' + rng.nextInt(26)) + ("" + rng.nextInt(26));
}
str = str.substring(0, c) + "\"" + replacement + "\"" + str.substring(c + "%string%".length());
}
return str;
}
static String instantiateIntegers(final String input, final Random rng)
{
String str = input.trim();
// Instantiate 'int' placeholders
int c = 0;
while (true)
{
// Find next occurrence of 'int'
c = str.indexOf("%int%", c + 1);
if (c < 0)
break;
int num = lowBiasedRandomInteger(rng, true);
final String owner = enclosingLudemeName(str, c);
if (owner.equalsIgnoreCase("players") && rng.nextInt(4) != 0)
{
// Restrict number of players
num = num % 4 + 1;
}
str = str.substring(0, c) + num + str.substring(c + "%int%".length());
}
return str;
}
static String instantiateDims(final String input, final Random rng)
{
String str = input.trim();
// Instantiate 'dim' placeholders
int c = 0;
while (true)
{
// Find next occurrence of 'dim'
c = str.indexOf("%dim%", c + 1);
if (c < 0)
break;
// Positive number within reasonable bounds
int num = Math.abs(lowBiasedRandomInteger(rng, true)) % 20;
final String owner = enclosingLudemeName(str, c);
if (owner.equalsIgnoreCase("players") && rng.nextInt(4) != 0)
{
// Restrict number of players
num = num % 4 + 1;
}
str = str.substring(0, c) + num + str.substring(c + "%dim%".length());
}
return str;
}
static String instantiateFloats(final String input, final Random rng)
{
String str = input.trim();
final DecimalFormat df = new DecimalFormat("#.##");
// Instantiate 'float' placeholders
int c = 0;
while (true)
{
// Find next occurrence of 'float'
c = str.indexOf("%float%", c + 1);
if (c < 0)
break;
final double num = lowBiasedRandomInteger(rng, true) / 4.0;
str = str.substring(0, c) + df.format(num).replace(',', '.') + str.substring(c + "%float%".length());
}
return str;
}
//-------------------------------------------------------------------------
/**
* @return Name of enclosing ludeme (if any).
*/
static String enclosingLudemeName(final String str, final int fromIndex)
{
int c = fromIndex;
while (c >= 0 && str.charAt(c) != '(')
c--;
if (c < 0)
return str.split(" ")[0];
int cc = c + 1;
while (cc < str.length() && str.charAt(cc) != ' ')
cc++;
return str.substring(c + 1, cc);
}
//-------------------------------------------------------------------------
/**
* @return Random number (biased towards lower values) that is sometimes negative.
*/
private static int lowBiasedRandomInteger(final Random rng, final boolean negate)
{
int r = 0;
switch (rng.nextInt(10))
{
case 0: r = rng.nextInt(2) + 1; break;
case 1: r = rng.nextInt(4); break;
case 2: r = rng.nextInt(3) + 1; break;
case 3: r = rng.nextInt(4) + 1; break;
case 4: r = rng.nextInt(5) + 1; break;
case 5: r = rng.nextInt(6) + 1; break;
case 6: r = rng.nextInt(8); break;
case 7: r = rng.nextInt(16); break;
case 8: r = rng.nextInt(100); break;
case 9: r = rng.nextInt(1000); break;
default: r = 0;
}
if (negate && rng.nextInt(20) == 0)
r = -r;
return r;
}
//-------------------------------------------------------------------------
/**
* @param numGames The number of games to generate.
* @param randomSeed If the seed should be randomised.
* @param isValid Only the games with all the requirement and not satisfying the WillCrash test.
* @param boardlessIncluded If we try to generate some boardless games.
* @param doSave Whether to save generated games.
* @return The last valid game description.
*/
public static String testGames
(
final int numGames, final boolean randomSeed,
final boolean isValid, final boolean boardlessIncluded, final boolean doSave
)
{
Grammar.grammar().ebnf(); // trigger grammar and EBNF structure to be created
// final EBNF ebnf = Grammar.grammar().ebnf();
// for (final EBNFRule rule : ebnf.rules().values())
// System.out.println(rule);
final long startAt = System.currentTimeMillis();
int numValid = 0;
int numParse = 0;
int numCompile = 0;
int numFunctional = 0;
int numPlayable = 0;
// Keep a record of the last valid, playable, generated game, which will be returned at the end.
String lastGeneratedGame = null;
final Random rng = new Random();
// Generate games
for (int n = 0; n < numGames; n++)
{
System.out.println("\n---------------------------------\nGame " + n + ":");
final String str = Generator.generate("game", randomSeed ? rng.nextLong() : n);
System.out.println(str);
if (str == "")
continue; // generation failed
numValid++;
String gameName = StringRoutines.gameName(str);
if (gameName == null)
gameName = "Anon";
final String fileName = gameName + ".lud"; // just in case...
// Check whether game parses
final Description description = new Description(str);
final UserSelections userSelections = new UserSelections(new ArrayList<String>());
final Report report = new Report();
Parser.expandAndParse(description, userSelections, report, true, false);
if (report.isError())
{
// Game does not parse
if (doSave)
FileHandling.saveStringToFile(str, "../Common/res/lud/test/buggy/unparsable/", fileName);
continue;
}
//System.out.println("Parses...");
numParse++;
if (!boardlessIncluded)
{
//if (game.isBoardless())
if (description.expanded().contains("boardless"))
continue;
}
for (final String warning : report.warnings())
if (!warning.contains("No version info."))
System.out.println("- Warning: " + warning);
// Check whether game compiles
Game game = null;
try
{
game = (Game)Compiler.compileTest(new Description(str), false);
}
catch (final Exception e)
{
for (final String error : report.errors())
System.out.println("- Error: " + error);
for (final String warning : report.warnings())
if (!warning.contains("No version info."))
System.out.println("- Warning: " + warning);
e.printStackTrace();
}
if (game == null)
{
// Game does not compile
if (doSave)
FileHandling.saveStringToFile(str, "../Common/res/lud/test/buggy/uncompilable/", fileName);
continue;
}
//System.out.println("Compiles...");
numCompile++;
if (isValid)
{
if (game.hasMissingRequirement() || game.willCrash())
continue;
System.out.println("Not known to crash...");
}
// if (!boardlessIncluded)
// {
// //if (game.isBoardless())
// if (description.expanded().contains("boardless"))
// continue;
// System.out.println("Parses...");
// }
// Check whether game is functional
try
{
if (!isFunctional(game))
{
// Game is not functional
if (doSave)
FileHandling.saveStringToFile(str, "../Common/res/lud/test/buggy/nonfunctional/", fileName);
continue;
}
}
catch (final Exception e)
{
System.out.println("Handling exception during playability test.");
e.printStackTrace();
}
//System.out.println("Is functional...");
numFunctional++;
// Check whether game is playable
if (!isPlayable(game))
{
// Game is not playable
if (doSave)
FileHandling.saveStringToFile(str, "../Common/res/lud/test/buggy/unplayable/", fileName);
continue;
}
System.out.println("Is playable.");
numPlayable++;
//if (doSave)
FileHandling.saveStringToFile(str, "../Common/res/lud/test/playable/", fileName);
lastGeneratedGame = str;
}
final double secs = (System.currentTimeMillis() - startAt) / 1000.0;
System.out.println
(
"\n===========================================\n"
+
numGames + " random games generated in " + secs + "s:\n"
+
numValid + " valid (" + (numValid * 100.0 / numGames) + "%).\n"
+
numParse + " parse (" + (numParse * 100.0 / numGames) + "%).\n"
+
numCompile + " compile (" + (numCompile * 100.0 / numGames) + "%).\n"
+
numFunctional + " functional (" + (numFunctional * 100.0 / numGames) + "%).\n"
+
numPlayable + " playable (" + (numPlayable * 100.0 / numGames) + "%).\n"
);
return lastGeneratedGame;
}
//-------------------------------------------------------------------------
/**
* Method from Eric to improve some generations did with Ludii.
*
* @param numGames The number of games to generate.
* @param dlpRestriction If we apply some DLP restrictions (like no
* boardless, cards etc...)
* @param withDecision If we keep the games with only decision moves.
* @return The last valid game description.
*/
public static String testGamesEric
(
final int numGames, final boolean dlpRestriction,
final boolean withDecision
)
{
Grammar.grammar().ebnf(); // trigger grammar and EBNF structure to be created
final long startAt = System.currentTimeMillis();
final Report report = new Report();
// Keep a record of the last valid, playable, generated game, which will be returned at the end.
String lastGeneratedGame = null;
final Random rng = new Random();
// Generate games
int n = 0;
int numTry = 0;
while (n < numGames)
{
final String str = Generator.generate("game", rng.nextLong());
if (str == "")
{
numTry++;
// System.out.println("Generation failed for try " + numTry);
continue; // generation failed
}
final boolean containsPlayRules = str.contains("(play");
final boolean containsEndRules = str.contains("(end");
final boolean containsMatch = str.contains("(match");
if (!containsPlayRules || !containsEndRules || containsMatch)
{
numTry++;
// System.out.println("Game is a match or does not generate a play and end rule
// " + numTry);
continue;
}
// Check whether game parses
final Description description = new Description(str);
final UserSelections userSelections = new UserSelections(new ArrayList<String>());
Parser.expandAndParse(description, userSelections, report, true, false);
if (report.isError())
{
// Game does not parse
// FileHandling.saveStringToFile(str,
// "../Common/res/lud/test/buggy/unparsable/", fileName);
numTry++;
// System.out.println("Game unparsable for try " + numTry);
continue;
}
// for (final String warning : report.warnings())
// if (!warning.contains("No version info."))
// System.out.println("- Warning: " + warning);
// Check whether game compiles
Game game = null;
try
{
game = (Game)Compiler.compileTest(new Description(str), false);
}
catch (final Exception e)
{
// Nothing to do.
}
if (game == null)
{
// Game does not compile
numTry++;
// System.out.println("Game uncompilable for try " + numTry);
continue;
}
if (game.hasMissingRequirement() || game.willCrash())
{
numTry++;
// System.out.println("Game with warning and possible crash for try " + numTry);
continue;
}
// No boardless, No match, no deduc Puzzle, cards, dominoes or large pieces, no
// hidden info.
// Only Alternating game.
if (dlpRestriction)
if (game.hasSubgames() || game.isBoardless() || game.isDeductionPuzzle() || game.hasCard()
|| game.hasDominoes() || game.hasLargePiece() || !game.isAlternatingMoveGame()
|| game.hiddenInformation()
)
{
numTry++;
// System.out.println("Game not satisfying for try " + numTry);
continue;
}
final String fileName = game.name() + ".lud";
// Check whether game is functional
if (withDecision)
{
if (!isFunctionalAndWithOnlyDecision(game))
{
// Game is not functional
numTry++;
// System.out.println("Game non functional or has a move with no decision for
// try " + numTry);
continue;
}
}
else if (!isFunctional(game))
{
// Game is not functional
numTry++;
FileHandling.saveStringToFile(str, "../Common/res/lud/test/buggy/nonfunctional/", fileName);
// System.out.println("Game non functional for
// try " + numTry);
continue;
}
// Check whether game is playable
if (!isPlayable(game))
{
// Game is not playable
numTry++;
FileHandling.saveStringToFile(str, "../Common/res/lud/test/buggy/unplayable/", fileName);
// System.out.println("Game unplayable for try " + numTry);
continue;
}
else
{
FileHandling.saveStringToFile(str, "../Common/res/lud/test/buggy/toTest/", fileName);
System.out.println("GAME " + n + " GENERATED");
numTry++;
n++;
}
lastGeneratedGame = str;
}
final double secs = (System.currentTimeMillis() - startAt) / 1000.0;
System.out.println("Generation done in " + secs + " seconds");
System.out.println(numTry + " tries were necessary.");
return lastGeneratedGame;
}
/**
* @return Whether a trial of the game can be played without crashing.
*/
public static boolean isFunctionalAndWithOnlyDecision(final Game game)
{
final Context context = new Context(game, new Trial(game));
game.start(context);
Trial trial = null;
try
{
trial = game.playout
(
context, null, 1.0, null, 0, MAX_MOVES,
ThreadLocalRandom.current()
);
}
catch(final Exception e)
{
e.printStackTrace();
}
if(trial == null)
return false;
for(final Move m : trial.generateCompleteMovesList())
if(!m.isDecision())
return false;
return true;
}
//-------------------------------------------------------------------------
/**
* @return Whether a trial of the game can be played without crashing.
*/
public static boolean isFunctional(final Game game)
{
final Context context = new Context(game, new Trial(game));
game.start(context);
Trial trial = null;
try
{
trial = game.playout
(
context, null, 1.0, null, 0, MAX_MOVES,
ThreadLocalRandom.current()
);
}
catch(final Exception e)
{
e.printStackTrace();
}
return trial != null;
}
//-------------------------------------------------------------------------
/**
* @return Whether the game is basically playable, i.e. more trials are of
* reasonable length than not. A trial is of reasonable length if it
* lasts at least 2 * num_players moves and ends before 90% of MAX_MOVES are reached.
*/
public static boolean isPlayable(final Game game)
{
final Context context = new Context(game, new Trial(game));
final int NUM_TRIALS = 10;
int numResults = 0;
for (int t = 0; t < NUM_TRIALS; t++)
{
game.start(context);
Trial trial = null;
try
{
trial = game.playout
(
context, null, 1.0, null, 0, MAX_MOVES,
ThreadLocalRandom.current()
);
}
catch(final Exception e)
{
e.printStackTrace();
}
//System.out.println(trial.numMoves() + " moves in " + trial.numberOfTurns() + " turns.");
if (trial == null)
return false;
final int minMoves = 2 * game.players().count();
final int maxMoves = MAX_MOVES * 9 / 10;
if (trial.numMoves() >= minMoves && trial.numMoves() <= maxMoves)
numResults++;
}
return numResults >= NUM_TRIALS / 2;
}
//-------------------------------------------------------------------------
@SuppressWarnings("static-method")
void test()
{
Grammar.grammar().ebnf(); // trigger grammar and EBNF structure to be created
// Check rules
int numClauses = 0;
for (final EBNFRule rule : Grammar.grammar().ebnf().rules().values())
{
numClauses += rule.rhs().size();
for (final EBNFClause clause : rule.rhs())
{
//System.out.println("EBNF clause: " + clause);
if (clause != null && clause.args() != null)
for (final EBNFClauseArg arg : clause.args())
{
final List<EBNFRule> list = findRules(arg.token());
if
(
list.isEmpty()
&&
!arg.token().equalsIgnoreCase("string")
&&
!Character.isUpperCase(arg.token().charAt(0)) // probably a single enum that has been instantiated
)
{
System.out.println("** No rule for: " + arg);
}
}
}
}
System.out.println(Grammar.grammar().ebnf().rules().size() + " EBNF rules with " + numClauses + " clauses generated.");
// final Random rng = new Random();
// final int bound = 2;
// for (int seed = 0; seed < 100; seed++)
// {
// rng.setSeed(seed);
// //rng.nextInt();
// for (int n = 0; n < 32; n++)
// System.out.print(rng.nextInt(bound) + " ");
// System.out.println();
// }
System.out.println("===========================================================\n");
final long startAt = System.currentTimeMillis();
// Generate games
final int NUM_GAMES = 1000;
for (int n = 0; n < NUM_GAMES; n++)
{
final String str = generate("game", n);
if (n % 100 == 0)
{
System.out.println(n + ":");
System.out.println(str == "" ? "** Generation failed.\n" : str);
}
}
final double secs = (System.currentTimeMillis() - startAt) / 1000.0;
System.out.println(NUM_GAMES + " games generated in " + secs + "s.");
System.out.println("===========================================================\n");
// Generate sub-ludeme
String str = generate("or", 0);
System.out.println(str);
str = generate("or", 1);
System.out.println(str);
System.out.println("===========================================================\n");
// Generate sub-ludeme
str = generate("board", System.currentTimeMillis());
System.out.println(str);
System.out.println("===========================================================\n");
// Generate enum
str = generate("ShapeType", 0);
System.out.println(str);
str = generate("ShapeType", 1);
System.out.println(str);
}
//-------------------------------------------------------------------------
/**
* The main method of the generator.
*
* @param arg
*/
public static void main(final String[] arg)
{
final Generator generator = new Generator();
generator.test();
}
}
| 33,092 | 24.996072 | 156 |
java
|
Ludii
|
Ludii-master/Generation/test/RandomGameTester.java
|
import approaches.random.Generator;
/**
* Random game tester.
* @author cambolbro
*/
public class RandomGameTester
{
public static void main(final String[] arg)
{
Generator.testGames(10, true, false, false, false);
}
}
| 228 | 15.357143 | 53 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/Arg.java
|
package compiler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import annotations.Hide;
import grammar.Grammar;
import main.grammar.Call;
import main.grammar.Instance;
import main.grammar.Report;
import main.grammar.Token;
//-----------------------------------------------------------------------------
/**
* Constructor argument read in from file, in compilable format.
* Could be a constructor, terminal (String, enum, etc.) or list of constructors.
* @author cambolbro
*/
public abstract class Arg
{
// Name of the symbol
protected String symbolName = null;
// Optional parameter name
protected String parameterName = null;
// Possible instances of this symbol that might be instantiated
protected final List<Instance> instances = new ArrayList<Instance>();
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param symbolName Symbol name.
* @param parameterName Optional parameter label.
*/
public Arg(final String symbolName, final String parameterName)
{
this.symbolName = (symbolName == null) ? null : new String(symbolName);
this.parameterName = (parameterName == null) ? null : new String(parameterName);
//System.out.println("+ Constructed symbolName \"" + this.symbolName + "\", label=\"" + this.label + "\".");
}
//-------------------------------------------------------------------------
/**
* @return The name of the symbol.
*/
public String symbolName()
{
return symbolName;
}
/**
* @return The name of the parameter.
*/
public String parameterName()
{
return parameterName;
}
/**
* @return The instances.
*/
public List<Instance> instances()
{
return Collections.unmodifiableList(instances);
}
//-------------------------------------------------------------------------
/**
* Factory method to generate appropriate subclass for this part.
*
* @param grammar The grammar.
* @param token The token.
* @return Appropriate Arg subclass for this part.
*/
public static Arg createFromToken(final Grammar grammar, final Token token)
{
Arg arg = null;
//System.out.println("+ Creating Arg for token: " + token);
switch (token.type())
{
case Terminal:
return new ArgTerminal(token.name(), token.parameterLabel());
case Class:
arg = new ArgClass(token.name(), token.parameterLabel());
for (final Token sub : token.arguments())
// ((ArgClass)arg).argsIn().add(createFromToken(grammar, sub));
((ArgClass)arg).add(createFromToken(grammar, sub));
break;
case Array:
arg = new ArgArray(token.name(), token.parameterLabel());
for (final Token sub : token.arguments())
// ((ArgArray)arg).elements().add(createFromToken(grammar, sub));
((ArgArray)arg).add(createFromToken(grammar, sub));
break;
default:
return null;
}
return arg;
}
//-------------------------------------------------------------------------
/**
* @param grammar The grammar.
* @param report The report.
* @return Whether was able to match all symbols in Arg tree.
*/
public abstract boolean matchSymbols(final Grammar grammar, final Report report);
/**
* @param expected Class type expected for this argument.
* @param depth Depth of recursive nesting (for formatting console display messages).
* @param report
* @param callNode Call node for this object's entry in the call tree.
* @param hasCompiled Record of whether items have compiled or not at least once in some context.
* @return The compiled object(s) based on this argument and its parameters, else null if none.
*/
public abstract Object compile
(
final Class<?> expected, final int depth, final Report report,
final Call callNode, final Map<String, Boolean> hasCompiled
);
//-------------------------------------------------------------------------
/**
* @param expected Expected class to check.
* @return Whether the expected class has a matching instance.
*/
public Instance matchingInstance(final Class<?> expected)
{
if (this instanceof ArgArray)
{
// Is an array
final List<Arg> elements = ((ArgArray)this).elements();
if (elements == null || elements.isEmpty())
return null;
if
(
elements.get(0) instanceof ArgArray
&&
((ArgArray)elements.get(0)).elements() != null
&&
!((ArgArray)elements.get(0)).elements().isEmpty()
&&
((ArgArray)elements.get(0)).elements().get(0) instanceof ArgArray
)
{
// Doubly nested array
final Class<?> componentType = expected.getComponentType().getComponentType().getComponentType();
if (componentType == null)
return null;
for (final Arg element : elements)
for (final Arg element2 : ((ArgArray)element).elements())
for (final Arg element3 : ((ArgArray)element2).elements())
for (final Instance instance : element3.instances())
{
final Class<?> elementType = instance.cls();
//System.out.println("+ ArgArray elementType is " + elementType + ", componentType is " + componentType);
if (!componentType.isAssignableFrom(elementType))
continue;
return instance;
}
}
else if (elements.get(0) instanceof ArgArray)
{
// Singly nested array
if (expected.getComponentType() == null)
return null;
final Class<?> componentType = expected.getComponentType().getComponentType();
if (componentType == null)
return null;
for (final Arg element : elements)
for (final Arg element2 : ((ArgArray)element).elements())
{
if (element2 == null)
continue;
for (final Instance instance : element2.instances())
{
final Class<?> elementType = instance.cls();
//System.out.println("+ ArgArray elementType is " + elementType + ", componentType is " + componentType);
if (!componentType.isAssignableFrom(elementType))
continue;
return instance;
}
}
}
else
{
// Flat array
final Class<?> componentType = expected.getComponentType();
if (componentType == null)
return null;
for (final Arg element : elements)
for (final Instance instance : element.instances())
{
final Class<?> elementType = instance.cls();
//System.out.println("+ ArgArray elementType is " + elementType + ", componentType is " + componentType);
if (!componentType.isAssignableFrom(elementType))
continue;
return instance;
}
}
}
else
{
// Check instances
for (int inst = 0; inst < instances.size(); inst++)
{
final Instance instance = instances.get(inst);
final Class<?> cls = instance.cls();
if (cls == null)
continue;
if (!expected.isAssignableFrom(cls))
continue;
if (cls.getAnnotation(Hide.class) != null)
continue;
return instance; // matching instance found
}
}
return null; // no matching instance
}
//-------------------------------------------------------------------------
}
| 7,178 | 27.042969 | 113 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/ArgArray.java
|
package compiler;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import compiler.exceptions.CompilerException;
import compiler.exceptions.UnknownArrayErrorException;
import grammar.Grammar;
import main.grammar.Call;
import main.grammar.Report;
import main.grammar.Call.CallType;
//-----------------------------------------------------------------------------
/**
* Argument in constructor consisting of a list of arguments (of the same type).
* @author cambolbro
*/
public class ArgArray extends Arg
{
/**
* Elements will probably be constructors,
* but could possibly be a nested array.
*/
private final List<Arg> elements = new ArrayList<Arg>();
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param name The name of the argument.
* @param label the label of the argument.
*/
public ArgArray(final String name, final String label)
{
super(name, label);
}
//-------------------------------------------------------------------------
/**
* @return The elements.
*/
public List<Arg> elements()
{
return Collections.unmodifiableList(elements);
}
/**
* Add an element.
*
* @param arg The num element.
*/
public void add(final Arg arg)
{
elements.add(arg);
}
//-------------------------------------------------------------------------
@Override
public boolean matchSymbols(final Grammar grammar, final Report report)
{
for (final Arg arg : elements)
if (!arg.matchSymbols(grammar, report))
return false;
return true;
}
//-------------------------------------------------------------------------
@Override
public Object compile
(
final Class<?> expected, final int depth, final Report report,
final Call callNode, final Map<String, Boolean> hasCompiled
)
{
final String key = "Array of " + expected.getName();
if (!hasCompiled.containsKey(key))
hasCompiled.put(key, Boolean.FALSE);
String pre = "";
for (int n = 0; n < depth; n++)
pre += ". ";
pre += "[]: ";
// Create an empty array Call for this item
final Call call = (callNode == null) ? null : new Call(CallType.Array);
if (depth != -1)
{
//System.out.println("\n" + pre + "[][][][][][][][][][][][][][][][][][][][][][][][][][]");
//System.out.println(pre + "Compiling ArgArray (expected=" + expected.getName() + "):");
report.addLogLine("\n" + pre + "[][][][][][][][][][][][][][][][][][][][][][][][][][]");
report.addLogLine(pre + "Compiling ArgArray (expected=" + expected.getName() + "):");
}
final Class<?> elementType = expected.getComponentType();
if (depth != -1)
{
//System.out.println(pre + "Element type is: " + elementType);
report.addLogLine(pre + "Element type is: " + elementType);
}
if (elementType == null)
{
//throw new ArrayTypeNotFoundException(expected.getName());
return null;
}
// Create array of parameterised type.
// From: https://docs.oracle.com/javase/tutorial/reflect/special/arrayInstance.html
Object objs = null;
try
{
objs = Array.newInstance(elementType, elements.size());
for (int i = 0; i < elements.size(); i++)
{
final Arg elem = elements.get(i);
final Object match = elem.compile
(
elementType,
(depth == -1 ? -1 : depth+1),
report,
call,
hasCompiled
);
if (match == null)
{
// No match
return null;
}
Array.set(objs, i, match);
}
}
catch (final CompilerException e)
{
throw e;
}
catch(final Exception e)
{
e.printStackTrace();
throw new UnknownArrayErrorException(expected.getName(), e.getMessage());
}
final Object[] array = (Object[])objs;
if (depth != -1)
{
//System.out.println(pre + "+ Array okay, " + array.length + " elements matched.");
report.addLogLine(pre + "+ Array okay, " + array.length + " elements matched.");
}
if (callNode != null)
callNode.addArg(call);
hasCompiled.put(key, Boolean.TRUE);
return array;
//final List<Object> objects = new ArrayList<Object>();
//objects.add(array);
//return objects;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "{ ";
for (int a = 0; a < elements.size(); a++)
{
final Arg arg = elements.get(a);
str += arg.toString() + " ";
}
str += "}";
return str;
}
//-------------------------------------------------------------------------
}
| 4,787 | 24.333333 | 93 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/ArgClass.java
|
package compiler;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import annotations.Hide;
import compiler.exceptions.BadKeywordException;
import compiler.exceptions.BadSymbolException;
import compiler.exceptions.BadSyntaxException;
import compiler.exceptions.ListNotSupportedException;
import grammar.Grammar;
import main.StringRoutines;
import main.grammar.Call;
import main.grammar.Call.CallType;
import main.grammar.Instance;
import main.grammar.Report;
import main.grammar.Symbol;
import main.grammar.Symbol.LudemeType;
//-----------------------------------------------------------------------------
/**
* Arg consisting of a class constructor and its arguments.
* @author cambolbro
*/
public class ArgClass extends Arg
{
/** List of input parameters for this ludeme class class constructor. */
private final List<Arg> argsIn = new ArrayList<Arg>();
//-------------------------------------------------------------------------
/**
* Constructor
* @param name Symbol name.
* @param label Optional parameter label.
*/
public ArgClass(final String name, final String label)
{
super(name, label);
}
//-------------------------------------------------------------------------
/**
* @return The list of arguments in it.
*/
public List<Arg> argsIn()
{
return Collections.unmodifiableList(argsIn);
}
/**
* Add an element.
*
* @param arg The new element.
*/
public void add(final Arg arg)
{
argsIn.add(arg);
}
//-------------------------------------------------------------------------
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public boolean matchSymbols(final Grammar grammar, final Report report)
{
//System.out.println("At matchSymbols with symbolName: \"" + symbolName + "\".");
final char initial = symbolName.charAt(0);
if (Character.isAlphabetic(initial) && !Character.isLowerCase(initial))
throw new BadKeywordException(symbolName, "Class names should be lowercase.");
for (final Arg arg : argsIn)
arg.matchSymbols(grammar, report);
final String name = StringRoutines.upperCaseInitial(symbolName);
final List<Symbol> existing = grammar.symbolListFromClassName(name);
if (existing == null)
{
// System.out.println("** Symbol not found from \"" + keyword + "\" (original symbolName is \"" + symbolName + "\").");
// if (instances == null || instances.size() < 1)
// {
// System.out.println("** No instances!");
// }
// else
// {
// for (Instance instance : instances)
// System.out.println("** Instance is: " + instance.cls().getName());
// }
throw new BadKeywordException(name, null);
}
// Create list of instances
final List<Symbol> symbols = new ArrayList(existing);
instances.clear();
for (final Symbol symbol : symbols)
{
if (symbol == null)
throw new BadSymbolException(symbolName);
final Class<?> cls = loadClass(symbol);
if (cls == null)
{
// Probably tried to load class with same name as enum, ignore it.
// e.g. tried Mover() when it should be RoleType.Mover.
continue;
}
instances.add(new Instance(symbol, null)); //cls));
}
return true;
}
//-------------------------------------------------------------------------
/**
* Load class matching each symbol.
*/
private static Class<?> loadClass(final Symbol symbol)
{
Class<?> cls = null;
if (symbol.ludemeType() != LudemeType.Constant)
{
cls = symbol.cls();
}
// else
// {
// try { cls = Class.forName(symbol.path()); }
// catch (final ClassNotFoundException e)
// {
// // e.printStackTrace();
// }
// }
if (cls == null)
{
if (symbol.ludemeType() != LudemeType.Constant)
{
// If constant is enum, ignore class with same name
final Exception e = new Exception("Couldn't load ArgClass " + symbol.path() + ".");
e.printStackTrace();
// FIXME - should this be checked?
}
}
// else
// {
// System.out.println("cls : " + cls.getName() + "\nsymbol: " + symbol.path() + "\n");
// }
return cls;
}
//-------------------------------------------------------------------------
@Override
public Object compile
(
final Class<?> expected, final int depth, final Report report,
final Call callNode, final Map<String, Boolean> hasCompiled
)
{
String pre = "";
for (int n = 0; n < depth; n++)
pre += ". ";
pre += "C: ";
if (depth != -1)
{
report.addLogLine("\n" + pre + "==========================================");
report.addLogLine(pre + "Compiling ArgClass: " + this.symbolName);
report.addLogLine(pre + "\n" + pre + "Expected: name=" + expected.getName() + ", type=" + expected.getTypeName() + ".");
}
if (expected.getName().contains("[L"))
return null; // should not be handling arrays here
if (depth != -1)
{
report.addLogLine(pre + instances.size() + " instances:");
}
Call call = null;
for (int inst = 0; inst < instances.size(); inst++)
{
final Instance instance = instances.get(inst);
if (depth != -1)
{
report.addLogLine(pre + "-- instance " + inst + ": " + instance);
}
final Class<?> cls = instance.cls();
if (cls == null)
{
continue;
}
if (expected.isArray())
{
final Class<?> elementType = expected.getComponentType();
if (!elementType.isAssignableFrom(cls))
{
if (depth != -1)
{
report.addLogLine(pre + "Skipping non-assignable class " + cls.getName() + " (in array).");
}
continue;
}
}
else if (!expected.isAssignableFrom(cls))
{
if (depth != -1)
{
report.addLogLine(pre + "Skipping non-assignable class " + cls.getName() + ".");
}
continue;
}
if (cls.getAnnotation(Hide.class) != null)
{
// Do not compile hidden class
continue;
}
// Construct the object
Object object = null;
if (depth != -1)
{
report.addLogLine(pre + "\n" + pre + "Constructing: " + cls + "...");
}
// Ensure that an entry exist for this expected class (but beware that return type may be compiled instead).
final String key = expected.getName();
//System.out.println("AC key: " + key);
if (!hasCompiled.containsKey(key))
hasCompiled.put(key, Boolean.FALSE);
// We'll first try static construct() methods, and then constructors
for (final boolean tryConstructors : new boolean[] {false, true})
{
final List<Executable> executables = new ArrayList<Executable>();
if (tryConstructors)
{
// Get list of constructors
executables.addAll(Arrays.asList(cls.getDeclaredConstructors()));
}
else
{
// Get list of static construct() methods
final Method[] methods = cls.getDeclaredMethods();
for (final Method method : methods)
if (method.getName().equals("construct") && Modifier.isStatic(method.getModifiers()))
executables.add(method);
}
if (depth != -1)
{
report.addLogLine(pre + executables.size() + " constructors found.");
}
for (int c = 0; c < executables.size(); c++)
{
final Executable exec = executables.get(c);
if (depth != -1)
{
report.addLogLine(pre + "\n" + pre + "Constructor " + c + ": " + exec.toString());
}
if (exec.getAnnotation(Hide.class) != null)
{
// Do not compile hidden class
continue;
}
// Get argument types and annotations for this constructor's arguments
Parameter[] params = null;
Class<?>[] types = null;
Annotation[][] annos = null;
try
{
params = exec.getParameters();
types = exec.getParameterTypes();
annos = exec.getParameterAnnotations();
}
catch (final IllegalArgumentException e)
{
e.printStackTrace();
}
final int numSlots = params.length;
if (numSlots < argsIn.size())
{
if (depth != -1)
report.addLogLine(pre + "Not enough args in constructor for " + argsIn.size() + " input args.");
continue;
}
if (numSlots == 0)
{
// No arguments to match
try
{
if (tryConstructors)
object = ((Constructor<?>)exec).newInstance();
else
object = ((Method)exec).invoke(null, new Object[0]);
}
catch (final Exception e)
{
// Failed to compile.
if (depth != -1)
{
report.addLogLine(pre + "*********************");
report.addLogLine(pre + "Failed to create new instance (no args).");
report.addLogLine(pre + "*********************\n");
}
e.printStackTrace();
}
if (object != null)
{
// Success!
call = new Call(CallType.Class, instance, expected);
if (callNode != null)
callNode.addArg(call);
break; // success!
}
}
// Try to match arguments for this constructor
// Get optional and named args based on annotations
final String[] name = new String[numSlots];
int numOptional = 0;
final BitSet isOptional = new BitSet();
for (int a = 0; a < numSlots; a++)
{
name[a] = null; // just to be sure!
if (depth != -1)
{
report.addLog(pre + "- con arg " + a + ": " + types[a].getName());
}
if (types[a].getName().equals("java.util.List"))
throw new ListNotSupportedException();
for (int b = 0; b < annos[a].length; b++)
{
if
(
annos[a][b].toString().equals("@annotations.Opt()")
||
annos[a][b].toString().equals("@annotations.Or()")
||
annos[a][b].toString().equals("@annotations.Or2()")
)
{
isOptional.set(a, true);
numOptional++;
if (depth != -1)
report.addLog(" [Opt] (or an Or)");
}
else if (annos[a][b].toString().equals("@annotations.Name()"))
{
name[a] = params[a].getName();
if (Character.isUpperCase(name[a].charAt(0)))
{
// First char is capital, probably If, Else, etc.
name[a] = Character.toLowerCase(name[a].charAt(0)) + name[a].substring(1);
}
if (depth != -1)
report.addLog(" [name=" + name[a] + "]");
}
}
if (depth != -1)
report.addLogLine("");
}
if (argsIn.size() < numSlots - numOptional)
{
if (depth != -1)
report.addLogLine(pre + "Not enough input args (" + argsIn.size() + ") for non-optional constructor args (" + (numSlots - numOptional) + ").");
continue;
}
// Try possible combinations of input arguments
final Object[] argObjects = new Object[numSlots];
// Try arg combinations
final List<List<Arg>> combos = argCombos(argsIn, numSlots);
for (int cmb = 0; cmb < combos.size(); cmb++)
{
final List<Arg> combo = combos.get(cmb);
// Create a potential call for this combination
call = new Call(CallType.Class, instance, expected);
if (depth != -1)
{
report.addLog(pre);
int count = 0;
for (int n = 0; n < combo.size(); n++)
{
final Arg arg = combo.get(n);
report.addLog((arg == null ? "-" : Character.valueOf((char)('A' + count))) + " ");
if (arg != null)
count++;
}
report.addLogLine("");
}
// Attempt to match this combination of args
int slot;
// Quick pre-test: abort if any null argIn is not an optional parameter
for (slot = 0; slot < numSlots; slot++)
if (combo.get(slot) == null && !isOptional.get(slot))
break;
if (slot < numSlots)
continue;
for (slot = 0; slot < numSlots; slot++)
{
argObjects[slot] = null;
final Arg argIn = combo.get(slot);
if (depth != -1)
{
report.addLog(pre + "argIn " + slot + ": ");
report.addLogLine(argIn == null ? "null" : (argIn.symbolName() + " (" + argIn.getClass().getName() +")") + ".");
}
if (depth != -1)
{
if (argIn != null && argIn.parameterName() != null)
report.addLogLine(pre + "argIn has parameterName: " + argIn.parameterName());
}
if (argIn == null)
{
// Null placeholder for this slot
if (!isOptional.get(slot))
break;
if (callNode != null)
{
// Add null placeholder arg
call.addArg(new Call(CallType.Null));
}
}
else
{
// This argIn must compile!
if (name[slot] != null && (argIn.parameterName() == null || !argIn.parameterName().equals(name[slot])))
{
// argIn name does not match named constructor parameter
if (depth != -1)
{
report.addLogLine(pre + "- Named arg '" + name[slot] + "' in constructor does not match argIn parameterName '" + argIn.parameterName() + "'.");
}
break;
}
if (argIn.parameterName() != null && (name[slot] == null || !argIn.parameterName().equals(name[slot])))
{
// Named argIn does not match constructor parameter name
if (depth != -1)
{
report.addLogLine(pre + "- Named argIn '" + argIn.parameterName() + "' does not match parameter constructor arg label '" + name[slot] + "'.");
}
break;
}
// ArgIn must match the constructor argument for this slot!
// **
// ** Check here that candidate arg can possibly match the known arg.
// ** Small saving on time if used, but greatly reduces error log size.
// ** Doesn't work for Omega (4-player option) and Temeen Tavag (Square option).
// **
// if (argIn.matchingInstance(types[slot]) == null)
// {
// //System.out.println("++ argIn " + argIn + " doesn't match type " + types[slot]);
// break; // the arg at this slot doesn't match the required arg
// }
final Call callDummy = (callNode == null) ? null : new Call(CallType.Null);
final Object match = argIn.compile
(
types[slot],
(depth == -1 ? -1 : depth+1),
report,
callDummy,
hasCompiled
);
if (match == null)
{
// Can't compile argIn for this constructor parameter
if (depth != -1)
report.addLogLine(pre + "- Arg '" + argIn.toString() + "' doesn't match '" + types[slot] + ".");
break;
}
// Arguments match
argObjects[slot] = match;
if (callNode != null && callDummy.args().size() > 0)
{
// Add a call for this argument
final Call argCall = callDummy.args().get(0);
if (name[slot] != null)
argCall.setLabel(name[slot]);
call.addArg(argCall);
}
if (depth != -1)
{
report.addLogLine(pre + "arg " + slot + " corresponds to " + argIn + ",");
report.addLogLine(pre + " returned match " + match + " for expected " + types[slot]);
}
}
}
if (slot >= numSlots)
{
// All args match, no conflicts, all slots have a valid object or are null (and optional).
if (depth != -1)
report.addLogLine(pre + "++ Matched all input args.");
if (depth != -1)
{
report.addLogLine(pre + " Trying to create instance of " + exec.getName() + " with " + argObjects.length + " args:");
for (int o = 0; o < argObjects.length; o++)
report.addLogLine(pre + " - argObject " + o + ": " +
((argObjects[o] == null) ? "null" : argObjects[o].toString()));
}
try
{
if (tryConstructors)
object = ((Constructor<?>)exec).newInstance(argObjects);
else
object = ((Method)exec).invoke(null, argObjects);
}
catch (final Exception e)
{
// Failed to compile
// **
// ** Turn these error logs back on for full stack trace,
// ** but can be annoying as this case will legitimately
// ** occur many times for some games.
// **
//report.addLogLine("***************************");
//e.printStackTrace();
// Possibly an initialisation error, e.g. null placeholder for Integer parameter
if (depth != -1)
{
report.addLogLine(pre + "\n" + pre + "*********************");
report.addLogLine(pre + "Failed to create new instance (with args).");
report.addLogLine(pre + "Expected types:");
for (final Type type : types)
report.addLogLine(pre + "= " + type);
report.addLogLine(pre + "Actual argObjects:");
for (final Object obj : argObjects)
report.addLogLine(pre + "= " + obj);
report.addLogLine(pre + "*********************\n");
}
}
if (object != null)
{
// Successfully compiled object
if (callNode != null)
callNode.addArg(call);
break;
}
}
}
}
if (object != null)
break; // successfully compiled object
}
if (object != null)
{
//System.out.println("Compiled " + object.getClass().getName());
if (depth != -1)
{
report.addLogLine(pre + "------------------------------");
report.addLogLine(pre + "Compiled object " + object + " (key=" + key + ") successfully.");
report.addLogLine(pre + "------------------------------");
}
instance.setObject(object);
// Expected class was compiled (but possibly as return type!)
hasCompiled.put(key, Boolean.TRUE);
// Also indicate object type was compiled, to be sure.
hasCompiled.put(object.getClass().getName(), Boolean.TRUE);
//System.out.println("+ Did compile: " + key);
return object;
}
}
if (symbolName.equals("game"))
{
throw new BadSyntaxException("game", "Could not create \"game\" ludeme from description.");
}
if (symbolName.equals("match"))
{
throw new BadSyntaxException("match", "Could not create a \"match\" ludeme from description.");
}
return null; // no match found
}
//-------------------------------------------------------------------------
/**
* @param args
* @param numSlots
* @return List of possible arg combinations padded with nulls to give length.
*/
private static List<List<Arg>> argCombos(final List<Arg> args, final int numSlots)
{
final List<List<Arg>> combos = new ArrayList<List<Arg>>();
final Arg[] current = new Arg[numSlots];
for (int i = 0; i < current.length; i++)
current[i] = null;
argCombos(args, numSlots, 0, 0, current, combos);
// for (final int[] indices : Constants.combos[args.size()][numSlots])
// {
// final List<Arg> combo = new ArrayList<Arg>();
// for (int n = 0; n < numSlots; n++)
// combo.add(indices[n] == 0 ? null : args.get(indices[n]-1));
// combos.add(combo);
// }
return combos;
}
private static void argCombos
(
final List<Arg> args, final int numSlots, final int numUsed, final int slot,
final Arg[] current, final List<List<Arg>> combos
)
{
if (numUsed > args.size())
{
// Overshot -- too many null placeholders to allow all args to be placed
return;
}
if (slot == numSlots)
{
// All slots filled
if (numUsed < args.size())
return; // all args not used
// Combo completed -- store in list
final List<Arg> combo = new ArrayList<Arg>();
for (int n = 0; n < numSlots; n++)
combo.add(current[n]);
combos.add(combo);
return;
}
if (numUsed < args.size())
{
// Try next arg in next slot
current[slot] = args.get(numUsed);
argCombos(args, numSlots, numUsed+1, slot+1, current, combos);
current[slot] = null;
}
// Try null placeholder
argCombos(args, numSlots, numUsed, slot+1, current, combos);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String strT = "";
if (parameterName != null)
strT += parameterName + ":";
strT += "(" + symbolName;
if (argsIn.size() > 0)
for (final Arg arg : argsIn)
strT += " " + arg.toString();
strT += ")";
return strT;
}
//-------------------------------------------------------------------------
}
| 21,102 | 27.1749 | 158 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/ArgTerminal.java
|
package compiler;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import compiler.exceptions.TerminalNotFoundException;
//import game.functions.booleans.BooleanConstant;
//import game.functions.dim.DimConstant;
//import game.functions.floats.FloatConstant;
//import game.functions.ints.IntConstant;
import grammar.Grammar;
import main.StringRoutines;
import main.grammar.Call;
import main.grammar.Call.CallType;
import main.grammar.Instance;
import main.grammar.Report;
import main.grammar.Symbol;
import main.grammar.Symbol.LudemeType;
//-----------------------------------------------------------------------------
/**
* Token argument in constructor argument list. The token may be a:
* 1. String: in which case "str" will have surrounding quotes.
* 2. Integer: in which case it will satisfy Global.isInteger(str).
* 3. Boolean: in which case it will be "true" or "false".
* 4. Enum constant: in which case str will have at least one matching symbol in the grammar.
* @author cambolbro
*/
public class ArgTerminal extends Arg
{
//-------------------------------------------------------------------------
/**
* Constructor
* @param name Symbol name.
* @param label Optional parameter label.
*/
public ArgTerminal(final String name, final String label)
{
super(name, label);
}
//-------------------------------------------------------------------------
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public boolean matchSymbols(final Grammar grammar, final Report report)
{
Object object = null;
Symbol symbol = null;
final String className = StringRoutines.upperCaseInitial(symbolName);
final List<Symbol> match = grammar.symbolsByName(className);
final List<Symbol> symbols = (match == null) ? null : new ArrayList(match);
instances.clear();
if (symbols == null || Grammar.applicationConstantIndex(symbolName) != -1)
{
// Check if is a known type
if
(
symbolName.length() >= 2
&&
symbolName.charAt(0) == '\"'
&&
symbolName.charAt(symbolName.length() - 1) == '\"'
)
{
// Is a String
symbol = grammar.symbolsByName("String").get(0);
// System.out.println("* arg " + symbolName + " has " + instances.size() + " matches (String).");
String str = symbolName;
while (str.contains("\""))
str = str.replace("\"", "");
object = new String(str);
instances.add(new Instance(symbol, object));
}
else if
(
StringRoutines.isInteger(symbolName)
||
Grammar.applicationConstantIndex(symbolName) != -1
)
{
// Is an integer
int value;
final int acIndex = Grammar.applicationConstantIndex(symbolName);
final String valueName = (acIndex == -1) ? symbolName : Grammar.ApplicationConstants[acIndex][3];
final String constantName = (acIndex == -1) ? null : symbolName;
try
{
value = Integer.parseInt(valueName);
}
catch (NumberFormatException e)
{
e.printStackTrace();
return false;
}
catch (NullPointerException e)
{
e.printStackTrace();
return false;
}
// 1. IntConstant version
//object = new IntConstant(value);
try
{
// Load class from Core (is outside build path)
object = Class.forName("game.functions.ints.IntConstant")
.getDeclaredConstructor(int.class)
.newInstance(Integer.valueOf(value));
}
catch (Exception e)
{
e.printStackTrace();
}
symbol = grammar.symbolsByName("IntConstant").get(0);
instances.add(new Instance(symbol, object, constantName));
// 1a. DimConstant version
//object = new DimConstant(value);
try
{
// Load class from Core (is outside build path)
object = Class.forName("game.functions.dim.DimConstant")
.getDeclaredConstructor(int.class)
.newInstance(Integer.valueOf(value));
}
catch (Exception e)
{
e.printStackTrace();
}
symbol = grammar.symbolsByName("DimConstant").get(0);
instances.add(new Instance(symbol, object, constantName));
// 2. Integer version
symbol = grammar.symbolsByName("Integer").get(0);
object = Integer.valueOf(value);
instances.add(new Instance(symbol, object, constantName));
// 3. Primitive int version
symbol = grammar.symbolsByName("int").get(0);
object = Integer.valueOf(value);
instances.add(new Instance(symbol, object, constantName));
// System.out.println("* arg " + symbolName + " has " + instances.size() + " matches (value=" + value + ").");
}
else if (symbolName.equalsIgnoreCase("true") || symbolName.equalsIgnoreCase("false"))
{
// Is a boolean
boolean value = symbolName.equalsIgnoreCase("true");
// 1. BooleanConstant version
//object = BooleanConstant.construct(value);
try
{
// Load class from Core (is outside build path)
object = Class.forName("game.functions.booleans.BooleanConstant")
.getDeclaredConstructor(boolean.class)
.newInstance(Boolean.valueOf(value));
}
catch (Exception e)
{
e.printStackTrace();
}
symbol = grammar.symbolsByName("BooleanConstant").get(0);
instances.add(new Instance(symbol, object));
// 2. Boolean version
symbol = grammar.symbolsByName("Boolean").get(0);
object = Boolean.valueOf(value);
instances.add(new Instance(symbol, object));
// 3. Primitive boolean version
symbol = grammar.symbolsByName("boolean").get(0); // null;
object = Boolean.valueOf(value);
instances.add(new Instance(symbol, object));
// System.out.println("* arg " + symbolName + " has " + instances.size() + " matches (value=" + value + ").");
}
// 2. Check if is a predefined data type?
// 3. Check if is a named item?
// 4. Check if is a named ludeme?
else
{
// Can't match it with anything
// symbols = grammar.symbolMap().get("String");
// System.out.println("!! arg " + symbolName + " has no matches.");
}
if
(
StringRoutines.isFloat(symbolName)
)
{
// Is a float
float value;
final String valueName = symbolName;
try
{
value = Float.parseFloat(valueName);
}
catch (NumberFormatException e)
{
e.printStackTrace();
return false;
}
catch (NullPointerException e)
{
e.printStackTrace();
return false;
}
// 1. FloatConstant version
//object = new FloatConstant(value);
try
{
// Load class from Core (is outside build path)
object = Class.forName("game.functions.floats.FloatConstant")
.getDeclaredConstructor(float.class)
.newInstance(Float.valueOf(value));
}
catch (Exception e)
{
e.printStackTrace();
}
symbol = grammar.symbolsByName("FloatConstant").get(0);
instances.add(new Instance(symbol, object));
// 2. Float version
symbol = grammar.symbolsByName("Float").get(0);
object = Float.valueOf(value);
instances.add(new Instance(symbol, object));
// 3. Primitive float version
symbol = grammar.symbolsByName("float").get(0);
object = Float.valueOf(value);
instances.add(new Instance(symbol, object));
// System.out.println("* arg " + symbolName + " has " + instances.size() + " matches (value=" + value + ").");
}
}
else
{
// At least one matching symbol
for (final Symbol sym : symbols)
{
if (sym.ludemeType() == LudemeType.Constant)
{
// Is probably an enum
final Class<?> cls = sym.cls();
// FIXME: Add placeholder object to match number of entries in lists?
// Or add object?
if (cls == null)
{
System.out.println("** ArgTerminal: null cls, symbolName=" + symbolName + ", parameterName=" + parameterName);
report.addLogLine("** ArgTerminal: null cls, symbolName=" + symbolName + ", parameterName=" + parameterName);
}
Object[] enums = cls.getEnumConstants();
if (enums != null && enums.length > 0)
{
for (Object obj : enums)
{
// System.out.println(" obj: " + obj);
if (obj.toString().equals(sym.token()))
{
final Instance instance = new Instance(sym, obj);
instances.add(instance);
}
}
}
// if (instance.cls() != null)
// break; // success!
}
else
{
// FIXME: Check this. Should these be set by their relevant class?
}
}
}
if (instances.size() == 0)
{
// System.out.println("!! arg " + symbolName + " has no instance after matching symbols.");
return false;
}
return true;
}
//-------------------------------------------------------------------------
@Override
public Object compile
(
final Class<?> expected, final int depth, final Report report,
final Call callNode, final Map<String, Boolean> hasCompiled
)
{
final String key = expected.getName() + " (terminal)";
if (!hasCompiled.containsKey(key))
hasCompiled.put(key, Boolean.FALSE);
String pre = "";
for (int n = 0; n < depth; n++)
pre += ". ";
pre += "T: ";
if (depth != -1)
{
//System.out.println("\n" + pre + "Compiling ArgTerminal: " + toString());
//System.out.println(pre + "Trying expected type: " + expected);
report.addLogLine("\n" + pre + "Compiling ArgTerminal: " + toString());
report.addLogLine(pre + "Trying expected type: " + expected);
}
if (depth != -1)
{
for (Instance instance : instances)
{
final Symbol symbol = instance.symbol();
//System.out.println(pre + "T: > " + symbol + " (" + symbol.path() + ") " + symbol.keyword() + ".");
report.addLogLine(pre + "T: > " + symbol + " (" + symbol.path() + ") " + symbol.token() + ".");
}
}
if (depth != -1)
{
//System.out.println(pre + "Instances:");
report.addLogLine(pre + "Instances:");
}
for (int n = 0; n < instances.size(); n++)
{
final Instance instance = instances.get(n);
if (depth != -1)
{
// System.out.println
// (
// pre + "\n" + pre +
// "Instance " + n + " is " + instance.symbol().grammarLabel() +
// ": symbol=" + instance.symbol() +
// " (path=" + instance.symbol().path() + ")."
// );
report.addLogLine
(
pre + "\n" + pre +
"Instance " + n + " is " + instance.symbol().grammarLabel() +
": symbol=" + instance.symbol() +
" (path=" + instance.symbol().path() + ")."
);
}
final Class<?> cls = instance.cls();
if (depth != -1)
{
//System.out.println(pre + "- cls is: " + (cls == null ? "null" : cls.getName()));
report.addLogLine(pre + "- cls is: " + (cls == null ? "null" : cls.getName()));
}
if (cls == null)
{
//System.out.println(pre + "- unexpected null cls.");
report.addLogLine(pre + "- unexpected null cls.");
throw new TerminalNotFoundException(expected.getName());
}
if (expected.isAssignableFrom(cls))
{
//System.out.println("Terminal match: " + instance.object());
if (depth != -1)
{
//System.out.println(pre + "+ MATCH! Returning object " + instance.object());
report.addLogLine(pre + "+ MATCH! Returning object " + instance.object());
}
if (callNode != null)
{
// Create a terminal object Call for this item
final Call call = new Call(CallType.Terminal, instance, expected);
callNode.addArg(call);
}
hasCompiled.put(key, Boolean.TRUE);
return instance.object();
//final List<Object> objects = new ArrayList<Object>();
//objects.add(instance.object());
//return objects;
}
}
if (depth != -1)
{
//System.out.println(pre + "\n" + pre + "* Failed to compile ArgTerminal: " + toString());
report.addLogLine(pre + "\n" + pre + "* Failed to compile ArgTerminal: " + toString());
}
//throw new TerminalNotFoundException(expected.getName());
return null;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return (parameterName == null ? "" : parameterName + ":") + symbolName;
}
//-------------------------------------------------------------------------
}
| 12,197 | 26.977064 | 116 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/Compiler.java
|
package compiler;
import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import compiler.exceptions.CantDecomposeException;
import compiler.exceptions.CompilerErrorWithMessageException;
import compiler.exceptions.CompilerException;
import compiler.exceptions.CreationErrorWithMessageException;
import compiler.exceptions.NullGameException;
import grammar.Grammar;
import main.grammar.Call;
import main.grammar.Call.CallType;
import main.grammar.Description;
import main.grammar.Report;
import main.grammar.Symbol;
import main.grammar.Symbol.LudemeType;
import main.grammar.Token;
import main.options.UserSelections;
import parser.Parser;
//-----------------------------------------------------------------------------
/**
* Compiles game descriptions in the Ludii class grammar format to executable
* Game objects, if possible.
*
* @author cambolbro
*/
public class Compiler
{
// Avoid warning about failure to close resource
private static ClassLoader classLoader;
//-------------------------------------------------------------------------
/**
* Default private constructor; can't be called directly.
*/
private Compiler()
{
}
//-------------------------------------------------------------------------
/**
* Compile option for testing purposes. Does not interact with UI settings. Not
* for release! Create and throws away GameOptions each time.
*
* Cast the returned object to (Game) in order to use it!
*
* @param description The description.
* @param isVerbose True if this is verbose.
* @return Executable Game object if can be compiled, else null.
*/
public static Object compileTest
(
final Description description,
final boolean isVerbose
)
{
final Object game = compile
(
description,
new UserSelections(new ArrayList<String>()),
new Report(),
isVerbose
);
if (game == null)
System.out.println("** Compiler.compileTest(): Game compiled but returned null after initialisation.");
return game;
}
//-------------------------------------------------------------------------
/**
* Cast the returned object to (Game) in order to use it!
*
* @param description The description.
* @param userSelections The user selections.
* @param report The report.
* @param isVerbose True if this is verbose.
* @return Executable Game object if can be compiled, else null.
*/
public static Object compile
(
final Description description,
final UserSelections userSelections,
final Report report,
final boolean isVerbose
)
{
try
{
return compileActual(description, userSelections, report, isVerbose);
}
catch (final CompilerException e)
{
//if (isVerbose)
e.printStackTrace();
throw new CompilerException(e.getMessageBody(description.raw()), e);
}
catch (final Exception e)
{
e.printStackTrace();
throw new IllegalArgumentException(e);
}
}
//-------------------------------------------------------------------------
/**
* @return Compiled Game object else null.
*/
private static Object compileActual
(
final Description description,
final UserSelections userSelections,
final Report report,
final boolean isVerbose
)
{
if (isVerbose)
{
//System.out.println("+++++++++++++++++++++\nCompiling:\n" + description.raw());
report.addLogLine("+++++++++++++++++++++\nCompiling:\n" + description.raw());
}
// System.out.println("\nAt Compiler.compiler(), current option selections are:\n "
// + options.currentSelectionsAsString() + " => " + options.toStrings());
//final Parser parser = Parser.getParser(); //new Parser();
// if (!parser.parse(description, userSelections, isVerbose))
// throw new CompilerErrorWithMessageException("Failed to parse game description.");
Parser.expandAndParse(description, userSelections, report, true, isVerbose);
if (report.isError())
{
System.out.println("Failed to parse game description:");
for (final String error : report.errors())
{
System.out.println("* " + error);
report.addLogLine("* " + error);
}
final StringBuilder sb = new StringBuilder();
//sb.append(description.expanded());
for (final String error : report.errors())
sb.append(error + "\n");
for (final String warning : report.warnings())
sb.append("Warning: " + warning + "\n");
for (final String note : report.notes())
sb.append("Note: " + note + "\n");
throw new CompilerErrorWithMessageException(sb.toString());
//throw new RuntimeException(sb.toString());
// return null;
}
// System.out.println("Expanded description:\n" + gameDescription.expandedDescription());
// System.out.println("Metadata description:\n" + gameDescription.metadataDescription());
// boolean isMatch = false;
// final int matchAt = gameDescription.expandedDescription().indexOf("(match");
// if (matchAt >= 0)
// {
// final char ch = gameDescription.expandedDescription().charAt(matchAt + 6);
// if (!StringRoutines.isTokenChar(ch)) // avoid superstrings e.g. "(matchScore"
// isMatch = true;
// }
//Game game = null;
// Match match = null;
// if (isMatch)
// {
// // Compile match
// match = (Match)compileTask
// (
// gameDescription.expandedDescription(), "match", "game.Match", isVerbose
// );
// }
// else
// {
final Object game = compileTask
(
description.expanded(),
"game",
"game.Game",
report,
isVerbose,
description
);
if (game == null)
{
System.out.println("** Compiler.compiler(): Could not compile game.");
return null;
}
try
{
// If the report object has a messenger attached, print this message using it.
// final Method gameName = game.getClass().getMethod("name");
//
// if (report.getReportMessageFunctions() != null)
// report.getReportMessageFunctions().printMessageInStatusPanel
// (
//// "Compiled " + game.name() + " successfully.\n"
// "Compiled " + gameName.invoke(game) + " successfully.\n"
// );
// Associate the game with its description
//game.setDescription(description);
final Method gameSetDescription = game.getClass().getMethod("setDescription", Description.class);
gameSetDescription.invoke(game, description);
}
catch (final Exception e)
{
e.printStackTrace();
}
// Check that the game can be created
try
{
//game.create();
final Method gameCreate = game.getClass().getMethod("create");
gameCreate.invoke(game);
}
catch (final Error e)
{
String msg = "Error during game creation: " + e;
final boolean isStackOverflow = e.getClass().getName().contains("StackOverflowError");
if (isStackOverflow)
{
msg = "Error: Stack overflow during game creation.\n" +
"Check for recursive rules, e.g. (forEach Piece ...) within a piece.";
}
report.addError(msg);
throw new CreationErrorWithMessageException(msg);
}
catch (final Exception e)
{
e.printStackTrace();
final String msg = "Exception during game creation: " + e;
report.addError(msg);
throw new CreationErrorWithMessageException(msg);
}
// }
// System.out.println("Game created. Compiling metadata...");
// Compile metadata
//System.out.println("Compiling metadata string:\n" + parser.metadataString());
Object md = null;
if (description.metadata() != null && description.metadata() != "")
{
md = compileTask
(
description.metadata(), "metadata", "metadata.Metadata", report, isVerbose, null
);
}
if (md == null)
{
//md = new Metadata(null, null, null);
try
{
md = loadExternalClass
(
"../Core/src/metadata/",
"metadata.Metadata"
)
.getDeclaredConstructor()
.newInstance();
} catch (final Exception e)
{
e.printStackTrace();
}
}
try
{
//game.setMetadata(md);
final Method gameSetMetadata = game.getClass().getMethod("setMetadata", Object.class);
gameSetMetadata.invoke(game, md);
//game.setOptions(userSelections.selectedOptionStrings());
final Method gameSetOptions = game.getClass().getMethod("setOptions", List.class);
gameSetOptions.invoke(game, userSelections.selectedOptionStrings());
}
catch (final Exception e)
{
e.printStackTrace();
}
// System.out.println("Game is: " + game.name());
// System.out.print("Aliases are: ");
// for (final String alias : game.metadata().info().getAliases())
// System.out.print(" " + alias);
// System.out.println();
// if (game != null)
// return game;
//
// return match;
return game;
}
//-------------------------------------------------------------------------
/**
* Compiles an object from an arbitrary class from given string (in ludeme-like
* format).
*
* This method should not be used for full game objects, but only for smaller
* objects that may typically be found deeper inside Game or Metadata objects.
*
* Does not support any more advanced mechanisms like options, defines, etc.
*
* @param strIn
* @param className Fully qualified name of type of Object that we're expecting
* @param report The report.
* @return Compiled object, or null if failed to compile.
*/
public static Object compileObject
(
final String strIn,
final String className,
final Report report
)
{
final String[] classNameSplit = className.split(Pattern.quote("."));
//final String symbolName = StringRoutines.lowerCaseInitial(classNameSplit[classNameSplit.length - 1]);
final String symbolName = classNameSplit[classNameSplit.length - 1];
return compileObject(strIn, symbolName, className, report);
}
/**
* Compiles an object from an arbitrary class from given string (in ludeme-like
* format).
*
* This method should not be used for full game objects, but only for smaller
* objects that may typically be found deeper inside Game or Metadata objects.
*
* Does not support any more advanced mechanisms like options, defines, etc.
*
* @param strIn
* @param symbolName The symbol name (usually last part of className, or an
* alias)
* @param className Fully qualified name of type of Object that we're expecting
* @param report The report.
* @return Compiled object, or null if failed to compile.
*/
public static Object compileObject
(
final String strIn,
final String symbolName,
final String className,
final Report report
)
{
return compileTask(strIn, symbolName, className, report, false, null);
// final Object result = compileTask(strIn, symbolName, className, false);
// if (result == null)
// compileTask(strIn, symbolName, className, true);
// return result;
}
//-------------------------------------------------------------------------
/**
* Compile option for reconstruction testing purposes. Does not interact with UI settings. Not
* for release! Create and throws away GameOptions each time.
*
* Cast the returned object to (Game) in order to use it!
*
* @param description The description.
* @param isVerbose True if this is verbose.
* @return Executable Game object if can be compiled, else null.
*/
public static Object compileReconsTest
(
final Description description,
final boolean isVerbose
)
{
final Object game = compileRecons
(
description,
new UserSelections(new ArrayList<String>()),
new Report(),
isVerbose
);
if (game == null)
System.out.println("** Compiler.compileTest(): Game compiled but returned null after initialisation.");
return game;
}
//-------------------------------------------------------------------------
/**
* Cast the returned object to (Game) in order to use it! Do not print any exception.
*
* @param description The description.
* @param userSelections The user selections.
* @param report The report.
* @param isVerbose True if this is verbose.
* @return Executable Game object if can be compiled, else null.
*/
public static Object compileRecons
(
final Description description,
final UserSelections userSelections,
final Report report,
final boolean isVerbose
)
{
try
{
return compileActual(description, userSelections, report, isVerbose);
}
catch (final CompilerException e)
{
//if (isVerbose)
// e.printStackTrace();
throw new CompilerException(e.getMessageBody(description.raw()), e);
}
catch (final Exception e)
{
// e.printStackTrace();
throw new IllegalArgumentException(e);
}
}
//-------------------------------------------------------------------------
/**
* Compile either the Game object or the Metadata object.
* @return Compiled object, else null if error.
*/
private static Object compileTask
(
final String strIn,
final String symbolName,
final String className,
final Report report,
final boolean isVerbose,
final Description description
)
{
// /**
// * List of ludemes to ignore if found not to compile. These are typically
// * ludemes automatically generated as defaults for enclosing ludemes
// * that can but do not actually appear in the game description.
// */
// final Map<String, String> ignoreNonCompiledLudemes = new HashMap<String, String>();
// {
//// ignoreNonCompiledLudemes.put("java.lang.Integer", "java.lang.Integer");
//// ignoreNonCompiledLudemes.put("java.lang.String", "java.lang.String");
//// ignoreNonCompiledLudemes.put("game.rules.meta.Meta", "game.rules.meta.Meta");
//// ignoreNonCompiledLudemes.put("game.util.moves.Player", "game.util.moves.Player");
//// ignoreNonCompiledLudemes.put("game.util.moves.From", "game.util.moves.From");
//// ignoreNonCompiledLudemes.put("game.util.moves.To", "game.util.moves.To");
//// ignoreNonCompiledLudemes.put("game.util.moves.Between", "game.util.moves.Between");
//// ignoreNonCompiledLudemes.put("game.util.moves.Flips", "game.util.moves.Flips");
//// ignoreNonCompiledLudemes.put("game.util.moves.Piece", "game.util.moves.Piece");
//// ignoreNonCompiledLudemes.put("game.rules.start.Start", "game.rules.start.Start");
//// ignoreNonCompiledLudemes.put("game.mode.Mode", "game.mode.Mode");
//// ignoreNonCompiledLudemes.put("game.functions.intArray.state.Rotations", "game.functions.intArray.state.Rotations");
//// ignoreNonCompiledLudemes.put("metadata.graphics.Graphics", "metadata.graphics.Graphics");
//// ignoreNonCompiledLudemes.put("metadata.ai.heuristics.Heuristics", "metadata.ai.heuristics.Heuristics");
//// ignoreNonCompiledLudemes.put("game.equipment.container.board.Track", "game.equipment.container.board.Track");
// //ignoreNonCompiledLudemes.put("", "");
// //ignoreNonCompiledLudemes.put("", "");
// //ignoreNonCompiledLudemes.put("", "");
// };
//System.out.println("parser.metadataString:\n" + parser.metadataString());
// System.out.println("\nCompiling description starting: " + strIn.substring(0, 20));
// System.out.println("symbolName is: " + symbolName);
final Token tokenTree = new Token(strIn, report);
if (isVerbose)
{
//System.out.println("\nCompiler.compileTask() token tree:\n" + tokenTree);
report.addLogLine("\nCompiler.compileTask() token tree:\n" + tokenTree);
}
if (tokenTree.type() == null)
{
//System.out.println("** Compiler.compileTask(): Null token tree.");
report.addLogLine("** Compiler.compileTask(): Null token tree.");
if (symbolName.equals("game")) // || symbolName.equals("match"))
throw new CantDecomposeException("CompilercompileTask()"); // must have a game object!
else
return null; // may be no metadata
}
final ArgClass rootClass = (ArgClass)Arg.createFromToken(Grammar.grammar(), tokenTree);
if (rootClass == null)
throw new NullGameException();
if (isVerbose)
{
//System.out.println("\nRoot:" + rootClass);
report.addLogLine("\nRoot:" + rootClass);
}
// Eric: commented for the match
// if (!rootClass.symbolName().equals(symbolName))
// {
// System.out.println("rootClass is: " + rootClass.symbolName() + ", symbolName is: " + symbolName);
// throw new BadRootException(rootClass.symbolName(), symbolName);
// }
final Grammar grammar = Grammar.grammar();
if (!rootClass.matchSymbols(grammar, report))
{
System.out.println("Compiler.compileTask(): Failed to match symbols.");
report.addLogLine("Compiler.compileTask(): Failed to match symbols.");
throw new CompilerErrorWithMessageException("Failed to match symbols when compiling.");
}
// Attempt to compile the game
Class<?> clsRoot = null;
try
{
clsRoot = Class.forName(className);
} catch (final ClassNotFoundException e)
{
e.printStackTrace();
}
// Create call tree with dummy root
Call callTree = (description == null) ? null : new Call(CallType.Null);
final Map<String, Boolean> hasCompiled = new HashMap<>();
final Object result = rootClass.compile(clsRoot, (isVerbose ? 0 : -1), report, callTree, hasCompiled);
// Check fragments that did not compile
for (final Map.Entry<String, Boolean> entry : hasCompiled.entrySet())
{
//System.out.println("key: " + entry.getKey());
if (entry.getValue() == Boolean.TRUE)
continue; // item did compile
final String path = entry.getKey();
// if (ignoreNonCompiledLudemes.containsKey(path))
// continue; // ignore certain classes
final Symbol symbol = grammar.findSymbolByPath(path);
if (symbol == null) // || !symbol.usedInDescription())
continue; // is probably a primitive type or structural <rule> ludeme
if (symbol.ludemeType() == LudemeType.Structural)
continue; // don't include structural ludemes
//System.out.println(path);
//System.out.println("symbol: " + symbol + ", name: " + symbol.name());
// final Boolean check = hasCompiled.get(symbol.returnType().cls().getName());
// if (check == Boolean.TRUE)
// continue; // symbol's return type compiled successfully
System.out.println("** Could not compile " + path + ".");
report.addWarning("Could not compile " + path + ".");
//report.addError("Could not compile " + path + ".");
//report.addLogLine("Could not compile " + path + ".");
if (report.getReportMessageFunctions() != null)
report.getReportMessageFunctions().printMessageInStatusPanel("WARNING: Could not compile " + path + ".\n");
}
if (description != null)
{
// Remove dummy root from call tree and store it
if (callTree == null || callTree.args().isEmpty())
System.out.println("Compiler.compileTask: Bad call tree.");
callTree = callTree.args().isEmpty() ? null : callTree.args().get(0);
description.setCallTree(callTree);
//System.out.println(description.callTree());
// callTree.export("call-tree-" + ((Game)result).name() + ".txt");
}
if (isVerbose)
System.out.println(report.log());
if (result == null)
{
//System.out.println("Compiler.compileTask(): Null result from compiling root ArgClass object.");
report.addLogLine("Compiler.compileTask(): Null result from compiling root ArgClass object.");
throw new NullGameException();
}
//System.out.println("Compiled task:\n" + result.toString());
return result;
}
//-------------------------------------------------------------------------
public static Class<?> loadExternalClass(final String folderPath, final String classPath)
{
Class<?> cls = null;
final String relPath = folderPath.replace('.', '/');
// Create a File object on the root of the directory containing the class file
final File file = new File(relPath); //folderPath);
try
{
// Convert File to a URL
final URL url = file.toURI().toURL();
final URL[] urls = new URL[] { url };
classLoader = new URLClassLoader(urls, Compiler.class.getClassLoader());
// Load in the class; MyClass.class should be located in
// the directory file:/c:/myclasses/com/mycompany
cls = classLoader.loadClass(classPath);
}
catch (final MalformedURLException e)
{
e.printStackTrace();
}
catch (final ClassNotFoundException e)
{
e.printStackTrace();
}
return cls;
}
//-------------------------------------------------------------------------
}
| 20,745 | 30.338369 | 122 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/ArrayTypeNotFoundException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class ArrayTypeNotFoundException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String expectedType;
/**
* @param expectedType
*/
public ArrayTypeNotFoundException(final String expectedType)
{
super();
this.expectedType = expectedType;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, expectedType, "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "The array type " + expectedType + " was not found.";
}
}
| 1,043 | 19.470588 | 88 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/BadArrayElementException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class BadArrayElementException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String expectedType;
private final String elementType;
/**
* @param expectedType
* @param elementType
*/
public BadArrayElementException(final String expectedType, final String elementType)
{
super();
this.expectedType = expectedType;
this.elementType = elementType;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, elementType, "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "Array element of type " + elementType + " but type " + expectedType + " expected.";
}
}
| 1,188 | 21.018519 | 93 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/BadComponentException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class BadComponentException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String badComponentName;
/**
* @param badComponentName
*/
public BadComponentException(final String badComponentName)
{
super();
this.badComponentName = StringRoutines.toDromedaryCase(badComponentName);
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, badComponentName, "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "The component " + badComponentName + " is not defined. Try appending the player index.";
}
}
| 1,125 | 21.078431 | 98 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/BadImportException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class BadImportException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String badFile;
/**
* @param badFile
*/
public BadImportException(final String badFile)
{
super();
this.badFile = badFile;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, badFile, "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "Failed to import " + badFile + ".";
}
}
| 980 | 18.235294 | 83 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/BadKeywordException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class BadKeywordException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String badKeyword;
private final String message;
/**
* @param badKeyword
* @param message
*/
public BadKeywordException(final String badKeyword, final String message)
{
super();
this.badKeyword = badKeyword; //StringRoutines.toDromedaryCase(badKeyword);
this.message = message;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, badKeyword, "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
String str = "The keyword \"" + badKeyword + "\" cannot be recognised.";
if (message != null)
str += " " + message;
return str;
}
}
| 1,239 | 20.37931 | 86 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/BadRangeException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class BadRangeException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final int limit;
/**
* @param limit
*/
public BadRangeException(final int limit)
{
super();
this.limit = limit;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, "..", "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "A range \"..\" has exceeded the limit " + limit + ".";
}
}
| 978 | 18.196078 | 80 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/BadRootException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class BadRootException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String badRoot;
private final String expectedRoot;
/**
* @param badRoot
* @param expectedRoot
*/
public BadRootException(final String badRoot, final String expectedRoot)
{
super();
this.badRoot = badRoot;
this.expectedRoot = expectedRoot;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, badRoot, "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "Root " + badRoot + " found rather than expected root " + expectedRoot + ".";
}
}
| 1,141 | 19.763636 | 86 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/BadSymbolException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class BadSymbolException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String badSymbol;
/**
* @param badSymbol
*/
public BadSymbolException(final String badSymbol)
{
super();
this.badSymbol = badSymbol;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, badSymbol, "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "An error occurred when matching " + badSymbol + ".";
}
}
| 1,009 | 18.803922 | 85 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/BadSyntaxException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class BadSyntaxException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String keyword;
private final String message;
/**
* @param keyword
* @param message
*/
public BadSyntaxException(final String keyword, final String message)
{
super();
this.keyword = keyword;
this.message = message;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(keyword == null ? safeDescription : StringRoutines.highlightText(safeDescription, keyword, "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "Syntax error: " + message;
}
}
| 1,105 | 19.481481 | 119 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/CantCompileException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
* @author cambolbro
*/
public class CantCompileException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String badKeyword;
/**
* @param badKeyword
*/
public CantCompileException(final String badKeyword)
{
super();
this.badKeyword = StringRoutines.toDromedaryCase(badKeyword);
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, badKeyword, "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "Can't compile the ludeme \"" + badKeyword + "\".";
}
}
| 1,045 | 19.92 | 86 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/CantDecomposeException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class CantDecomposeException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String source;
/**
* @param source
*/
public CantDecomposeException(final String source)
{
super();
this.source = source;
}
@Override
public String getMessageBody(final String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(safeDescription);
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return source + ": The game description could not be decomposed into parts.";
}
}
| 971 | 17.692308 | 79 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/CompilerErrorWithMessageException.java
|
package compiler.exceptions;
//-----------------------------------------------------------------------------
/**
*
* @author cambolbro
*/
public class CompilerErrorWithMessageException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String message;
/**
* @param message
*/
public CompilerErrorWithMessageException(final String message)
{
super();
this.message = message;
}
@Override
public String getMessageBody(String gameDescription)
{
final StringBuilder sb = new StringBuilder();
// final String safeDescription = StringRoutines.escapeText(gameDescription);
// sb.append("<html>");
// sb.append("<h2>");
// sb.append(getMessageTitle());
// sb.append("</h2>");
// sb.append("<br/>");
// sb.append("<p>");
// sb.append(safeDescription);
// sb.append("</p>");
// sb.append("</html>");
sb.append(message);
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return message;
}
}
| 1,026 | 18.018519 | 79 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/CompilerException.java
|
package compiler.exceptions;
/**
* Compiler-specific exception hierarchy.
* @author cambolbro, mrraow
*/
public class CompilerException extends RuntimeException
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param messageBody
* @param e
*/
public CompilerException(String messageBody, CompilerException e)
{
super(messageBody, e);
}
/**
*
*/
public CompilerException()
{
super();
}
/**
* @param gameDescription The description of the game.
*
* @return The body message.
*/
public String getMessageBody(final String gameDescription)
{
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(gameDescription);
sb.append("</p>");
sb.append("</html>");
return sb.toString();
}
/**
* @return The message of the title.
*/
@SuppressWarnings("static-method")
public String getMessageTitle()
{
return "A compiler error has occurred.";
}
}
| 1,134 | 17.306452 | 76 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/CreationErrorWithMessageException.java
|
package compiler.exceptions;
/**
*
* @author cambolbro
*/
public class CreationErrorWithMessageException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String message;
/**
* @param message
*/
public CreationErrorWithMessageException(final String message)
{
super();
this.message = message;
}
@Override
public String getMessageBody(String gameDescription)
{
final StringBuilder sb = new StringBuilder();
sb.append(message);
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return message;
}
}
| 631 | 14.8 | 72 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/DefineExpansionException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class DefineExpansionException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String message;
/**
* @param msg
*/
public DefineExpansionException(final String msg)
{
super();
this.message = msg;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, "define", "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return message;
}
}
| 954 | 17.72549 | 84 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/InvalidOptionException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
* @author mrraow
*/
public class InvalidOptionException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String message;
/**
* @param message The message.
*/
public InvalidOptionException(final String message)
{
super();
this.message = message;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(safeDescription);
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return message;
}
}
| 912 | 17.26 | 76 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/ListNotSupportedException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class ListNotSupportedException extends CompilerException
{
private static final long serialVersionUID = 1L;
/**
* An exception for the not supported symbols.
*/
public ListNotSupportedException()
{
super();
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, "List", "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "List<> not supported as ludeme constructor argument.";
}
}
| 964 | 18.693878 | 82 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/NullGameException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class NullGameException extends CompilerException
{
private static final long serialVersionUID = 1L;
/**
* An exception for a null game.
*/
public NullGameException()
{
super();
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, "game", "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "The game could not be compiled, but no specific error was identified.";
}
}
| 951 | 18.428571 | 82 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/ParserException.java
|
package compiler.exceptions;
/**
* Parser-specific exception hierarchy.
* @author cambolbro, mrraow
*/
public class ParserException extends RuntimeException
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param messageBody The message.
* @param e The exception.
*/
public ParserException(String messageBody, ParserException e)
{
super(messageBody, e);
}
/**
*
*/
public ParserException()
{
super();
}
/**
* @param gameDescription The game description.
* @return The message to print.
*/
public String getMessageBody(final String gameDescription)
{
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(gameDescription);
sb.append("</p>");
sb.append("</html>");
return sb.toString();
}
/**
* @return The title of the message.
*/
@SuppressWarnings("static-method")
public String getMessageTitle()
{
return "A parser error has occurred.";
}
}
| 1,152 | 17.901639 | 76 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/TerminalNotFoundException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class TerminalNotFoundException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String badTerminal;
/**
*
* @param badTerminal
*/
public TerminalNotFoundException(final String badTerminal)
{
super();
this.badTerminal = badTerminal;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, badTerminal, "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "The keyword " + badTerminal + " cannot be recognised.";
}
}
| 1,043 | 19.076923 | 87 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/UnclosedClauseException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class UnclosedClauseException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String badClause;
/**
* @param badClause
*/
public UnclosedClauseException(final String badClause)
{
super();
this.badClause = badClause;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, badClause, "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "The clause \"" + badClause + "\" was not closed.";
}
}
| 1,017 | 18.960784 | 85 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/UnexpectedArrayException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class UnexpectedArrayException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String expectedType;
/**
* @param expectedType
*/
public UnexpectedArrayException(final String expectedType)
{
super();
this.expectedType = expectedType;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, expectedType, "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "An array of type " + expectedType + " was found when expecting a different type.";
}
}
| 1,069 | 19.980392 | 92 |
java
|
Ludii
|
Ludii-master/Language/src/compiler/exceptions/UnknownArrayErrorException.java
|
package compiler.exceptions;
import main.StringRoutines;
/**
*
* @author cambolbro
*/
public class UnknownArrayErrorException extends CompilerException
{
private static final long serialVersionUID = 1L;
private final String expectedType;
private final String message;
/**
* @param expectedType
* @param message
*/
public UnknownArrayErrorException(final String expectedType, final String message)
{
super();
this.expectedType = expectedType;
this.message = message;
}
@Override
public String getMessageBody(String gameDescription)
{
final String safeDescription = StringRoutines.escapeText(gameDescription);
final StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<h2>");
sb.append(getMessageTitle());
sb.append("</h2>");
sb.append("<br/>");
sb.append("<p>");
sb.append(StringRoutines.highlightText(safeDescription, expectedType, "font", "red"));
sb.append("</p>");
sb.append("</html>");
System.out.println(sb);
return sb.toString();
}
@Override
public String getMessageTitle()
{
return "An array of type " + expectedType + " suffered an unexpected error " + message + ". We apologise for any inconvenience";
}
}
| 1,209 | 21.407407 | 130 |
java
|
Ludii
|
Ludii-master/Language/src/completer/Completer.java
|
package completer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import main.StringRoutines;
import main.grammar.Define;
import main.grammar.Report;
import parser.Expander;
//-----------------------------------------------------------------------------
/**
* Completes partial game descriptions ready for expansion.
* @author cambolbro
*/
public class Completer
{
public static final char CHOICE_DIVIDER_CHAR = '|';
private static final int MAX_PARENTS = 10;
private static final int MAX_RANGE = 1000;
//-------------------------------------------------------------------------
public static boolean needsCompleting(final String desc)
{
// Remove comments first, so that recon syntax can be commented out
// to not trigger a reconstruction without totally removing it.
final String str = Expander.removeComments(desc);
return str.contains("[") && str.contains("]");
}
//-------------------------------------------------------------------------
/**
* Creates all completions exhaustively.
* @param raw Partial raw game description.
* @param maxCompletions Maximum number of completions to make (default is 1, e.g. for Travis tests).
* @param report Report log for warnings and errors.
* @return List of completed (raw) game descriptions ready for expansion and parsing.
*/
public static List<Completion> completeExhaustive(final String raw, final int maxCompletions, final Report report)
{
System.out.println("Completer.complete(): Completing at most " + maxCompletions + " descriptions...");
final List<Completion> completions = new ArrayList<Completion>();
// Create list of alternative Descriptions, as each will need to be expanded
final Map<String, String> ludMap = getAllLudContents();
final Map<String, String> defMap = getAllDefContents();
final List<Completion> queue = new ArrayList<Completion>();
queue.add(new Completion(new String(raw)));
while (!queue.isEmpty())
{
final Completion comp = queue.remove(0);
if (!needsCompleting(comp.raw()))
{
// Completed!
completions.add(comp);
if (completions.size() >= maxCompletions)
return completions;
continue;
}
// Complete the next completion clause
nextCompletionExhaustive(comp, queue, ludMap, defMap, report);
}
return completions;
}
//-------------------------------------------------------------------------
/**
* Process next completion and add results to queue.
* Completes in order according to next available valid completion.
* @param queue
* @param report
*/
public static void nextCompletionExhaustive
(
final Completion completion, final List<Completion> queue,
final Map<String, String> ludMap, final Map<String, String> defMap,
final Report report
)
{
System.out.println("Completing next completion for raw string:\n" + completion.raw());
final String raw = completion.raw();
// Find opening and closing bracket locations
final int from = raw.indexOf("[");
final int to = StringRoutines.matchingBracketAt(raw, from);
// Get reconstruction clause (substring within square brackets)
final String left = raw.substring(0, from);
final String clause = raw.substring(from + 1, to);
final String right = raw.substring(to + 1);
//System.out.println("left is: " + left);
//System.out.println("clause is: " + clause);
//System.out.println("right is: " + right);
// Determine left and right halves of parents
final List<String[]> parents = determineParents(left, right);
// System.out.println("Parents:\n");
// for (final String[] parent : parents)
// System.out.println(parent[0] + "?" + parent[1] + "\n");
final List<String> choices = extractChoices(clause);
final List<String> inclusions = new ArrayList<String>();
final List<String> exclusions = new ArrayList<String>();
//final List<String> enumerations = new ArrayList<String>();
int enumeration = 0;
for (int c = choices.size() - 1; c >= 0; c--)
{
final String choice = choices.get(c);
//System.out.println("choice is: " + choice);
if
(
choice.length() > 3 && choice.charAt(0) == '['
&&
choice.charAt(1) == '+' && choice.charAt(choice.length() - 1) == ']'
)
{
// Is an inclusion
inclusions.add(choice.substring(2, choice.length() - 1).trim());
choices.remove(c);
}
else if
(
choice.length() > 3 && choice.charAt(0) == '['
&&
choice.charAt(1) == '-' && choice.charAt(choice.length() - 1) == ']'
)
{
// Is an exclusion
exclusions.add(choice.substring(2, choice.length() - 1).trim());
choices.remove(c);
}
else if
(
choice.length() >= 1 && choice.charAt(0) == '#'
||
choice.length() >= 3 && choice.charAt(0) == '['
&&
choice.charAt(1) == '#' && choice.charAt(choice.length() - 1) == ']'
)
{
// Is an enumeration
//enumerations.add(choice.substring(1, choice.length() - 1).trim());
enumeration = numHashes(choice);
//System.out.println("Enumeration has " + enumeration + " hashes...");
choices.remove(c);
}
}
if (enumeration > 0)
{
// Enumerate on parents
final String[] parent = parents.get(enumeration - 1);
//System.out.println("Enumerating on parent " + enumeration + ": " + parent[0] + "?" + parent[1]);
enumerateMatches(left, right, parent, ludMap, queue, completion.score());
enumerateMatches(left, right, parent, defMap, queue, completion.score());
}
else
{
// Handle choices as usual
for (int n = 0; n < choices.size(); n++)
{
final String choice = choices.get(n);
if (!exclusions.isEmpty())
{
// Check whether this choice contains excluded text
boolean found = false;
for (final String exclusion : exclusions)
if (choice.contains(exclusion))
{
found = true;
break;
}
if (found)
continue; // excluded text is present
}
if (!inclusions.isEmpty())
{
// Check that this choice contains included text
boolean found = false;
for (final String inclusion : inclusions)
if (choice.contains(inclusion))
{
found = true;
break;
}
if (!found)
continue; // included text is not present
}
final String str = raw.substring(0, from) + choice + raw.substring(to + 1);
final Completion newCompletion = new Completion(str);
// System.out.println("\n**********************************************************");
// System.out.println("completion " + n + "/" + choices.size() + " is:\n" + completion);
queue.add(newCompletion);
}
}
}
//-------------------------------------------------------------------------
/**
* Creates list of completions irrespective of previous completions.
* @param raw Partial raw game description.
* @param maxCompletions Maximum number of completions to make (default is 1, e.g. for Travis tests).
* @param report Report log for warnings and errors.
* @return List of completed (raw) game descriptions ready for expansion and parsing.
*/
public static List<Completion> completeSampled(final String raw, final int maxCompletions, final Report report)
{
// System.out.println("\nCompleter.complete(): Completing at most " + maxCompletions + " descriptions...");
final List<Completion> completions = new ArrayList<Completion>();
// Create list of alternative Descriptions, as each will need to be expanded
final Map<String, String> ludMap = getAllLudContents();
final Map<String, String> defMap = getAllDefContents();
for (int n = 0; n < maxCompletions; n++)
{
Completion comp = new Completion(new String(raw));
while (needsCompleting(comp.raw()))
comp = nextCompletionSampled(comp, ludMap, defMap, report);
completions.add(comp);
}
// System.out.println("\nList of completions:");
// for (final Completion comp : completions)
// System.out.println(comp.raw());
return completions;
}
//-------------------------------------------------------------------------
/**
* Process next completion and add results to queue.
* Solves the next completion independently by sampling from candidates.
* @param report
*/
public static Completion nextCompletionSampled
(
final Completion completion,
final Map<String, String> ludMap, final Map<String, String> defMap,
final Report report
)
{
// System.out.println("\nCompleting next completion for raw string:\n" + completion.raw());
final Random rng = new Random();
final List<Completion> completions = new ArrayList<Completion>();
// Find opening and closing bracket locations
final String raw = Expander.removeComments(completion.raw());
final int from = raw.indexOf("[");
final int to = StringRoutines.matchingBracketAt(raw, from);
// Get reconstruction clause (substring within square brackets)
final String left = raw.substring(0, from);
final String clause = raw.substring(from + 1, to);
final String right = raw.substring(to + 1);
//System.out.println("left is: " + left);
//System.out.println("clause is: " + clause);
//System.out.println("right is: " + right);
// Determine left and right halves of parents
final List<String[]> parents = determineParents(left, right);
// System.out.println("Parents:\n");
// for (final String[] parent : parents)
// System.out.println(parent[0] + "?" + parent[1] + "\n");
final List<String> choices = extractChoices(clause);
final List<String> inclusions = new ArrayList<String>();
final List<String> exclusions = new ArrayList<String>();
//final List<String> enumerations = new ArrayList<String>();
int enumeration = 0;
for (int c = choices.size() - 1; c >= 0; c--)
{
final String choice = choices.get(c);
//System.out.println("choice is: " + choice);
if
(
choice.length() > 3 && choice.charAt(0) == '['
&&
choice.charAt(1) == '+' && choice.charAt(choice.length() - 1) == ']'
)
{
// Is an inclusion
inclusions.add(choice.substring(2, choice.length() - 1).trim());
choices.remove(c);
}
else if
(
choice.length() > 3 && choice.charAt(0) == '['
&&
choice.charAt(1) == '-' && choice.charAt(choice.length() - 1) == ']'
)
{
// Is an exclusion
exclusions.add(choice.substring(2, choice.length() - 1).trim());
choices.remove(c);
}
else if
(
choice.length() >= 1 && choice.charAt(0) == '#'
||
choice.length() >= 3 && choice.charAt(0) == '['
&&
choice.charAt(1) == '#' && choice.charAt(choice.length() - 1) == ']'
)
{
// Is an enumeration
//enumerations.add(choice.substring(1, choice.length() - 1).trim());
enumeration = numHashes(choice);
//System.out.println("Enumeration has " + enumeration + " hashes...");
choices.remove(c);
}
}
if (enumeration > 0)
{
// Enumerate on parents
final String[] parent = parents.get(enumeration - 1);
// System.out.println("\nEnumerating on parent " + enumeration + ": \"" + parent[0] + "\" + ? + \"" + parent[1] + "\"");
enumerateMatches(left, right, parent, ludMap, completions, completion.score());
enumerateMatches(left, right, parent, defMap, completions, completion.score());
}
else
{
// Handle choices as usual
for (int n = 0; n < choices.size(); n++)
{
final String choice = choices.get(n);
if (!exclusions.isEmpty())
{
// Check whether this choice contains excluded text
boolean found = false;
for (final String exclusion : exclusions)
if (choice.contains(exclusion))
{
found = true;
break;
}
if (found)
continue; // excluded text is present
}
if (!inclusions.isEmpty())
{
// Check that this choice contains included text
boolean found = false;
for (final String inclusion : inclusions)
if (choice.contains(inclusion))
{
found = true;
break;
}
if (!found)
continue; // included text is not present
}
final String str = raw.substring(0, from) + choice + raw.substring(to + 1);
final Completion newCompletion = new Completion(str);
// System.out.println("\n**********************************************************");
// System.out.println("completion " + n + "/" + choices.size() + " is:\n" + completion);
//queue.add(newCompletion);
completions.add(newCompletion);
}
}
if (completions.isEmpty())
{
// No valid completions for this completion point
if (report != null)
report.addError("No completions for: " + raw);
return null;
// **
// ** TODO: Choose preferred completion based on context.
// **
// ** TODO: Maybe use UCB to balance reward with novelty, i.e. prefer
// ** high scoring candidates but not the same ones every time,
// ** also try low scoring ones occasionally.
// **
}
return completions.get(rng.nextInt(completions.size()));
}
//-------------------------------------------------------------------------
/**
* Enumerate all parent matches in the specified map.
* @param parent
* @param map
* @param queue
*/
private static void enumerateMatches
(
final String left, final String right, final String[] parent,
final Map<String, String> map, final List<Completion> queue,
final double confidence
)
{
for (Map.Entry<String, String> entry : map.entrySet())
{
final String otherDescription = entry.getValue();
final String candidate = new String(otherDescription);
// **
// ** TODO: Determine distance between map entry and this completion
// **
final double distance = 0.1; // dummy value for testing
final int l = candidate.indexOf(parent[0]);
if (l < 0)
continue; // not a match
String secondPart = candidate.substring(l + parent[0].length()); //.trim();
// System.out.println("\notherDescription is: " + otherDescription);
// System.out.println("parent[0] is: " + parent[0]);
// System.out.println("parent[1] is: " + parent[1]);
// System.out.println("secondPart is: " + secondPart);
// System.out.println("left is: " + left);
// System.out.println("right is: " + right);
// final int r = secondPart.indexOf(parent[1]);
final int r = (StringRoutines.isBracket(secondPart.charAt(0)))
? StringRoutines.matchingBracketAt(secondPart, 0)
: secondPart.indexOf(parent[1]) - 1;
if (r >= 0)
{
// Is a match
//final String match = mapString.substring(l, l + parent[0].length() + r + parent[1].length());
final String match = secondPart.substring(0, r + 1); //l, l + parent[0].length() + r + parent[1].length());
//System.out.println("match is: " + match);
// final String str =
// left.substring(0, left.length() - parent[0].length())
// +
// match
// +
// right.substring(parent[1].length());
//final String str = left + " " + match + " " + right;
String str = left + match + right;
// Eric: I COMMENTED THIS, BECAUSE this code is making an infinite loop on some cases and break Travis.
//str = addLocalDefines(str, otherDescription);
final Completion completion = new Completion(str);
//System.out.println("completion is:\n" + completion.raw());
if (!queue.contains(completion))
{
//System.out.println("Adding completion:\n" + completion.raw());
completion.setScore(confidence * (1 - distance));
queue.add(completion);
}
}
}
}
//-------------------------------------------------------------------------
/**
* @return Completed string with all necessary local defines added.
*/
static String addLocalDefines(final String current, final String otherDescription)
{
// Make a list of local defines in the current description
final List<Define> localDefinesCurrent = new ArrayList<Define>();
Expander.extractDefines(current, localDefinesCurrent, null);
// System.out.println("Local defines (current):");
// for (final Define def : localDefinesCurrent)
// System.out.println("-- " + def.formatted());
// Make a list of local defines in the other description
final List<Define> localDefinesOther = new ArrayList<Define>();
Expander.extractDefines(otherDescription, localDefinesOther, null);
// System.out.println("Local defines (other):");
// for (final Define def : localDefinesOther)
// System.out.println("-- " + def.formatted());
// Determine which defines from the other description are used in the current description
final BitSet used = new BitSet();
for (int n = 0; n < localDefinesOther.size(); n++)
if (current.contains(localDefinesOther.get(n).tag()))
used.set(n);
// Turn off the ones already present in the current description
for (int n = 0; n < localDefinesCurrent.size(); n++)
{
if (!used.get(n))
continue; // not used
final Define localDefineCurrent = localDefinesCurrent.get(n);
boolean found = false;
for (int o = 0; o < localDefinesOther.size() && !found; o++)
{
final Define localDefineOther = localDefinesOther.get(o);
if (localDefineOther.tag().equals(localDefineCurrent.tag()))
found = true;
}
if (found)
used.set(n, false); // turn it off again
}
// Prepend used defines to the current string
String result = new String(current);
for (int n = used.nextSetBit(0); n >= 0; n = used.nextSetBit(n + 1))
result = localDefinesOther.get(n).formatted() + result;
return result;
}
//-------------------------------------------------------------------------
/**
* @return Number of hash characters '#' in string.
*/
private static int numHashes(final String str)
{
int numHashes = 0;
for (int c = 0; c < str.length(); c++)
if (str.charAt(c) == '#')
numHashes++;
return numHashes;
}
//-------------------------------------------------------------------------
/**
* @return List of successively nested parents based on left and right substrings.
*/
private static final List<String[]> determineParents
(
final String left, final String right
)
{
final List<String[]> parents = new ArrayList<String[]>();
// Step backwards to previous bracket on left side
int l = left.length() - 1;
int r = 0;
boolean lZero = false;
boolean rEnd = false;
for (int p = 0; p < MAX_PARENTS; p++)
{
// Step backwards to previous "("
while (l > 0 && left.charAt(l) != '(' && left.charAt(l) != '{')
{
// Step past embedded clauses
if (left.charAt(l) == ')' || left.charAt(l) == '}')
{
int depth = 1;
while (l >= 0 && depth > 0)
{
l--;
if (l < 0)
break;
if (left.charAt(l) == ')' || left.charAt(l) == '}')
depth++;
else if (left.charAt(l) == '(' || left.charAt(l) == '{')
depth--;
}
}
else
{
l--;
}
}
if (l > 0)
l--;
if (l == 0)
{
if (lZero)
break;
lZero = true;
}
if (l < 0)
break;
// Step forwards to next bracket on right side
boolean curly = left.charAt(l + 1) == '{';
while
(
r < right.length()
&&
(
!curly && right.charAt(r) != ')'
||
curly && right.charAt(r) != '}'
)
)
{
// Step past embedded clauses
if (right.charAt(r) == '(' || right.charAt(r) == '{')
{
int depth = 1;
while (r < right.length() && depth > 0)
{
r++;
if (r >= right.length())
break;
if (right.charAt(r) == '(' || right.charAt(r) == '{')
depth++;
else if (right.charAt(r) == ')' || right.charAt(r) == '}')
depth--;
}
}
else
{
r++;
}
}
if (r < right.length() - 1)
r++;
if (r == right.length() - 1)
{
if (rEnd)
break;
rEnd = true;
}
if (r >= right.length())
break;
// Store the two halves of the parent
final String[] parent = new String[2];
parent[0] = left.substring(l); //.trim();
parent[1] = right.substring(0, r); //.trim();
// Strip leading spaces from parent[0]
while (parent[0].length() > 0 && parent[0].charAt(0) == ' ')
parent[0] = parent[0].substring(1);
//System.out.println("Parent " + p + " is " + parent[0] + "?" + parent[1]);
parents.add(parent);
}
return parents;
}
//-------------------------------------------------------------------------
/**
* Extract completion choices from reconstruction clause.
* @param clause
* @return
*/
static List<String> extractChoices(final String clause)
{
final List<String> choices = new ArrayList<String>();
if (clause.length() >= 1 && clause.charAt(0) == '#')
{
// Is an enumeration, just return as is
choices.add(clause);
return choices;
}
final StringBuilder sb = new StringBuilder();
int depth = 0;
for (int c = 0; c < clause.length(); c++)
{
final char ch = clause.charAt(c);
if (depth == 0 && (c >= clause.length() - 1 || ch == CHOICE_DIVIDER_CHAR))
{
// Store this choice and reset sb
final String choice = sb.toString().trim();
// System.out.println("extractChoices choice is: " + choice);
if (choice.contains(".."))
{
// Handle range
final List<String> rangeChoices = expandRanges(new String(choice), null);
if (!rangeChoices.isEmpty() && !rangeChoices.get(0).contains(".."))
{
// Is a number range
//System.out.println(rangeChoices.size() + " range choices:" + rangeChoices);
choices.addAll(rangeChoices);
}
else
{
// Check for site ranges
final List<String> siteChoices = expandSiteRanges(new String(choice), null);
if (!siteChoices.isEmpty())
choices.addAll(siteChoices);
}
}
else
{
choices.add(choice);
}
// Reset to accumulate next choice
sb.setLength(0);
}
else
{
if (ch == '[')
depth++;
else if (ch == ']')
depth--;
sb.append(ch);
}
}
return choices;
}
//-------------------------------------------------------------------------
/**
* @param strIn
* @return Game description with all number range occurrences expanded.
*/
private static List<String> expandRanges
(
final String strIn,
final Report report
)
{
final List<String> choices = new ArrayList<String>();
if (!strIn.contains(".."))
return choices; // nothing to do
String str = new String(strIn);
int ref = 1;
while (ref < str.length() - 2)
{
if
(
str.charAt(ref) == '.' && str.charAt(ref+1) == '.'
&&
Character.isDigit(str.charAt(ref-1))
&&
Character.isDigit(str.charAt(ref+2))
)
{
// Is a range: expand it
int c = ref - 1;
while (c >= 0 && Character.isDigit(str.charAt(c)))
c--;
c++;
final String strM = str.substring(c, ref);
final int m = Integer.parseInt(strM);
c = ref + 2;
while (c < str.length() && Character.isDigit(str.charAt(c)))
c++;
final String strN = str.substring(ref+2, c);
final int n = Integer.parseInt(strN);
if (Math.abs(n - m) > MAX_RANGE)
{
if (report == null)
{
System.out.println("** Range exceeded maximum of " + MAX_RANGE + ".");
}
else
{
report.addError("Range exceeded maximum of " + MAX_RANGE + ".");
return null;
}
}
// Generate the expanded range substring
String sub = " ";
final int inc = (m <= n) ? 1 : -1;
for (int step = m; step != n; step += inc)
{
if (step == m || step == n)
continue; // don't include end points
sub += step + " ";
}
str = str.substring(0, ref) + sub + str.substring(ref+2);
ref += sub.length();
}
ref++;
}
final String[] subs = str.split(" ");
for (final String sub : subs)
choices.add(sub);
return choices;
}
/**
* @param strIn
* @return Game description with all site range occurrences expanded.
*/
private static List<String> expandSiteRanges
(
final String strIn,
final Report report
)
{
final List<String> choices = new ArrayList<String>();
//System.out.println("** Warning: Completer: Site ranges not expanded yet.");
//return choices;
if (!strIn.contains(".."))
return choices; // nothing to do
String str = new String(strIn);
int ref = 1;
while (ref < str.length() - 2)
{
if
(
str.charAt(ref) == '.' && str.charAt(ref+1) == '.'
&&
str.charAt(ref-1) == '"' && str.charAt(ref+2) == '"'
)
{
// Must be a site range
int c = ref - 2;
while (c >= 0 && str.charAt(c) != '"')
c--;
final String strC = str.substring(c+1, ref-1);
// System.out.println("strC: " + strC);
int d = ref + 3;
while (d < str.length() && str.charAt(d) != '"')
d++;
d++;
final String strD = str.substring(ref+3, d-1);
// System.out.println("strD: " + strD);
// System.out.println("Range: " + str.substring(c, d));
if (strC.length() < 2 || !isLetter(strC.charAt(0)))
{
if (report != null)
report.addError("Bad 'from' coordinate in site range: " + str.substring(c, d));
return null;
}
final int fromChar = Character.toUpperCase(strC.charAt(0)) - 'A';
if (strD.length() < 2 || !isLetter(strD.charAt(0)))
{
if (report != null)
report.addError("Bad 'to' coordinate in site range: " + str.substring(c, d));
return null;
}
final int toChar = Character.toUpperCase(strD.charAt(0)) - 'A';
// System.out.println("fromChar=" + fromChar + ", toChar=" + toChar + ".");
final int fromNum = Integer.parseInt(strC.substring(1));
final int toNum = Integer.parseInt(strD.substring(1));
// System.out.println("fromNum=" + fromNum + ", toNum=" + toNum + ".");
// Generate the expanded range substring
String sub = "";
for (int m = fromChar; m < toChar + 1; m++)
for (int n = fromNum; n < toNum + 1; n++)
sub += "\"" + (char)('A' + m) + (n) + "\" ";
str = str.substring(0, c) + sub.trim() + str.substring(d);
ref += sub.length();
}
ref++;
}
//System.out.println("str is: " + str);
final String[] subs = str.split(" ");
for (final String sub : subs)
choices.add(sub);
return choices;
}
public static boolean isLetter(final char ch)
{
return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z';
}
//-------------------------------------------------------------------------
// Ludeme loader code from Matthew
/**
* @return Names and contents of all files within the lud/board path.
*/
public static Map<String, String> getAllLudContents()
{
return getAllDirectoryContents("../Common/res/lud/board/");
}
/**
* @return Names and contents of all files within the define path.
*/
public static Map<String, String> getAllDefContents()
{
return getAllDirectoryContents("../Common/res/def/");
}
/**
* @return Names and contents of all files within the specific directory path.
*/
public static Map<String, String> getAllDirectoryContents(final String dir)
{
final File startFolder = new File(dir);
final List<File> gameDirs = new ArrayList<>();
gameDirs.add(startFolder);
final Map<String, String> fileContents = new HashMap<>();
for (int i = 0; i < gameDirs.size(); ++i)
{
final File gameDir = gameDirs.get(i);
for (final File fileEntry : gameDir.listFiles())
{
if (fileEntry.isDirectory())
{
gameDirs.add(fileEntry);
}
else
{
try(BufferedReader br = new BufferedReader(new FileReader(fileEntry)))
{
final StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
// Strip out formatting so that completion string matching it more robust
everything = Expander.cleanUp(everything, null);
fileContents.put(fileEntry.getName(), everything);
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
return fileContents;
}
//-------------------------------------------------------------------------
/**
* Save reconstruction to file.
* @param path Path to save output file (will use default /Common/res/out/recons/ if null).
* @param name Output file name for reconstruction.
* @throws IOException
*/
public static void saveCompletion
(
final String path, final String name, final Completion completion
) throws IOException
{
final String safePath = (path != null) ? path : "../Common/res/out/recons/";
// **
// ** TODO: Need to check if this path exists! If not, then try to make it.
// **
//final String scoreString = String.format("%.3f", Double.valueOf(completion.score()));
//final String outFileName = safePath + name + "-" + index + "-" + scoreString + ".lud";
final String outFileName = safePath + name + ".lud";
// Prepare the output file
final File file = new File(outFileName);
if (!file.exists())
file.createNewFile();
try
(
final PrintWriter writer =
new PrintWriter
(
new BufferedWriter(new FileWriter(outFileName, false))
)
)
{
writer.write(completion.raw());
}
}
//-------------------------------------------------------------------------
}
| 30,071 | 26.973953 | 122 |
java
|
Ludii
|
Ludii-master/Language/src/completer/Completion.java
|
package completer;
import java.util.ArrayList;
import java.util.List;
import gnu.trove.list.array.TIntArrayList;
/**
* Record of a reconstruction completion, which will be a raw *.lud description.
* @author cambolbro and Eric.Piette
*/
public class Completion
{
private String raw; // completed game description
private double score = 0; // confidence in enumeration (0..1)
private double culturalScore = 0; // (0..1)
private double conceptualScore = 0; // (0..1)
private double geographicalScore = 0; // (0..1)
private TIntArrayList idsUsed = new TIntArrayList(); // The ruleset ids used to make the completion.
private List<TIntArrayList> otherIdsUSed = new ArrayList<TIntArrayList>(); // The other possible combinations of rulesets used to obtain the same completion.
//-------------------------------------------------------------------------
public Completion(final String raw)
{
this.raw = raw;
}
//-------------------------------------------------------------------------
public String raw()
{
return raw;
}
public void setRaw(final String raw)
{
this.raw = raw;
}
public double score()
{
return score;
}
public void setScore(final double value)
{
score = value;
}
public double culturalScore()
{
return culturalScore;
}
public void setCulturalScore(final double value)
{
culturalScore = value;
}
public double geographicalScore()
{
return geographicalScore;
}
public void setGeographicalScore(final double value)
{
geographicalScore = value;
}
public double conceptualScore()
{
return conceptualScore;
}
public void setConceptualScore(final double value)
{
conceptualScore = value;
}
public TIntArrayList idsUsed()
{
return idsUsed;
}
public void setIdsUsed(final TIntArrayList ids)
{
idsUsed = new TIntArrayList(ids);
}
public void addId(final int id)
{
idsUsed.add(id);
}
public List<TIntArrayList> otherIdsUsed()
{
return otherIdsUSed;
}
public void addOtherIds(final TIntArrayList ids)
{
otherIdsUSed.add(ids);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return raw;
}
}
| 2,198 | 18.121739 | 158 |
java
|
Ludii
|
Ludii-master/Language/src/completer/TestCompleter.java
|
package completer;
//import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
//import org.junit.Test;
//import main.grammar.Report;
//import parser.Completer;
/**
* Test various reconstruction routines.
* @author cambolbro
*/
public class TestCompleter
{
//-------------------------------------------------------------------------
// @Test
// public void test()
// {
// testSaving();
// testLoadLuds();
// testCompletion();
// }
//-------------------------------------------------------------------------
/**
* From FileHandling.
* @param filePath
* @return Text contents from file.
* @throws IOException
* @throws FileNotFoundException
*/
public static String loadTextContentsFromFile(final String filePath) throws FileNotFoundException, IOException
{
// Load the string from file
final StringBuilder sb = new StringBuilder();
String line = null;
try
(
final InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8);
final BufferedReader bufferedReader = new BufferedReader(isr)
)
{
while ((line = bufferedReader.readLine()) != null)
sb.append(line + "\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
// void testSaving()
// {
// try
// {
// Completer.saveReconstruction("Test", "(test ...)");
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
// }
//-------------------------------------------------------------------------
static void testLoadLuds()
{
final Map<String, String> luds = Completer.getAllLudContents();
final Map<String, String> defs = Completer.getAllDefContents();
System.out.println(luds.size() + " luds loaded, " + defs.size() + " defs loaded.");
}
//-------------------------------------------------------------------------
static void testCompletion()
{
testCompletion(null, "TestReconOneClause.lud");
testCompletion(null, "TestReconTwoClauses.lud");
testCompletion(null, "TestReconNested.lud");
testCompletion(null, "TestReconRange.lud");
testCompletion(null, "TestReconRanges.lud");
testCompletion(null, "TestReconRangeSite.lud");
testCompletion(null, "TestReconInclude.lud");
testCompletion(null, "TestReconExclude.lud");
testCompletion(null, "TestReconEnumeration1.lud");
testCompletion(null, "TestReconEnumeration2.lud");
}
/**
* @param outFilePath Path to save output file (will use default /Common/res/out/recons/ if null).
* @param fileName File name.
*/
static void testCompletion(final String outFilePath, final String fileName)
{
//final String fileName = "TestReconA.lud";
final String filePath = "../Common/res/lud/test/recon/" + fileName;
System.out.println("\n####################################################");
System.out.println("\nTesting completion of " + filePath);
String str = "";
try
{
str = loadTextContentsFromFile(filePath);
System.out.println("desc:\n" + str);
System.out.println("File needs completing: " + Completer.needsCompleting(str));
//final Report report = new Report();
//final List<Completion> completions = Completer.completeExhaustive(str, 3, null); // save all completions
final List<Completion> completions = Completer.completeSampled(str, 3, null); // only save first completion for each file
for (int n = 0; n < completions.size(); n++)
{
final Completion completion = completions.get(n);
// Don't add ".lud" suffix, that is added by completer
final int suffixAt = fileName.indexOf(".lud");
final String outFileName = fileName.substring(0, suffixAt) + "-" + n;
try
{
Completer.saveCompletion(outFilePath, outFileName, completion);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
catch (final FileNotFoundException ex)
{
System.out.println("Unable to open file '" + fileName + "'");
}
catch (final IOException ex)
{
System.out.println("Error reading file '" + fileName + "'");
}
//final Map<String, String> luds = Completer.getAllLudContents();
//final Map<String, String> defs = Completer.getAllDefContents();
//System.out.println(luds.size() + " luds loaded, " + defs.size() + " defs loaded.");
}
//-------------------------------------------------------------------------
public static void main(String[] args)
{
TestCompleter.testLoadLuds();
TestCompleter.testCompletion();
}
}
| 4,706 | 27.527273 | 125 |
java
|
Ludii
|
Ludii-master/Language/src/grammar/ClassEnumerator.java
|
package grammar;
// From: https://github.com/ddopson/java-class-enumerator
// Reference: https://stackoverflow.com/questions/10119956/getting-class-by-its-name
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
//-----------------------------------------------------------------------------
/**
* Routines for enumerating classes.
* @author Dennis Soemers and cambolbro
*/
public class ClassEnumerator
{
// private static void log(String msg)
// {
// System.out.println("ClassDiscovery: " + msg);
// }
private static Class<?> loadClass(String className)
{
try
{
return Class.forName(className);
}
catch (final ClassNotFoundException e) {
throw new RuntimeException("Unexpected ClassNotFoundException loading class '" + className + "'");
}
}
/**
* Given a package name and a directory returns all classes within that directory
* @param directory
* @param pkgname
* @return Classes within Directory with package name
*/
public static List<Class<?>> processDirectory(File directory, String pkgname) {
final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
// log("Reading Directory '" + directory + "'");
// Get the list of the files contained in the package
final String[] files = directory.list();
for (int i = 0; i < files.length; i++) {
final String fileName = files[i];
String className = null;
// we are only interested in .class files
if (fileName.endsWith(".class")) {
// removes the .class extension
className = pkgname + '.' + fileName.substring(0, fileName.length() - 6);
}
// log("FileName '" + fileName + "' => class '" + className + "'");
if (className != null) {
classes.add(loadClass(className));
}
//If the file is a directory recursively class this method.
final File subdir = new File(directory, fileName);
if (subdir.isDirectory()) {
classes.addAll(processDirectory(subdir, pkgname + '.' + fileName));
}
}
return classes;
}
/**
* Given a jar file and a package name returns all classes within jar file.
*
* @param jarFile
* @param pkgname
* @return The list of the classes.
*/
public static List<Class<?>> processJarfile(final JarFile jarFile, final String pkgname)
{
final List<Class<?>> classes = new ArrayList<Class<?>>();
//Turn package name to relative path to jar file
final String relPath = pkgname.replace('.', '/');
try
{
// Get contents of jar file and iterate through them
final Enumeration<JarEntry> entries = jarFile.entries();
while(entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
//Get content name from jar file
final String entryName = entry.getName();
String className = null;
// If content is a class save class name.
if
(
entryName.endsWith(".class")
&&
entryName.startsWith(relPath)
&&
entryName.length() > (relPath.length() + "/".length())
)
{
className = entryName.replace('/', '.').replace('\\', '.');
className = className.substring(0, className.length() - ".class".length());
}
// log("JarEntry '" + entryName + "' => class '" + className + "'");
//If content is a class add class to List
if (className != null) {
classes.add(loadClass(className));
}
}
jarFile.close();
}
catch (final IOException e)
{
throw new RuntimeException("Unexpected IOException reading JAR File '" + jarFile.getName() + "'", e);
}
return classes;
}
//-------------------------------------------------------------------------
/**
* Return all classes contained in a given package.
* @param pkg
* @return The list of the classes.
*/
public static List<Class<?>> getClassesForPackage(final Package pkg)
{
final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
//Get name of package and turn it to a relative path
final String pkgname = pkg.getName();
final String relPath = pkgname.replace('.', '/');
// **
// ** The following code fails when looking for path in web archive.
// **
//final URL url = ClassLoader.getSystemClassLoader().getResource(relPath);
final URL url = ClassEnumerator.class.getClassLoader().getResource(relPath);
//System.out.println("pkg=" + pkg + ", relPath=" + relPath + ", url=" + url);
// If the resource is a jar get all classes from jar
if (url.getPath().contains(".jar"))
{
try
(
final JarFile jarFile = new JarFile
(
new File(ClassEnumerator.class.getProtectionDomain().getCodeSource().getLocation().toURI()))
)
{
classes.addAll(processJarfile(jarFile, pkgname));
}
catch (final IOException | URISyntaxException e)
{
throw new RuntimeException("Unexpected problem with JAR file for: " + relPath);
}
}
else
{
try
{
classes.addAll(processDirectory(new File(URLDecoder.decode(url.getPath(), "UTF-8")), pkgname));
}
catch (final UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
return classes;
}
}
| 5,340 | 26.389744 | 104 |
java
|
Ludii
|
Ludii-master/Language/src/grammar/ClassEnumeratorFindAll.java
|
package grammar;
// From: https://github.com/ddopson/java-class-enumerator
// Reference: https://stackoverflow.com/questions/10119956/getting-class-by-its-name
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
//-----------------------------------------------------------------------------
/**
*
*/
public class ClassEnumeratorFindAll
{
// private static void log(String msg)
// {
// System.out.println("ClassEnumeratorFindAll: " + msg);
// }
private static Class<?> loadClass(String className) {
try {
return Class.forName(className);
} catch (final ClassNotFoundException e) {
throw new RuntimeException("Unexpected ClassNotFoundException loading class '" + className + "'");
}
}
/**
* Given a directory returns all classes within that directory
*
* @param directory
* @return Classes within Directory
*/
public static List<Class<?>> processDirectory(File directory) {
final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
// log("Reading Directory '" + directory + "'");
try {
// Get the list of the files contained in the package
final String[] files = directory.list();
for (int i = 0; i < files.length; i++) {
final String fileName = files[i];
String className = null;
// we are only interested in .class files
if (fileName.endsWith(".class")) {
// removes the .class extension
className = fileName.substring(0, fileName.length() - 6);
}
// log("FileName '" + fileName + "' => class '" + className + "'");
if (className != null) {
classes.add(loadClass(className));
}
// If the file is a directory recursively find class.
final File subdir = new File(directory, fileName);
if (subdir.isDirectory()) {
classes.addAll(processDirectory(subdir));
}
// if file is a jar file
if (fileName.endsWith(".jar")) {
classes.addAll(processJarfile(directory.getAbsolutePath() + "/" + fileName));
}
}
} catch (final Exception e) {
e.printStackTrace();
}
return classes;
}
/**
* Given a jar file's URL returns all classes within jar file.
*
* @param jarPath The path of the Jar.
* @return The list of classes.
*/
public static List<Class<?>> processJarfile(String jarPath)
{
final List<Class<?>> classes = new ArrayList<Class<?>>();
try (JarFile jarFile = new JarFile(jarPath))
{
// Get contents of jar file and iterate through them
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
// Get content name from jar file
final String entryName = entry.getName();
String className = null;
// If content is a class save class name.
if (entryName.endsWith(".class"))
{
className = entryName.replace('/', '.').replace('\\', '.');
className = className.substring(0, className.length() - ".class".length());
}
// log("JarEntry '" + entryName + "' => class '" + className + "'");
// If content is a class add class to List
if (className != null) {
classes.add(loadClass(className));
continue;
}
// If jar contains another jar then iterate through it
if (entryName.endsWith(".jar")) {
classes.addAll(processJarfile(entryName));
continue;
}
// If content is a directory
final File subdir = new File(entryName);
if (subdir.isDirectory()) {
classes.addAll(processDirectory(subdir));
}
}
jarFile.close();
}
catch (final IOException e)
{
throw new RuntimeException("Unexpected IOException reading JAR File '" + jarPath + "'", e);
}
return classes;
}
}
| 3,803 | 25.978723 | 101 |
java
|
Ludii
|
Ludii-master/Language/src/grammar/Grammar.java
|
package grammar;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import annotations.Alias;
import main.Constants;
import main.FileHandling;
import main.StringRoutines;
import main.grammar.Clause;
import main.grammar.ClauseArg;
import main.grammar.GrammarRule;
import main.grammar.LudemeInfo;
import main.grammar.PackageInfo;
import main.grammar.Symbol;
import main.grammar.Symbol.LudemeType;
import main.grammar.ebnf.EBNF;
//-----------------------------------------------------------------------------
/**
* Ludii class grammar generator.
*
* @author cambolbro
*/
public class Grammar
{
/** List of symbols. */
private final List<Symbol> symbols = new ArrayList<Symbol>();
/** Hash map for accessing symbols directly by name (might be multiples). */
private final Map<String, List<Symbol>> symbolsByName = new HashMap<String, List<Symbol>>();
/** Hash map for identifying symbols by partial keyword (most will have multiples). */
private final Map<String, List<Symbol>> symbolsByPartialKeyword = new HashMap<String, List<Symbol>>();
/** List of rules. */
private final List<GrammarRule> rules = new ArrayList<GrammarRule>();
/** List of rule packages. */
private final List<PackageInfo> packages = new ArrayList<PackageInfo>();
/** Order in which packages are to be printed. */
private final List<PackageInfo> packageOrder = new ArrayList<PackageInfo>();
private Symbol rootGameSymbol = null;
private Symbol rootMetadataSymbol = null;
private EBNF ebnf = null;
//-------------------------------------------------------------------------
/** Primitive symbols with notional package names. */
public static final String[][] Primitives =
{
{ "int", "game.functions.ints" },
{ "boolean", "game.functions.booleans" },
{ "float", "game.functions.floats" },
};
/** Predefined symbols (known data types) with notional and actual package names, and keyword. */
public static final String[][] Predefined =
{
{ "java.lang.Integer", "game.functions.ints", "java.lang", "int" },
{ "java.lang.Boolean", "game.functions.booleans", "java.lang", "boolean" },
{ "java.lang.Float", "game.functions.floats", "java.lang", "float" },
{ "java.lang.String", "game.types", "java.lang", "string" },
};
/** Function names and associated constants. */
private final String[][] Functions =
{
// Function name Arg replacement Listed symbols (if any)
{ "IntFunction", "int", },
{ "IntConstant", "int", },
{ "BooleanFunction", "boolean", },
{ "BooleanConstant", "boolean", },
{ "FloatFunction", "float", },
{ "FloatConstant", "float", },
{ "IntArrayFunction", "ints", },
{ "IntArrayConstant", "ints", },
{ "RegionFunction", "sites", },
{ "RegionConstant", "sites", },
//{ "Region", "sites", },
{ "RangeFunction", "range", },
{ "RangeConstant", "range", },
{ "DirectionsFunction", "directions", },
{ "DirectionsConstant", "directions", },
{ "GraphFunction", "graph", },
{ "GraphConstant", "graph", },
//{ "GraphFunction", "tiling", },
//{ "GraphConstant", "tiling", },
{ "DimFunction", "dim", },
{ "DimConstant", "dim", },
};
/** Application constants. */
public final static String[][] ApplicationConstants =
{
// Constant name, return type, notional package, value
{ "Off", "int", "global", ("" + Constants.OFF) },
{ "End", "int", "global", ("" + Constants.END) },
{ "Undefined", "int", "global", ("" + Constants.UNDEFINED) },
{ "Infinity", "int", "global", ("" + Constants.INFINITY) },
// { "Unused", "int", "global", ("" + Constants.UNUSED) },
// { "Nobody", "int", "global", ("" + Constants.NOBODY) },
// { "NoPiece", "int", "global", ("" + Constants.NO_PIECE) },
// { "Repeat", "int", "global", ("" + Constants.REPEAT) },
};
//-------------------------------------------------------------------------
private static volatile Grammar singleton = null;
//-------------------------------------------------------------------------
private Grammar()
{
//final long startAt = System.nanoTime();
generate();
//final long endAt = System.nanoTime();
//final double secs = (endAt - startAt) / 1000000000.0;
//System.out.println("Grammar generated in " + secs + "s.");
}
//-------------------------------------------------------------------------
/**
* Access grammar here.
* @return The singleton grammar object.
*/
public static Grammar grammar()
{
if (singleton == null)
{
synchronized(Grammar.class)
{
if (singleton == null)
singleton = new Grammar();
}
}
return singleton;
}
//-------------------------------------------------------------------------
/**
* @param name
* @return Map of symbols by name.
*/
public List<Symbol> symbolsByName(final String name)
{
return symbolsByName.get(name);
}
// /**
// * @return Map of symbols by partial keyword.
// */
// public Map<String, List<Symbol>> symbolsByPartialKeyword()
// {
// return symbolsByPartialKeyword;
// }
/**
* @return The list of the symbols.
*/
public List<Symbol> symbols()
{
return Collections.unmodifiableList(symbols);
}
//-------------------------------------------------------------------------
/**
* Note: This looks like a getter but also may do some processing.
*
* @return The EBNF.
*/
public EBNF ebnf()
{
if (ebnf == null)
ebnf = new EBNF(grammar().toString());
//findEBNFClasses(ebnf);
return ebnf;
}
//-------------------------------------------------------------------------
// /**
// * Do here in Grammar rather than EBNF, so EBNF doesn't depend on Grammar.
// */
// public void findEBNFClasses()
// {
// for (final EBNFRule rule : Grammar.grammar().ebnf().rules().values())
// {
// System.out.println("EBNF rule: " + rule);
// //final Class<?> cls = null;
// // ...
// //rule.setClass(cls);
// }
// }
//-------------------------------------------------------------------------
/**
* Generate the grammar from the current code base.
*/
void execute()
{
System.out.println("Ludii library " + Constants.LUDEME_VERSION + ".");
generate();
final String outFileName = "grammar-" + Constants.LUDEME_VERSION + ".txt";
System.out.println("Saving to file " + outFileName + ".");
try
{
export(outFileName);
}
catch (final Exception e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Generate grammar from the class library.
*/
public void generate()
{
symbols.clear();
getRules().clear();
packages.clear();
createSymbols();
disambiguateSymbols();
createRules();
addReturnTypeClauses();
addApplicationConstantsToRule();
crossReferenceSubclasses();
//replaceListFunctionArgs();
linkDirectionsRules();
linkRegionRules();
handleDimFunctions();
handleGraphAndRangeFunctions();
handleTrackSteps();
linkToPackages();
instantiateSingleEnums();
visitSymbols(rootGameSymbol);
visitSymbols(rootMetadataSymbol);
setDisplayOrder(rootGameSymbol);
removeRedundantFunctionNames();
createSymbolMap();
alphabetiseRuleClauses();
removeDuplicateClauses();
filterOutPrimitiveWrappers();
setUsedInGrammar();
setUsedInDescription();
setUsedInMetadata();
setLudemeTypes();
setAtomicLudemes();
findAncestors();
tidyUpFormat();
final boolean debug = FileHandling.isCambolbro() && false;
if (debug)
{
System.out.println(symbolDetails());
}
// System.out.println("=================\nPackages:");
// for (Package pack : packages)
// System.out.println(pack.path());
// System.out.println("\n=================\n");
// Show symbol count
int numGrammar = 0;
int numMetadata = 0;
int numClasses = 0;
int numConstants = 0;
int numPredefined = 0;
int numPrimitive = 0;
for (final Symbol symbol : symbols)
{
if (symbol.usedInDescription())
numGrammar++;
if (symbol.usedInMetadata())
numMetadata++;
if (symbol.isClass())
numClasses++;
if (symbol.ludemeType() == LudemeType.Constant)
numConstants++;
if (symbol.ludemeType() == LudemeType.Predefined)
numPredefined++;
if (symbol.ludemeType() == LudemeType.Primitive)
numPrimitive++;
}
if (debug)
{
System.out.println
(
symbols.size() + " symbols: " + numClasses + " classes, " +
numConstants + " constants, " + numPredefined + " predefined, " + numPrimitive + " primitives."
);
System.out.println(getRules().size() + " rules, " + numGrammar + " used in grammar, " +
numMetadata + " used in metadata.");
}
if (debug)
{
// Check ludemes used
System.out.println("Ludemes used:");
final List<LudemeInfo> ludemesUsed = ludemesUsed();
for (final LudemeInfo li : ludemesUsed)
System.out.println(li.symbol().token() + " (" + li.symbol().name() + ") : " + li.symbol().cls().getName());
}
}
//-------------------------------------------------------------------------
/**
* Create all symbols in the grammar.
*/
void createSymbols()
{
Symbol symbolInt = null;
// Create Primitive symbols
for (int pid = 0; pid < Primitives.length; pid++)
{
Class<?> cls = null;
if (Primitives[pid][0].equals("int"))
cls = int.class;
else if (Primitives[pid][0].equals("float"))
cls = float.class;
else if (Primitives[pid][0].equals("boolean"))
cls = boolean.class;
final Symbol symbol = new Symbol(LudemeType.Primitive, Primitives[pid][0], null, Primitives[pid][1], cls);
symbol.setReturnType(symbol); // returns itself
symbols.add(symbol);
if (Primitives[pid][0].equals("int"))
symbolInt = symbol;
}
// Create Predefined symbols
for (int pid = 0; pid < Predefined.length; pid++)
{
Class<?> cls = null;
try
{
cls = Class.forName(Predefined[pid][0]);
} catch (final ClassNotFoundException e)
{
e.printStackTrace();
}
final Symbol symbol = new Symbol
(
LudemeType.Predefined, Predefined[pid][0], null,
Predefined[pid][1], cls
);
symbol.setToken(Predefined[pid][3]);
symbol.setGrammarLabel(Predefined[pid][3]);
symbol.setReturnType(symbol); // returns itself
symbols.add(symbol);
}
// Create symbols for application constants
for (int cs = 0; cs < ApplicationConstants.length; cs++)
{
// **
// ** Assumes that all application constants are ints. Extend this if needed.
// **
final Class<?> cls = int.class;
final Symbol symbolC = new Symbol
(
LudemeType.Constant, ApplicationConstants[cs][0],
null, ApplicationConstants[cs][2], cls
);
symbolC.setReturnType(symbolInt);
symbols.add(symbolC);
}
// Traverse class hierarchy to generate symbols
findSymbolsFromClasses("game.Game");
findSymbolsFromClasses("metadata.Metadata");
checkHiddenClasses();
checkAbstractClasses();
handleEnums();
overrideReturnTypes();
// Check that appropriate symbols are included in grammar
// for (final Symbol symbol : symbols)
// //if (symbol.hasAlias())
// if (!symbol.name().equalsIgnoreCase(symbol.token()))
// symbol.setUsedInGrammar(true); // is probably an alias or remapped form something else
// // Ensure that functions are not used in grammar
// for (final Symbol symbol : symbols)
// if (symbol.name().contains("Function"))
// System.out.println("Symbol function found: " + symbol.info());
// Set root symbols
rootGameSymbol = null;
rootMetadataSymbol = null;
for (final Symbol symbol : symbols)
{
if (symbol.path().equals("game.Game"))
rootGameSymbol = symbol;
if (symbol.path().equals("metadata.Metadata"))
rootMetadataSymbol = symbol;
}
if (rootGameSymbol == null || rootMetadataSymbol == null)
throw new RuntimeException("Cannot find game.Game or metadata.Metadata.");
}
//-------------------------------------------------------------------------
/**
* Traverse files in library to find symbols.
*
* @param rootPackageName The root package name.
*/
public void findSymbolsFromClasses(final String rootPackageName)
{
Class<?> clsRoot = null;
try
{
clsRoot = Class.forName(rootPackageName);
}
catch (final ClassNotFoundException e)
{
e.printStackTrace();
}
final List<Class<?>> classes = ClassEnumerator.getClassesForPackage(clsRoot.getPackage());
for (final Class<?> cls : classes)
{
if (cls.getName().contains("$"))
continue; // is an internal class or enum?
if (cls.getName().contains("package-info"))
continue; // placeholder file for documentation
String alias = null;
// From: http://tutorials.jenkov.com/java-reflection/annotations.html
final Annotation[] annotations = cls.getAnnotations();
for (final Annotation annotation : annotations)
{
if (annotation instanceof Alias)
{
final Alias anno = (Alias)annotation;
alias = anno.alias();
}
}
final String classPath = cls.getName();
// **
// ** Assume it is Ludeme type until proven otherwise.
// **
final Symbol symbol = new Symbol(LudemeType.Ludeme, classPath, alias, cls);
symbol.setReturnType(symbol); // returns itself (unless superseded by eval())
symbols.add(symbol);
// Add this package name, if not already found
final Package pack = cls.getPackage();
final String packageName = pack.getName();
int p;
for (p = 0; p < packages.size(); p++)
if (packages.get(p).path().equals(packageName))
break;
if (p >= packages.size())
packages.add(new PackageInfo(packageName));
}
}
//-------------------------------------------------------------------------
void disambiguateSymbols()
{
for (int sa = 0; sa < symbols.size(); sa++)
{
final Symbol symbolA = symbols.get(sa);
if (!symbolA.isClass())
continue;
String grammarLabel = "";
for (int sb = 0; sb < symbols.size(); sb++)
{
if (sa == sb)
continue;
final Symbol symbolB = symbols.get(sb);
if (!symbolB.isClass())
continue;
if (symbolA.name().equals(symbolB.name()))
{
// Classes with same name found
final String label = symbolA.disambiguation(symbolB);
if (label == null)
continue;
if (label.length() > grammarLabel.length())
grammarLabel = new String(label);
}
}
if (grammarLabel != "")
symbolA.setGrammarLabel(grammarLabel);
}
}
//-------------------------------------------------------------------------
void createSymbolMap()
{
symbolsByName.clear();
for (final Symbol symbol : symbols)
{
final String key = symbol.name();
List<Symbol> list = symbolsByName.get(key);
if (list != null)
{
// Symbol(s) with same name already in map
list.add(symbol);
}
else
{
// Add symbol to new list
list = new ArrayList<Symbol>();
list.add(symbol);
symbolsByName.put(key, list);
}
}
// // Sort lists (shortest to longest)
// for (final List<Symbol> list : symbolsByName.values())
// {
// Collections.sort(list, new Comparator<Symbol>()
// {
// @Override
// public int compare(final Symbol sa, final Symbol sb)
// {
// final int lenA = sa.name().length();
// final int lenB = sb.name().length();
//
// if (lenA == lenB)
// return sa.name().compareTo(sb.name());
//
// return lenA < lenB ? -1 : 1;
// }
// });
// }
// Create map for partial keyword matches
symbolsByPartialKeyword.clear();
for (final Symbol symbol : symbols)
{
final String fullKey = symbol.token();
for (int i = 1; i < fullKey.length() + 1; i++)
{
final String key = fullKey.substring(0, i);
// System.out.println("key=" + key);
List<Symbol> list = symbolsByPartialKeyword.get(key);
if (list != null)
{
// Symbol(s) with same name already in map
list.add(symbol);
}
else
{
// Add symbol to new list
list = new ArrayList<Symbol>();
list.add(symbol);
symbolsByPartialKeyword.put(key, list);
}
}
}
//System.out.println(symbolMap.size() + " symbol entries.");
//System.out.println(symbolMapPartial.size() + " partial entries.");
}
//-------------------------------------------------------------------------
/**
* @param className May be class name or alias.
* @return Symbol list matching the specified keyword.
*/
public List<Symbol> symbolListFromClassName(final String className)
{
final List<Symbol> list = symbolsByName.get(className);
if (list != null)
return list; // found symbol by class name
// Check for aliases
for (final Symbol symbol : symbols)
if (symbol.token().equals(className))
return symbolsByName.get(symbol.name());
return null; // could not find
}
//-------------------------------------------------------------------------
/**
* @param partialKeyword The partial keyword.
* @return Symbols matching the given partial keyword.
*/
public List<Symbol> symbolsWithPartialKeyword(final String partialKeyword)
{
return symbolsByPartialKeyword.get(partialKeyword);
}
//-------------------------------------------------------------------------
/**
* @param description Game description (may be expanded or not).
* @param cursorAt Character position of cursor.
* @param usePartial True if we use the partial keywords.
* @return Paths of best matches for the keyword at the cursor position.
*/
public List<String> classPaths(final String description, final int cursorAt, final boolean usePartial)
{
final List<String> list = new ArrayList<String>();
if (cursorAt <= 0 || cursorAt >= description.length())
{
System.out.println("** Grammar.classPaths(): Invalid cursor position " + cursorAt + " specified.");
return list;
}
// Get partial keyword up to cursor
int c = cursorAt - 1;
char ch = description.charAt(c);
if (!StringRoutines.isTokenChar(ch))
{
// Not currently on a token (or at the start of one): return nothing
return list;
}
while (c > 0 && StringRoutines.isTokenChar(ch))
{
c--;
ch = description.charAt(c);
}
// Get full keyword
int cc = cursorAt;
char ch2 = description.charAt(cc);
while (cc < description.length() && StringRoutines.isTokenChar(ch2))
{
cc++;
if (cc < description.length())
ch2 = description.charAt(cc);
}
if (cc >= description.length())
{
System.out.println("** Grammar.classPaths(): Couldn't find end of token from position " + cursorAt + ".");
return list;
}
if (ch2 == ':')
{
// Token is a parameter name: return nothing
return list;
}
String partialKeyword = description.substring(c+1, cursorAt);
String fullKeyword = description.substring(c+1, cc);
boolean isRule = false;
if (partialKeyword.charAt(0) == '<')
{
isRule = true;
partialKeyword = partialKeyword.substring(1);
}
if (fullKeyword.charAt(0) == '<' && fullKeyword.charAt(fullKeyword.length() - 1) == '>')
{
isRule = true;
fullKeyword = fullKeyword.substring(1, fullKeyword.length() - 1);
}
if
(
description.charAt(c) == '<'
||
description.charAt(c) == '[' && description.charAt(c+1) == '<'
||
description.charAt(c) == '(' && description.charAt(c+1) == '<'
)
isRule = true;
// Handle primitive and predefined types
if (fullKeyword.charAt(0) == '"')
{
// Is a string: note that quotes '"' are a valid token character
list.add("java.lang.String");
return list;
}
else if (fullKeyword.equals("true"))
{
list.add("true");
}
else if (fullKeyword.equals("false"))
{
list.add("false");
}
else if (StringRoutines.isInteger(fullKeyword))
{
list.add("int");
}
else if (StringRoutines.isFloat(fullKeyword) || StringRoutines.isDouble(fullKeyword))
{
list.add("float");
}
// Find for matches
final String keyword = usePartial ? partialKeyword : fullKeyword;
final List<Symbol> matches = symbolsWithPartialKeyword(keyword);
if (matches == null)
{
// Nothing to return
return list;
}
// Filter out unwanted matches
if (ch == '(')
{
// Is a class constructor
for (final Symbol symbol : matches)
if (symbol.cls() != null && !symbol.cls().isEnum())
list.add(symbol.path());
}
else if (ch == '<' || isRule)
{
// Is a rule
for (final Symbol symbol : matches)
list.add(symbol.path());
}
else if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == ':' || ch == '{')
{
// Is a terminal (probably an enum)
for (final Symbol symbol : matches)
if (symbol.cls() != null && symbol.cls().isEnum())
{
int lastDot = symbol.path().length() - 1;
while (lastDot >= 0 && symbol.path().charAt(lastDot) != '.')
lastDot--;
final String enumString = symbol.path().substring(0,lastDot) + '$' + symbol.path().substring(lastDot + 1);
list.add(enumString);
}
}
// Filter ludemes/metadata as appropriate
final int metadataAt = description.indexOf("(metadata");
final boolean inMetadata = metadataAt != -1 && metadataAt < cursorAt;
for (int n = list.size() - 1; n >= 0; n--)
{
final boolean isMetadata = list.get(n).contains("metadata.");
if (isMetadata && !inMetadata || !isMetadata && inMetadata)
list.remove(n);
}
return list;
}
//-------------------------------------------------------------------------
/**
* @param name
* @return Index of application constant with same name, else -1 if none.
*/
public static int applicationConstantIndex(final String name)
{
for (int ac = 0; ac < ApplicationConstants.length; ac++)
if (ApplicationConstants[ac][0].equals(name))
return ac;
return -1;
}
//-------------------------------------------------------------------------
/**
* Check for symbols that should be hidden.
*/
void checkHiddenClasses()
{
for (final Symbol symbol : symbols)
{
final Class<?> cls = symbol.cls();
if (cls == null)
continue;
final Annotation[] annos = cls.getAnnotations();
for (final Annotation anno : annos)
{
if (anno.annotationType().getName().equals("annotations.Hide"))
{
symbol.setHidden(true);
break;
}
}
}
}
//-------------------------------------------------------------------------
/**
* Determine which classes are abstract. These constitute rules rather than instances.
*/
void checkAbstractClasses()
{
for (final Symbol symbol : symbols)
{
final Class<?> cls = symbol.cls();
if (cls == null)
continue;
if (Modifier.isAbstract(cls.getModifiers()))
symbol.setIsAbstract(true);
}
}
//-------------------------------------------------------------------------
/**
* Handle enums (including inner classes).
*/
void handleEnums()
{
final List<Symbol> newSymbols = new ArrayList<Symbol>();
for (final Symbol symbol : symbols)
{
final Class<?> cls = symbol.cls();
if (cls == null)
continue;
if (cls.isEnum())
extractEnums(cls, symbol, newSymbols);
// Check for inner classes
for (final Class<?> inner : cls.getClasses())
{
if (inner.isEnum())
{
extractEnums(inner, symbol, newSymbols);
}
else
{
// Ignore inner classes that are not enums, even if they're ludemes
//System.out.println("!! Grammar.handleEnums(): Inner class found but not enum and not handled: ");
//System.out.println(" " + inner.getName() + "\n");
}
}
}
for (final Symbol newSymbol : newSymbols)
if (findSymbolMatch(newSymbol) == null)
symbols.add(newSymbol);
}
//-------------------------------------------------------------------------
/**
* Extract enums from class (including inner class).
*/
static void extractEnums(final Class<?> cls, final Symbol symbol, final List<Symbol> newSymbols)
{
final Symbol symbolEnum = new Symbol(LudemeType.Structural, cls.getName(), null, cls);
symbolEnum.setReturnType(symbolEnum);
newSymbols.add(symbolEnum);
for (final Object enumObj : cls.getEnumConstants())
{
final String symbolName = enumObj.toString();
final String path = symbolEnum.path() + "." + symbolName;
// Check for alias
String alias = null;
// From: https://clevercoder.net/2016/12/12/getting-annotation-value-enum-constant/
Field declaredField = null;
try
{
declaredField = cls.getDeclaredField(((Enum<?>)enumObj).name());
}
catch (final NoSuchFieldException e)
{
e.printStackTrace();
}
if (declaredField != null)
{
final Annotation[] annotations = declaredField.getAnnotations();
for (final Annotation annotation : annotations)
if (annotation instanceof Alias)
{
final Alias anno = (Alias)annotation;
alias = anno.alias();
}
}
final Symbol symbolValue = new Symbol
(
LudemeType.Constant, path, alias,
symbolEnum.notionalLocation(), cls
);
symbolValue.setReturnType(symbolEnum); // link value to its enum type
newSymbols.add(symbolValue);
}
}
//-------------------------------------------------------------------------
/**
* Override return types from classes with eval() method.
*/
void overrideReturnTypes()
{
final List<Symbol> newSymbols = new ArrayList<Symbol>();
for (final Symbol symbol : symbols)
{
if (!symbol.isClass())
continue;
final Class<?> cls = symbol.cls();
if (cls == null)
continue;
// Handle aliases here as well
String alias = null;
// From: http://tutorials.jenkov.com/java-reflection/annotations.html
final Annotation[] classAnnotations = cls.getAnnotations();
for (final Annotation annotation : classAnnotations)
{
if (annotation instanceof Alias)
{
final Alias anno = (Alias)annotation;
alias = anno.alias();
}
}
// Check for run() method
final Method[] methods = cls.getDeclaredMethods();
for (final Method method : methods)
{
if (!method.getName().equals("eval"))
continue;
final Type returnType = method.getReturnType();
if (returnType == null)
{
System.out.println("** Bad return type.");
continue;
}
final String returnTypeName = returnType.getTypeName();
if (returnTypeName.equals("void"))
continue;
// if (returnTypeName.equals("Moves"))
// continue;
final Symbol temp = new Symbol(null, returnTypeName, alias, cls);
Symbol returnSymbol = findSymbolByPath(temp.path());
if (returnSymbol == null)
{
continue;
}
if (symbol.nesting() != temp.nesting())
{
// Create a new return symbol for a collection of this symbol
returnSymbol = new Symbol(returnSymbol);
returnSymbol.setNesting(temp.nesting());
returnSymbol.setReturnType(returnSymbol);
newSymbols.add(returnSymbol);
}
symbol.setReturnType(returnSymbol);
}
}
for (final Symbol newSymbol : newSymbols)
if (findSymbolMatch(newSymbol) == null)
symbols.add(newSymbol);
}
//-------------------------------------------------------------------------
/**
* @param path
* @return Symbol with specified path, else null if not found.
*/
public Symbol findSymbolByPath(final String path)
{
for (final Symbol symbol : symbols)
if (symbol.path().equalsIgnoreCase(path))
return symbol;
return null;
}
//-------------------------------------------------------------------------
/**
* Create rules based on symbol return types.
*/
void createRules()
{
for (final Symbol symbol : symbols)
{
if (symbol.hidden())
continue; // skip hidden symbols
if (symbol.ludemeType() == LudemeType.Constant)
{
// Add constant clause to enum rule
final Symbol lhs = symbol.returnType();
final GrammarRule rule = getRule(lhs);
final Clause clause = new Clause(symbol);
rule.addToRHS(clause);
}
else
{
// Ensure that rule exists (or is created) for this symbol
final Symbol lhs = symbol;
final GrammarRule rule = getRule(lhs);
// Create clauses
if (symbol.isClass() && !symbol.isAbstract())
{
// Create constructor clause(s)
expandConstructors(rule, symbol);
}
else
{
// Add non-constructor clause
final Clause clause = new Clause(symbol);
if
(
!rule.containsClause(clause)
&&
(
symbol.ludemeType() == LudemeType.Primitive
||
symbol.ludemeType() == LudemeType.Predefined
||
!lhs.path().equals(symbol.path())
)
&& // avoid repetition of LHS collections on RHS
!(lhs.matches(symbol) && lhs.nesting() > 0)
)
{
rule.addToRHS(clause);
}
else
{
//System.out.println("- Failed test for generating clause for: " + symbol.name());
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* @param lhs
* @return Rule with the specified LHS, creates new rule if necessary.
*/
GrammarRule getRule(final Symbol lhs)
{
for (final GrammarRule rule : getRules())
if (rule.lhs().matches(lhs))
return rule; // existing rule
// Create new rule
final GrammarRule rule = new GrammarRule(lhs);
getRules().add(rule);
return rule;
}
/**
* @param lhs
* @return Rule with the specified LHS, else null if not found.
*/
GrammarRule findRule(final Symbol lhs)
{
for (final GrammarRule rule : getRules())
if (rule.lhs().matches(lhs))
return rule;
return null;
}
/**
* @param path
* @return Package with the specified path, else null if none.
*/
public PackageInfo findPackage(final String path)
{
for (final PackageInfo pack : packages)
if (path.equalsIgnoreCase(pack.path()))
return pack;
return null;
}
//-------------------------------------------------------------------------
/**
* Expand constructors for this concrete base class.
*
* @param rule
* @param symbol
*/
void expandConstructors(final GrammarRule rule, final Symbol symbol)
{
if (symbol.hidden())
return;
final Class<?> cls = symbol.cls();
if (cls == null)
return;
// Handle aliases here as well
String alias = null;
// From: http://tutorials.jenkov.com/java-reflection/annotations.html
final Annotation[] classAnnotations = cls.getAnnotations();
for (final Annotation annotation : classAnnotations)
{
if (annotation instanceof Alias)
{
final Alias anno = (Alias)annotation;
alias = anno.alias();
}
}
// Get list of either constructors or construct() methods
final List<Executable> ctors = new ArrayList<Executable>();
// Get list of constructors
ctors.addAll(Arrays.asList(cls.getConstructors()));
// Get list of static construct() methods
final Method[] methods = cls.getDeclaredMethods();
for (final Method method : methods)
if (method.getName().equals("construct") && Modifier.isStatic(method.getModifiers()))
ctors.add(method);
for (final Executable ctor : ctors)
{
final List<ClauseArg> constructorArgs = new ArrayList<ClauseArg>();
final Annotation[] ctorAnnotations = ctor.getAnnotations();
final Annotation[][] annotations = ctor.getParameterAnnotations();
final Type[] types = ctor.getGenericParameterTypes();
final Parameter[] parameters = ctor.getParameters();
boolean isHidden = false;
for (int ca = 0; ca < ctorAnnotations.length; ca++)
{
final Annotation ann = ctorAnnotations[ca];
if (ann.annotationType().getName().equals("annotations.Hide"))
isHidden = true;
}
int prevOrType = 0; // 'or' type of previous item
int prevAndType = 0; // 'and' type of previous item
int orGroup = 0;
int andGroup = 0;
for (int n = 0; n < types.length; n++)
{
final Type type = types[n];
final String typeName = type.getTypeName();
// Args maintain own records of List<> and array[] nesting,
// so find base symbol without collections.
// **
// ** Assume it is Ludeme type unless proven otherwise.
// **
final Symbol temp = new Symbol(LudemeType.Ludeme, typeName, alias, cls); //null);
temp.setNesting(0);
final Symbol symbolP = findSymbolMatch(temp);
if (symbolP == null)
{
//System.out.println("- No matching symbolP found for symbol: " + symbol.name());
continue;
}
// Check for parameter name
String label = (n < parameters.length && parameters[n].isNamePresent())
? parameters[n].getName()
: null;
// Check for annotations
boolean optional = false;
boolean isNamed = false;
int orType = 0;
int andType = 0;
for (int a = 0; a < annotations[n].length; a++)
{
final Annotation ann = annotations[n][a];
if (ann.annotationType().getName().equals("annotations.Opt"))
optional = true;
if (ann.annotationType().getName().equals("annotations.Name"))
isNamed = true;
if (ann.annotationType().getName().equals("annotations.Or"))
orType = 1;
if (ann.annotationType().getName().equals("annotations.Or2"))
{
if (orType != 0)
System.out.println("** Both @Or and @Or2 specified for label.");
orType = 2;
}
if (ann.annotationType().getName().equals("annotations.And"))
andType = 1;
if (ann.annotationType().getName().equals("annotations.And2"))
{
if (andType != 0)
System.out.println("** Both @And and @And2 specified for label.");
andType = 2;
}
}
final String actualParameterName = (label == null) ? null : new String(label);
if (!isNamed)
label = null;
if (orType != 0 && orType != prevOrType)
orGroup++; // new consecutive 'or' group
if (andType != 0 && andType != prevAndType)
andGroup++; // new consecutive 'and' group
final ClauseArg arg = new ClauseArg
(
symbolP, actualParameterName, label, optional,
(orType == 0 ? 0 : orGroup),
(andType == 0 ? 0 : andGroup)
);
int nesting = 0;
for (int c = 0; c < typeName.length() - 1; c++)
if (typeName.charAt(c) == '[' && typeName.charAt(c + 1) == ']')
nesting++;
if (nesting > 0)
arg.setNesting(nesting);
constructorArgs.add(arg);
prevOrType = orType;
prevAndType = andType;
}
final Clause clause = new Clause(symbol, constructorArgs, isHidden);
rule.addToRHS(clause);
}
}
/**
* @param symbol
* @return Specified symbol, else null if not found.
*/
Symbol findSymbolMatch(final Symbol symbol)
{
for (final Symbol sym : symbols)
if (sym.matches(symbol))
return sym;
return null;
}
//-------------------------------------------------------------------------
/**
* Cross-reference subclass LHSs to clauses in superclass rules.
*/
void crossReferenceSubclasses()
{
for (final Symbol symbol : symbols)
{
if (!symbol.isClass())
continue;
if (symbol.hidden())
continue;
final Class<?> cls = symbol.cls();
if (cls == null)
continue;
final Class<?> clsSuper = cls.getSuperclass();
if (clsSuper == null)
continue;
final Symbol symbolSuper = findSymbolByPath(clsSuper.getName());
if (symbolSuper == null)
continue;
final GrammarRule ruleSuper = findRule(symbolSuper);
if (ruleSuper == null)
continue;
final Clause clause = new Clause(symbol);
if (!ruleSuper.containsClause(clause))
ruleSuper.addToRHS(clause);
}
}
//-------------------------------------------------------------------------
/**
* Add clauses for rules of overridden return types.
*/
void addReturnTypeClauses()
{
for (final Symbol symbol : symbols)
{
// final boolean isAdd = symbol.cls().getName().equals("game.functions.graph.operators.Add");
// if (isAdd)
// System.out.println("\n" + symbol.cls().getName());
if (!symbol.isClass() || symbol.matches(symbol.returnType()))
continue; // not overridden
if (symbol.hidden())
continue;
final GrammarRule rule = findRule(symbol.returnType());
if (rule == null)
continue;
final Clause clause = new Clause(symbol);
if (!rule.containsClause(clause))
{
rule.addToRHS(clause);
// if (isAdd)
// System.out.println("- Adding clause to rule: " + rule);
}
}
}
//-------------------------------------------------------------------------
void addApplicationConstantsToRule()
{
// Find <int> symbol and rule
Symbol symbolInt = null;
for (final Symbol symbol : symbols)
if (symbol.grammarLabel().equals("int"))
{
symbolInt = symbol;
break;
}
if (symbolInt == null)
throw new RuntimeException("Failed to find symbol for <int>.");
final GrammarRule ruleInt = findRule(symbolInt);
if (ruleInt == null)
throw new RuntimeException("Failed to find <int> rule.");
// Find each constant symbol and add to <int> rule
for (int cs = 0; cs < ApplicationConstants.length; cs++)
for (final Symbol symbol : symbols)
if (symbol.grammarLabel().equals(ApplicationConstants[cs][0]))
{
ruleInt.addToRHS(new Clause(symbol));
break;
}
}
//-------------------------------------------------------------------------
/**
* Link symbols and rules to packages.
*/
void linkToPackages()
{
// Cross-reference symbols to their packages
for (final Symbol symbol : symbols)
symbol.setPack(findPackage(symbol.notionalLocation()));
// List rules per packages
for (final GrammarRule rule : getRules())
{
final PackageInfo pack = rule.lhs().pack();
// Hack to stop duplicate rules showing for primitives.
//
// TODO: Stop out why these redundant rules are being added in the first place.
// CBB: Does not affect operation, not urgent, fix when convenient.
//
if
(
(
rule.lhs().grammarLabel().equals("int")
||
rule.lhs().grammarLabel().equals("boolean")
||
rule.lhs().grammarLabel().equals("float")
)
&&
rule.rhs().size() == 1
)
continue;
if (pack != null)
pack.add(rule);
}
}
//-------------------------------------------------------------------------
/**
* Set display order of rules and packages.
*/
void setDisplayOrder(final Symbol rootSymbol)
{
// Order packages in depth-first order from root package
for (final PackageInfo pack : packages)
{
pack.listAlphabetically();
prioritiseSuperClasses(pack);
prioritisePackageClass(pack);
}
setPackageOrder(rootSymbol);
}
//-------------------------------------------------------------------------
/**
* Order rules within each package so the base class comes first.
* @param pack
*/
static void prioritisePackageClass(final PackageInfo pack)
{
//final List<GrammarRule> rulesP = pack.rules();
// First pass: Promote partial match (e.g. "player")
final List<GrammarRule> promote = new ArrayList<GrammarRule>();
for (int r = pack.rules().size()-1; r >= 0; r--)
{
final GrammarRule rule = pack.rules().get(r);
if
(
pack.path().contains(rule.lhs().grammarLabel())
&&
rule.lhs().grammarLabel().length() >= 3 // avoid trivial matches such as "le" in "boolean"
)
{
// Partial match found
pack.remove(r);
//rulesP.add(0, rule);
promote.add(rule);
// break;
// System.out.println("Promoting rule " + rule.lhs().name() + " (A).");
}
}
for (final GrammarRule rule : promote)
pack.add(0, rule);
// Second pass: Promote exact match (e.g. "players")
promote.clear();
for (int r = pack.rules().size()-1; r >= 0; r--)
{
final GrammarRule rule = pack.rules().get(r);
if (pack.path().equals(rule.lhs().name()))
{
// Exact match found
pack.remove(r);
//rulesP.add(0, rule);
promote.add(rule);
// break;
// System.out.println("Promoting rule " + rule.lhs().name() + " (B).");
}
}
for (final GrammarRule rule : promote)
pack.add(0, rule);
}
//-------------------------------------------------------------------------
/**
* Prioritise rule order within packages so that superclasses come before
* subclasses.
*
* @param pack
*/
static void prioritiseSuperClasses(final PackageInfo pack)
{
// Move symbol with same name as package to top of package list
for (int n = 0; n < pack.rules().size(); n++)
{
final GrammarRule rule = pack.rules().get(n);
if (rule.lhs().name().equalsIgnoreCase(pack.shortName()))
{
pack.remove(n);
pack.add(0, rule);
}
}
// Swap when collection of symbols is in wrong order
for (int a = 0; a < pack.rules().size(); a++)
{
final GrammarRule ruleA = pack.rules().get(a);
for (int b = a + 1; b < pack.rules().size(); b++)
{
final GrammarRule ruleB = pack.rules().get(b);
if (ruleB.lhs().isCollectionOf(ruleA.lhs()))
{
pack.remove(b);
pack.remove(a);
pack.add(a, ruleB);
pack.add(b, ruleA);
}
}
}
}
//-------------------------------------------------------------------------
void linkDirectionsRules()
{
// Add clauses for <directionFacing> rule
final Symbol symbolDirectionFacing = findSymbolByPath("game.util.directions.DirectionFacing");
symbolDirectionFacing.setUsedInGrammar(true);
final Symbol symbolCompass = findSymbolByPath("game.util.directions.CompassDirection");
symbolCompass.setUsedInGrammar(true);
final Symbol symbolRotational = findSymbolByPath("game.util.directions.RotationalDirection");
symbolCompass.setUsedInGrammar(true);
final Symbol symbolSpatial = findSymbolByPath("game.util.directions.SpatialDirection");
symbolSpatial.setUsedInGrammar(true);
final GrammarRule ruleDirectionFacing = findRule(symbolDirectionFacing);
ruleDirectionFacing.addToRHS(new Clause(symbolCompass));
ruleDirectionFacing.addToRHS(new Clause(symbolRotational));
ruleDirectionFacing.addToRHS(new Clause(symbolSpatial));
// Add clauses for <direction> rule
final Symbol symbolAbsolute = findSymbolByPath("game.util.directions.AbsoluteDirection");
symbolAbsolute.setUsedInGrammar(true);
final Symbol symbolRelative = findSymbolByPath("game.util.directions.RelativeDirection");
symbolRelative.setUsedInGrammar(true);
final Symbol symbolDirections = findSymbolByPath("game.functions.directions.Directions");
symbolDirections.setUsedInDescription(true);
symbolDirections.setUsedInGrammar(true);
final Symbol symbolIf = findSymbolByPath("game.functions.directions.If");
symbolIf.setUsedInDescription(true);
symbolIf.setUsedInGrammar(true);
// ruleDirectionFacing.addToRHS(new Clause(symbolAbsolute));
// ruleDirectionFacing.addToRHS(new Clause(symbolRelative));
// ruleDirectionFacing.addToRHS(new Clause(symbolDirections));
// ruleDirectionFacing.addToRHS(new Clause(symbolIf));
// Add clauses for <direction>
final Symbol symbolDirection = findSymbolByPath("game.util.directions.Direction");
symbolDirection.setUsedInGrammar(true);
final GrammarRule ruleDirection = findRule(symbolDirection);
ruleDirection.addToRHS(new Clause(symbolAbsolute));
ruleDirection.addToRHS(new Clause(symbolRelative));
ruleDirection.addToRHS(new Clause(symbolDirections));
ruleDirection.addToRHS(new Clause(symbolIf));
}
//-------------------------------------------------------------------------
void linkRegionRules()
{
final Symbol symbolRegion = findSymbolByPath("game.util.equipment.Region");
final GrammarRule ruleRegion = findRule(symbolRegion);
final Symbol symbolSites = findSymbolByPath("game.functions.region.sites.Sites");
final GrammarRule ruleSites = findRule(symbolSites);
for (final Clause clause : ruleRegion.rhs())
ruleSites.addToRHS(clause);
symbolRegion.setUsedInDescription(false);
symbolSites.setUsedInDescription(true);
// Remove <equipment.region> rule
for (int r = getRules().size() - 1; r >= 0; r--)
{
final GrammarRule rule = getRules().get(r);
if (rule.lhs().grammarLabel().equals("equipment.region"))
getRules().remove(r);
}
}
//-------------------------------------------------------------------------
void handleDimFunctions()
{
// Find <dim> symbol and rule
final Symbol symbolDim = findSymbolByPath("game.functions.dim.BaseDimFunction");
symbolDim.setUsedInDescription(true);
final GrammarRule ruleDim = findRule(symbolDim);
// Find <int> symbol
Symbol symbolInt = null;
for (final Symbol symbol : symbols)
if (symbol.grammarLabel().equals("int"))
{
symbolInt = symbol;
break;
}
if (symbolInt == null)
throw new RuntimeException("Failed to find symbol for <int>.");
ruleDim.addToRHS(new Clause(symbolInt));
}
void handleGraphAndRangeFunctions()
{
final Symbol symbolGraph = findSymbolByPath("game.functions.graph.BaseGraphFunction");
symbolGraph.setUsedInGrammar(true);
symbolGraph.setUsedInDescription(true);
final Symbol symbolRange = findSymbolByPath("game.functions.range.BaseRangeFunction");
symbolRange.setUsedInGrammar(true);
symbolRange.setUsedInDescription(true);
}
/**
* Remove class name from track step declarations.
*/
void handleTrackSteps()
{
// final Symbol symbolTrackStep = findSymbolByPath("game.util.equipment.TrackStep");
// final GrammarRule ruleTrackStep = findRule(symbolTrackStep);
//
// final Symbol symbolDim = findSymbolByPath("game.functions.dim.BaseDimFunction");
// //final GrammarRule ruleDim = findRule(symbolDim);
//
// final Symbol symbolDirn = findSymbolByPath("game.util.directions.Compass");
// //final GrammarRule ruleDirn = findRule(symbolDirn);
//
// final Symbol symbolStep = findSymbolByPath("game.types.board.TrackStepType");
// //final GrammarRule ruleStep = findRule(symbolStep);
//
// ruleTrackStep.clearRHS();
//
// ruleTrackStep.addToRHS(new Clause(symbolDim));
// ruleTrackStep.addToRHS(new Clause(symbolDirn));
// ruleTrackStep.addToRHS(new Clause(symbolStep));
}
//-------------------------------------------------------------------------
/**
* Set package order for printing.
*/
void visitSymbols(final Symbol rootSymbol)
{
if (rootSymbol == null)
{
System.out.println("** GrammarWriter.visitSymbols() error: Null root symbol.");
return;
}
final boolean isGame = rootSymbol.name().contains("Game");
// Don't initialise values, as <directions> would not be picked up
// // Prepare export queue, depth first from root
// for (final Symbol symbol : symbols)
// {
// symbol.setVisited(false);
// symbol.setDepth(Constants.UNDEFINED);
//
// if (isGame)
// symbol.setUsedInGrammar(false);
// else
// symbol.setUsedInMetadata(false);
// }
visitSymbol(rootSymbol, 0, isGame);
}
/**
* Visit symbols in depth first order and record packages in order.
* @param symbol
*/
void visitSymbol(final Symbol symbol, final int depth, final boolean isGame)
{
if (symbol == null)
return; // no effect on which rules to show
if (symbol.depth() == Constants.UNDEFINED)
symbol.setDepth(depth);
else if (depth < symbol.depth())
symbol.setDepth(depth); // overwrite existing depth with a shallower one
if (symbol.visited())
return;
if (isGame)
{
//symbol.setUsedInDescription(true);
symbol.setUsedInGrammar(true);
}
else
{
symbol.setUsedInMetadata(true);
}
symbol.setVisited(true);
if (symbol.ludemeType() == LudemeType.Constant)
return;
if (symbol.rule() == null || symbol.rule().rhs() == null)
return; // probably redirected return type
if (symbol.rule().rhs() == null)
System.out.println("* Symbol with null expression: " + symbol.grammarLabel()); //symbol.name());
// Don't add steps for abstract or hidden classes, which do not appear in the grammar
final boolean isVisible = !symbol.isAbstract() && !symbol.hidden();
final int nextDepth = depth + (isVisible ? 1 : 0);
// Recurse to embedded symbols in RHS expression
for (final Clause clause : symbol.rule().rhs())
{
visitSymbol(clause.symbol(), nextDepth, isGame);
// Check for matching clause symbols
for (final GrammarRule ruleC : getRules())
if (ruleC.lhs().validReturnType(clause))
visitSymbol(ruleC.lhs().returnType(), nextDepth, isGame);
// **
// ** TODO: Have more general arg matching, e.g. play() is easily missed.
// **
// Check for matching arg symbols
if (clause.args() != null) // is a constructor
for (final ClauseArg arg : clause.args())
{
visitSymbol(arg.symbol(), nextDepth, isGame);
for (final GrammarRule ruleA : getRules())
if (ruleA.lhs().validReturnType(arg))
visitSymbol(ruleA.lhs().returnType(), nextDepth, isGame);
}
}
}
//-------------------------------------------------------------------------
/**
* Set package order for printing.
*/
void setPackageOrder(final Symbol rootSymbol)
{
packageOrder.clear();
if (rootSymbol == null)
{
System.out.println("** GrammarWriter.setPackageOrder() error: Null root symbol.");
return;
}
// Prepare export queue, depth first from root
for (final Symbol symbol : symbols)
symbol.setVisited(false);
setPackageOrderRecurse(rootSymbol);
// Move utility packages to end of list
final String[] packsToMove =
{
"game.functions",
"game.util",
"game.types",
};
for (int pm = 0; pm < packsToMove.length; pm++)
for (int p = packageOrder.size()-1; p >= 0; p--)
if (packageOrder.get(p).path().contains(packsToMove[pm]))
{
// Move this package to the bottom of the list
final PackageInfo packInfo = packageOrder.get(p);
packageOrder.remove(p);
packageOrder.add(packInfo);
}
}
/**
* Visit symbols in depth first order and record packages in order.
* @param symbol
*/
void setPackageOrderRecurse(final Symbol symbol)
{
if (symbol == null || symbol.visited() || symbol.ludemeType() == LudemeType.Constant)
return; // no effect on which rules to show
symbol.setVisited(true);
if (symbol.rule() == null || symbol.rule().rhs() == null)
return; // probably redirected return type
final PackageInfo pack = symbol.pack();
if (pack == null)
{
//System.out.println("* Null pack for symbol='" + symbol.toString() + "'.");
return; // probably String
}
int p;
for (p = 0; p < packageOrder.size(); p++)
if (packageOrder.get(p).path().equals(pack.path()))
break;
if (p >= packageOrder.size())
packageOrder.add(pack); // add unvisited package to the list
if (symbol.rule().rhs() == null)
{
System.out.println("* Symbol with null expression: " + symbol.grammarLabel()); //symbol.name());
}
// Recurse to embedded symbols in RHS expression
for (final Clause clause : symbol.rule().rhs())
{
setPackageOrderRecurse(clause.symbol());
// Check for matching clause symbols
for (final GrammarRule ruleC : getRules())
if (ruleC.lhs().validReturnType(clause))
{
setPackageOrderRecurse(ruleC.lhs().returnType());
}
// **
// ** TODO: Have more general arg matching, e.g. play() is easily missed.
// **
// Check for matching arg symbols
if (clause.args() != null) // is a constructor
for (final ClauseArg arg : clause.args())
{
setPackageOrderRecurse(arg.symbol());
for (final GrammarRule ruleA : getRules())
if (ruleA.lhs().validReturnType(arg))
setPackageOrderRecurse(ruleA.lhs().returnType());
}
}
}
//-------------------------------------------------------------------------
/**
* Remove rules and clauses with redundant function and constant names.
*/
void removeRedundantFunctionNames()
{
for (final GrammarRule rule : getRules())
{
// Remove redundant function rules by turning off LHS
for (int f = 0; f < getFunctions().length; f++)
if (rule.lhs().grammarLabel().equalsIgnoreCase(getFunctions()[f][0]))
{
rule.lhs().setUsedInDescription(false);
rule.lhs().setUsedInMetadata(false);
}
// Remove redundant clauses from rules
for (int c = rule.rhs().size() - 1; c >= 0; c--)
{
final Clause clause = rule.rhs().get(c);
for (int f = 0; f < getFunctions().length; f++)
if (clause.symbol().grammarLabel().equalsIgnoreCase(getFunctions()[f][0]))
{
rule.removeFromRHS(c);
break;
}
}
}
}
//-------------------------------------------------------------------------
void alphabetiseRuleClauses()
{
for (final GrammarRule rule : getRules())
rule.alphabetiseClauses();
}
//-------------------------------------------------------------------------
/**
* Removes duplicate clauses from rules,
* For example, <int> ::= Off | Off
*
* BE CAREFUL: Do not eliminate multiple constructors!
*
*/
void removeDuplicateClauses()
{
for (final GrammarRule rule : getRules())
{
for (int ca = rule.rhs().size() - 1; ca >= 0; ca--)
{
final Clause clauseA = rule.rhs().get(ca);
if (clauseA.isConstructor())
continue; // don't remove
boolean doRemove = false;
for (int cb = ca - 1; cb >= 0; cb--)
{
final Clause clauseB = rule.rhs().get(cb);
if (clauseA.matches(clauseB))
{
doRemove = true;
break;
}
}
if (doRemove)
rule.removeFromRHS(ca);
}
}
}
//-------------------------------------------------------------------------
/**
* Filter out redundant rules for primitive wrapper classes
*/
void filterOutPrimitiveWrappers()
{
// Filter out trivial rules that map primitive filters to themselves
for (final GrammarRule rule : getRules())
{
if
(
rule.lhs().grammarLabel().equals("Integer")
&&
rule.rhs().size() == 1
&&
rule.rhs().get(0).symbol().grammarLabel().equals("Integer")
||
rule.lhs().grammarLabel().equals("Float")
&&
rule.rhs().size() == 1
&&
rule.rhs().get(0).symbol().grammarLabel().equals("Float")
||
rule.lhs().grammarLabel().equals("Boolean")
&&
rule.rhs().size() == 1
&&
rule.rhs().get(0).symbol().grammarLabel().equals("Boolean")
||
rule.lhs().grammarLabel().equals("String")
&&
rule.rhs().size() == 1
&&
rule.rhs().get(0).symbol().grammarLabel().equals("String")
)
{
rule.lhs().setUsedInDescription(false); // turn off so is not shown in grammar
rule.lhs().setUsedInMetadata(false); // turn off so is not shown in grammar
}
}
// Replace primitive wrapper symbols on RHS with their primitive equivalents
Symbol symbolInt = null;
Symbol symbolFloat = null;
Symbol symbolBoolean = null;
Symbol symbolString = null;
// Symbol symbolTrue = null;
// Symbol symbolFalse = null;
for (final Symbol symbol : symbols)
{
if (symbol.grammarLabel().equals("int"))
symbolInt = symbol;
if (symbol.grammarLabel().equals("float"))
symbolFloat = symbol;
if (symbol.grammarLabel().equals("boolean"))
symbolBoolean = symbol;
if (symbol.grammarLabel().equals("String"))
symbolString = symbol;
// if (symbol.grammarLabel().equals("true"))
// symbolTrue = symbol;
// if (symbol.grammarLabel().equals("false"))
// symbolFalse = symbol;
}
for (final GrammarRule rule : getRules())
for (final Clause clause : rule.rhs())
if (clause != null && clause.args() != null)
for (final ClauseArg arg : clause.args())
{
if (arg.symbol().grammarLabel().equals("Integer"))
arg.setSymbol(symbolInt);
if (arg.symbol().grammarLabel().equals("Float"))
arg.setSymbol(symbolFloat);
if (arg.symbol().grammarLabel().equals("Boolean"))
arg.setSymbol(symbolBoolean);
if (arg.symbol().grammarLabel().equals("String"))
arg.setSymbol(symbolString);
}
// // Add 'true' and 'false' constants to <boolean> rule
// for (final GrammarRule rule : rules)
// if (rule.lhs().grammarLabel().equals("boolean"))
// {
// rule.add(new Clause(symbolTrue));
// rule.add(new Clause(symbolFalse));
// }
// // Remove rule for primitive wrappers
// for (int r = rules.size() - 1; r >= 0; r--)
// {
// final GrammarRule rule = rules.get(r);
//
// //System.out.println("Rule for: " + rule.lhs().cls().getName());
//
// if
// (
// rule.lhs().cls().getName().equals("java.lang.Integer")
// ||
// rule.lhs().cls().getName().equals("java.lang.Boolean")
// ||
// rule.lhs().cls().getName().equals("java.lang.Float")
// ||
// rule.lhs().cls().getName().contains("Function")
// ||
// rule.lhs().cls().getName().contains("Constant")
// )
// {
// //System.out.println("** Removing rule for: " + rule.lhs().cls().getName());
// rule.lhs().setUsedInGrammar(false);
// rule.lhs().setUsedInDescription(false);
// rule.lhs().setUsedInMetadata(false);
//
// rules.remove(r);
// }
// }
}
//-------------------------------------------------------------------------
/**
* Instantiate enums in-place if they only have one value.
*/
void instantiateSingleEnums()
{
// Instantiate single enum values
for (final GrammarRule rule : getRules())
for (final Clause clause : rule.rhs())
if (clause != null && clause.args() != null)
for (int a = clause.args().size() - 1; a >= 0; a--)
{
final ClauseArg arg = clause.args().get(a);
final Symbol symbol = arg.symbol();
if (symbol.cls() != null && symbol.cls().isEnum())
{
final GrammarRule ruleS = symbol.rule();
if (ruleS != null && ruleS.rhs().size() == 1)
{
final Clause enumValue = ruleS.rhs().get(0);
arg.setSymbol(enumValue.symbol());
enumValue.symbol().setUsedInGrammar(true);
}
}
}
// Remove enum rules with a single value (should have all been picked up by previous test)
for (int r = getRules().size() - 1; r >= 0; r--)
{
final GrammarRule rule = getRules().get(r);
if (rule.lhs().cls() != null && rule.lhs().cls().isEnum() && rule.rhs().size() == 1)
getRules().remove(r);
}
}
//-------------------------------------------------------------------------
/**
* @return Returns a string containing the path abbreviation for each ludeme and the name of the ludeme.
*/
public String getFormattedSymbols()
{
String str = "";
for (final Symbol s : symbols)
{
final String[] pathList = s.path().split("\\.");
String strAbrev = "";
for (int i = 0; i < pathList.length; i++)
{
strAbrev += pathList[i].charAt(0);
}
str += "\n" + strAbrev + " : " + s.toString().replace("<", "").replace(">", "");
}
return str;
}
//-------------------------------------------------------------------------
/**
* Export grammar to file.
* @param fileName
* @throws IOException
*/
public void export(final String fileName) throws IOException
{
final File file = new File(fileName);
if (!file.exists())
file.createNewFile();
try
(
final FileWriter fw = new FileWriter(file.getName(), false);
final BufferedWriter writer = new BufferedWriter(fw);
)
{
final String str = toString();
writer.write(str);
}
}
//-------------------------------------------------------------------------
/**
* Tidy up final result, including replacing function names with return types.
*/
private void tidyUpFormat()
{
// Replace remaining function names
for (int f = 0; f < getFunctions().length; f++)
{
String name = getFunctions()[f][0];
name = name.substring(0, 1).toLowerCase() + name.substring(1); // lowerCamelCase keyword
for (final GrammarRule rule : rules)
{
String label = rule.lhs().grammarLabel();
if (label.contains(name))
{
label = label.replace(name, getFunctions()[f][1]);
rule.lhs().setGrammarLabel(label);
}
}
}
}
//-------------------------------------------------------------------------
/**
* Set flag for ludemes used in the grammar.
*/
private void setUsedInGrammar()
{
// Start with all symbols that can occur in descriptions and metadata
for (final Symbol symbol : symbols)
{
if
(
symbol.usedInDescription()
// ||
// symbol.usedInMetadata()
)
{
symbol.setUsedInGrammar(true);
continue;
}
}
// Iteratively find rules that use them
boolean didUpdate = false;
do
{
didUpdate = false;
for (final GrammarRule rule : rules)
{
if (rule.lhs().usedInGrammar())
for (final Clause clause : rule.rhs())
if (!clause.symbol().usedInGrammar())
{
clause.symbol().setUsedInGrammar(true);
didUpdate = true;
}
}
} while (didUpdate);
}
//-------------------------------------------------------------------------
/**
* Set flag for ludemes used in game descriptions.
* These will have instantiations in RHS rule clauses.
*/
private void setUsedInDescription()
{
for (final GrammarRule rule : rules)
for (final Clause clause : rule.rhs())
{
final Symbol symbol = clause.symbol();
if (!symbol.usedInGrammar())
continue; // don't include metadata
if
(
clause.isConstructor()
||
symbol.isTerminal()
)
symbol.setUsedInDescription(true);
if (clause.args() != null)
{
// Also check clause args for enum constants etc.
for (final ClauseArg arg : clause.args())
{
final Symbol argSymbol = arg.symbol();
if (!argSymbol.usedInGrammar())
continue; // don't include metadata
if (argSymbol.isTerminal())
argSymbol.setUsedInDescription(true);
}
}
}
}
//-------------------------------------------------------------------------
/**
* Set flag for ludemes used in metadata.
*/
private void setUsedInMetadata()
{
for (final Symbol symbol : symbols)
{
// if (symbol.cls() != null && MetadataItem.class.isAssignableFrom(symbol.cls()))
// {
// System.out.println("Metadata symbol path: " + symbol.path());
// symbol.setUsedInMetadata(true);
// }
// Avoid dependency on Core
if (symbol.path().contains("metadata"))
symbol.setUsedInMetadata(true);
}
for (final GrammarRule rule : rules)
for (final Clause clause : rule.rhs())
{
final Symbol symbol = clause.symbol();
if (!symbol.usedInMetadata())
continue; // don't include grammar
if (clause.args() != null)
{
// Check metadata clause args
for (final ClauseArg arg : clause.args())
{
final Symbol argSymbol = arg.symbol();
argSymbol.setUsedInMetadata(true);
}
}
}
}
//-------------------------------------------------------------------------
/**
* Set ludeme type for each symbol.
*/
private void setLudemeTypes()
{
for (final Symbol symbol : symbols)
{
final Class<?> cls = symbol.cls();
if (cls == null)
{
// Symbol has no class
System.out.println("Symbol has no class: " + symbol);
symbol.setLudemeType(null);
continue;
}
if (cls.isEnum())
{
symbol.setLudemeType(LudemeType.Constant);
}
else if
(
cls.getSimpleName().equals("String")
||
cls.getSimpleName().equals("Integer")
||
cls.getSimpleName().equals("Float")
||
cls.getSimpleName().equals("Boolean")
)
{
symbol.setLudemeType(LudemeType.Predefined);
}
else if
(
cls.getSimpleName().equals("int")
||
cls.getSimpleName().equals("float")
||
cls.getSimpleName().equals("boolean")
)
{
symbol.setLudemeType(LudemeType.Primitive);
}
else
{
// Must be a ludeme class
if (cls.isInterface())
{
// Assume is structural rule that links subrules but is never instantiated
//System.out.println("** Is an interface: " + this);
symbol.setLudemeType(LudemeType.Structural);
}
else
{
// Check for super ludeme
final Constructor<?>[] constructors = cls.getConstructors();
if (constructors.length == 0)
{
// No constructors: probably a super ludeme
//System.out.println("** No constructors found for: " + this);
symbol.setLudemeType(LudemeType.SuperLudeme);
}
else
{
symbol.setLudemeType(LudemeType.Ludeme);
}
}
}
}
// Overwrite ludemes that appear in grammar but not descriptions as structural
for (final GrammarRule rule : rules)
{
final Symbol symbol = rule.lhs();
if
(
(symbol.usedInGrammar() || symbol.usedInMetadata())
&&
!symbol.usedInDescription()
)
symbol.setLudemeType(LudemeType.Structural);
}
// Class<?> clsT = null;
// try
// {
// clsT = Class.forName("game.types.play.GravityType");
// } catch (ClassNotFoundException e)
// {
// e.printStackTrace();
// }
// System.out.println(clsT);
// System.out.println("Is enum: " + clsT.isEnum());
// Check for incorrectly labelled enum types
for (final Symbol symbol : symbols)
{
final Class<?> cls = symbol.cls();
if (cls.isEnum() && symbol.ludemeType() == LudemeType.Constant)
{
// Is classified as an enum constant
// System.out.println("Enum class " + symbol.token() + " is type: " + symbol.ludemeType());
// Check if is actually a constant...
boolean isConstant = false;
final Object[] constants = cls.getEnumConstants();
for (final Object obj : constants)
if (obj.toString().equals(symbol.token()))
{
// System.out.println("- Constant obj: " + obj.toString());
isConstant = true;
break;
}
if (!isConstant)
{
// Correct this mistakenly classified enum class
symbol.setLudemeType(LudemeType.Ludeme);
//symbol.setSymbolType(SymbolType.Class);
}
}
}
findSubludemes();
}
// /**
// * Find subludemes.
// * These will be be classes in the subfolder of a superludeme (or below)
// * that are not in the grammar or game descriptions.
// */
// private void findSubludemes()
// {
// // Find all super ludemes and store package
// final Map<String, Symbol> supers = new HashMap<>();
// for (final Symbol symbol : symbols)
// if (symbol.ludemeType() == LudemeType.SuperLudeme)
// {
// String path = symbol.path();
// path = path.substring(0, path.lastIndexOf('.'));
// supers.put(path, symbol);
// }
//
// // Find all ludeme classes that do not appear in grammar
// // and are in a superludeme package (or below).
// for (final Symbol symbol : symbols)
// {
// if (symbol.ludemeType() != LudemeType.Ludeme)
// continue; // can't be a subludeme
//
// if (symbol.usedInGrammar() || symbol.usedInDescription())
// continue; // can't be a subludeme
//
// if (symbol.name().contains("Type"))
// {
// // is parameter type class
// symbol.setLudemeType(LudemeType.Structural);
// continue;
// }
//
// for (final String superPath : supers.keySet())
// if (symbol.path().contains(superPath))
// {
// symbol.setLudemeType(LudemeType.SubLudeme);
// break;
// }
// }
// }
/**
* Find subludemes.
* These will be be classes in the subfolder of a superludeme (or below)
* that are not in the grammar or game descriptions.
*/
private void findSubludemes()
{
// Find all super ludemes and store package
final Map<String, Symbol> supers = new HashMap<>();
for (final Symbol symbol : symbols)
if (symbol.ludemeType() == LudemeType.SuperLudeme)
{
String path = symbol.path();
path = path.substring(0, path.lastIndexOf('.'));
supers.put(path, symbol);
}
// Find all ludeme classes that do not appear in grammar
// and are in a superludeme package (or below).
for (final Symbol symbol : symbols)
{
if (symbol.ludemeType() != LudemeType.Ludeme)
continue; // can't be a subludeme
if (symbol.usedInGrammar() || symbol.usedInDescription())
continue; // can't be a subludeme
if (symbol.name().contains("Type"))
{
// is parameter type class
symbol.setLudemeType(LudemeType.Structural);
// if (symbol.name().equalsIgnoreCase("isLineType"))
// System.out.println("IsLineType subludeme found...");
// Catch super ludeme parameter enum types
for (final String superPath : supers.keySet())
if (symbol.path().contains(superPath))
symbol.setSubLudemeOf(supers.get(superPath));
continue;
}
for (final String superPath : supers.keySet())
if (symbol.path().contains(superPath))
{
symbol.setLudemeType(LudemeType.SubLudeme);
symbol.setSubLudemeOf(supers.get(superPath));
break;
}
}
// Now catch super ludeme enum parameter types
for (final Symbol symbol : symbols)
{
if (symbol.ludemeType() != LudemeType.Ludeme)
continue; // can't be a subludeme
if (!symbol.name().contains("Type"))
continue; // not a super ludeme enum parameter type
for (final String superPath : supers.keySet())
if (symbol.path().contains(superPath))
{
if (symbol.usedInGrammar() || symbol.usedInDescription())
symbol.setLudemeType(LudemeType.Structural);
symbol.setSubLudemeOf(supers.get(superPath));
}
}
}
//-------------------------------------------------------------------------
/**
* Set ludeme type for each symbol.
*/
private void setAtomicLudemes()
{
// public static final String[][] Primitives =
// {
// { "int", "game.functions.ints" },
// };
//
// /** Predefined symbols (known data types) with notional and actual package names, and keyword. */
// public static final String[][] Predefined =
// {
// { "java.lang.Integer", "game.functions.ints", "java.lang", "int" },
// };
//
// /** Function names and associated constants. */
// private final String[][] Functions =
// {
// { "IntFunction", "int" },
// { "IntConstant", "int" },
// };
//
// /** Application constants. */
// public final static String[][] ApplicationConstants =
// {
// { "Off", "int", "global", ("" + Constants.OFF) },
// };
for (final Symbol symbol : symbols)
{
// 1. Set symbol as its own atomic symbol (unless proven otherwise)
symbol.setAtomicLudeme(symbol);
// 2. Primitives already remap to correct atomic ludeme
// Do nothing.
// 3. Remap predefined types
if (symbol.name().equals("String"))
continue; // special case
boolean found = false;
for (int n = 0; n < Predefined.length; n++)
if (symbol.cls().getName().equals(Predefined[n][0]))
{
// Is a predefined type
// System.out.println("Predefined type " + symbol.name() + "...");
// System.out.println("- return type is " + symbol.returnType());
final List<Symbol> to = this.symbolsByName.get(Predefined[n][3]);
if (to != null && to.size() >= 1)
{
// System.out.println(to.size( ) + " symbols found:");
// for (final Symbol st : to)
// System.out.println("-- " + st.name());
symbol.setAtomicLudeme(to.get(0));
found = true;
break;
}
//System.out.println("- return type is " + symbol.returnType());
}
if (found)
continue;
// 4. Remap functions
found = false;
for (int n = 0; n < Functions.length; n++)
if (symbol.name().equals(Functions[n][0]))
{
// Is a function
// System.out.println("Function type " + symbol.name() + "...");
// System.out.println("- return type is " + symbol.returnType());
symbol.setAtomicLudeme(symbol.returnType());
found = true;
break;
}
if (found)
continue;
// 5. Remap application constants
found = false;
for (int n = 0; n < ApplicationConstants.length; n++)
if
(
symbol.name().equals(ApplicationConstants[n][0])
&&
symbol.returnType().name().equals("int")
)
{
// Is a function
// System.out.println("Application constant " + symbol.name() + "...");
// System.out.println("- return type is " + symbol.returnType());
final List<Symbol> to = this.symbolsByName.get(ApplicationConstants[n][0]);
for (final Symbol st : to)
{
// System.out.println("-- " + st.name() + " (" + st.cls().getName() + ")");
if (!st.cls().getName().equals("int"))
continue; // only match to int type
// System.out.println("* Match *");
symbol.setAtomicLudeme(st);
found = true;
break;
}
}
if (found)
continue;
}
}
//-------------------------------------------------------------------------
/**
* @return List of ludemes used in grammar, with relevant info.
*/
public List<LudemeInfo> ludemesUsed()
{
// **
// ** Note: Assumes that simplest forms of ludemes are listed first!
// **
// ** e.g. boolean, Boolean, BooleanConstant and BooleanFunction
// ** will all reduce to first occurrence (boolean).
// **
// ** But different OS and/or Java version may list items in different order!
// **
final List<LudemeInfo> ludemesUsed = new ArrayList<>();
for (final Symbol symbol : symbols)
{
// if (symbol.path().equals("game.functions.booleans.math.Equals"))
// System.out.println("Equals...");
if (!symbol.usedInGrammar())
{
//System.out.println("Skipping: " + symbol.token() + " (" + symbol.cls().getName() + ")");
continue;
}
if (symbol.usedInMetadata() && !symbol.name().equals("String"))
continue;
// if (symbol.path().equals("game.functions.booleans.math.Equals"))
// System.out.println("A");
//symbol.usedInMetadata()
//||
//symbol.ludemeType() == LudemeType.SubLudeme
//||
//IncludeInGrammar.class.isAssignableFrom(symbol.cls())
// Check if symbol class has @Hide annotation
// boolean isHide = false;
// final Annotation[] annotations = symbol.cls().getAnnotations();
// for (int a = 0; a < annotations.length && !isHide; a++)
// if (annotations[a].annotationType().getName().equals("annotations.Hide"))
// isHide = true;
// if (isHide)
if (symbol.hidden())
{
//System.out.println("Skipping hidden ludeme class: " + symbol.name());
continue;
}
if
(
symbol.name().equals("Integer")
||
symbol.name().equals("Boolean")
||
symbol.name().equals("Float")
)
continue;
// if (symbol.path().equals("game.functions.booleans.math.Equals"))
// System.out.println("B");
if (symbol.ludemeType() != LudemeType.Constant)
{
// Check whether symbol is already present.
//
// We don't want to do this for constants, as we can
// legitimately have more than one constant with the
// same grammar label, e.g. All in RelationType, RoleType, etc.
//
boolean present = false;
for (final LudemeInfo used : ludemesUsed)
//if (used.symbol().token().equals(symbol.token()))
if (used.symbol().grammarLabel().equals(symbol.grammarLabel()))
{
present = true;
break;
}
if (present)
continue; // don't add duplicates, e.g. boolean/Boolean/BooleanConstant/BooleanFunction, etc.
}
// if (symbol.path().equals("game.functions.booleans.math.Equals"))
// System.out.println("C");
final LudemeInfo ludeme = new LudemeInfo(symbol);
// TODO: Add relevant info here: database id, JavaDoc help, etc.
ludemesUsed.add(ludeme);
}
// System.out.println("\n==================================\nLudemes used:");
// for (final LudemeInfo li : ludemesUsed)
// System.out.println(li.symbol().info());
return ludemesUsed;
}
//-------------------------------------------------------------------------
// /**
// * @return Set containing class names of all official ludemes.
// */
// public Set<String> ludemeNamesUsed()
// {
// final Set<String> set = new HashSet<String>();
//
// final List<LudemeInfo> ludemesUsed = ludemesUsed();
// for (final LudemeInfo ludeme : ludemesUsed)
// set.add(ludeme.symbol().cls().getName());
//
// return set;
// }
//-------------------------------------------------------------------------
/**
* Find ancestors of each symbol.
*/
private void findAncestors()
{
// Make symbol superclasses ancestors
for (final Symbol symbol : symbols)
{
Class<?> parent = symbol.cls();
while (true)
{
parent = parent.getSuperclass();
if (parent == null)
break;
final Symbol parentSymbol = findSymbolByPath(parent.getName());
if (parentSymbol == null)
break;
symbol.addAncestor(parentSymbol);
//System.out.println("Adding ancestor " + parentSymbol.name() + " to " + symbol.name() + ".");
}
}
// Set return type as ancestor (if not already present).
// This will catch enums in super ludeme enum parameter types, but not all ancestors of parent.
for (final Symbol symbol : symbols)
{
final Symbol parentSymbol = symbol.returnType();
if (parentSymbol == null)
continue;
if (parentSymbol.path().equals(symbol.path()))
continue; // symbol returns its own type
// Add parent symbol and its ancestors to current symbol
symbol.addAncestor(parentSymbol);
symbol.addAncestorsFrom(parentSymbol);
}
// Make super ludemes ancestors of their enum parameter types
for (final Symbol symbol : symbols)
{
final Symbol parentSymbol = symbol.subLudemeOf();
if (parentSymbol != null)
{
// Add parent symbol and its ancestors to current symbol
symbol.addAncestor(parentSymbol);
symbol.addAncestorsFrom(parentSymbol); // do we want to include ancestors of super ludeme?
}
}
// Set return type as ancestor (if not already present).
// Repeat to catch all ancestors of enums in super ludeme enum parameter types.
for (final Symbol symbol : symbols)
{
final Symbol returnSymbol = symbol.returnType();
if (returnSymbol == null)
continue;
if (returnSymbol.path().equals(symbol.path()))
continue; // symbol returns its own type
// Need to get actual symbol from the master list,
// as returnType() may be a duplicate (don't know why).
final Symbol parentSymbol = findSymbolByPath(returnSymbol.path());
// Add parent symbol and its ancestors to current symbol
symbol.addAncestor(parentSymbol);
symbol.addAncestorsFrom(parentSymbol);
}
// final Symbol is = findSymbolByPath("game.functions.booleans.is.Is");
// final Symbol isLineType = findSymbolByPath("game.functions.booleans.is.IsLineType");
// final Symbol line = findSymbolByPath("game.functions.booleans.is.IsLineType.Line");
// System.out.println("Line return type: " + line.returnType());
//
// System.out.println("Ancestors of Is: " + is.ancestors());
// System.out.println("Ancestors of IsLineType: " + isLineType.ancestors());
// System.out.println("Ancestors of Line: " + line.ancestors());
//
// System.out.println("IsLineType is type: " + isLineType.ludemeType());
// System.out.println("IsLineType is subludeme of: " + isLineType.subLudemeOf());
//
// System.out.print("Paths for Is are:");
// for (final Symbol symbol : symbolsByName("Is"))
// System.out.println(" " + symbol.path());
// System.out.println();
//
// System.out.print("Paths for IsLineType are:");
// for (final Symbol symbol : symbolsByName("IsLineType"))
// System.out.println(" " + symbol.path());
// System.out.println();
//
// System.out.print("Paths for Line are:");
// for (final Symbol symbol : symbolsByName("Line"))
// System.out.println(" " + symbol.path());
// System.out.println();
}
//-------------------------------------------------------------------------
/**
* @return Symbol details for debugging.
*/
public String symbolDetails()
{
final StringBuilder sb = new StringBuilder();
sb.append("\n+++++++++++++++++++ SYMBOLS ++++++++++++++++++++++\n");
for (final Symbol symbol : symbols)
sb.append(symbol.info() + "\n");
sb.append("\n\n++++++++++++++++++++ RULES +++++++++++++++++++++++\n");
for (final GrammarRule rule : getRules())
sb.append
(
(rule.lhs().usedInGrammar() ? "g" : "~") +
(rule.lhs().usedInDescription() ? "d" : "~") +
(rule.lhs().usedInMetadata() ? "m" : "~") +
" " + rule +
" [" + rule.lhs().cls().getName() + "] " +
"\n"
);
FileHandling.saveStringToFile(sb.toString(), "symbol-details.txt", "");
return(sb.toString());
}
//-------------------------------------------------------------------------
/**
* @return List of grammar rules.
*/
public List<GrammarRule> getRules()
{
return rules;
}
/**
* @return Function labels.
*/
public String[][] getFunctions()
{
return Functions;
}
//-------------------------------------------------------------------------
public String aliases()
{
final StringBuilder sb = new StringBuilder();
for (final Symbol symbol : symbols)
if (symbol.hasAlias())
sb.append(symbol.name() + " (" + symbol.path() + ") has alias: " + symbol.token() + "\n");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
for (final PackageInfo pack : packageOrder)
sb.append(pack.toString());
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 81,192 | 25.8762 | 111 |
java
|
Ludii
|
Ludii-master/Language/src/parser/Expander.java
|
package parser;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import exception.UnusedOptionException;
import main.FileHandling;
import main.StringRoutines;
import main.grammar.Define;
import main.grammar.DefineInstances;
import main.grammar.Description;
import main.grammar.Report;
import main.options.Option;
import main.options.OptionArgument;
import main.options.OptionCategory;
import main.options.Ruleset;
import main.options.UserSelections;
//-----------------------------------------------------------------------------
/**
* Expands raw user game description (.lud) into full game description with
* defines, options, rulesets and ranges realised for compilation.
*
* @author cambolbro
*/
public class Expander
{
private static final int MAX_EXPANSIONS = 1000;
private static final int MAX_CHARACTERS = 1000000;
private static final int MAX_RANGE = 1000;
private static final int MAX_DEFINE_ARGS = 20;
/** Placeholder character for null define parameters, e.g. ("Jump" ~ (from) ~ ~) */
public static final String DEFINE_PARAMETER_PLACEHOLDER = "~";
//-------------------------------------------------------------------------
/**
* Private constructor; don't allow class to be constructed.
*/
private Expander()
{
}
//-------------------------------------------------------------------------
/**
* Expands options and defines in user string to give full description. Pre:
* userDescription has already been set. Post: Result is stored in
* gameDescription.
*
* @param description The description.
* @param userSelections The user selections.
* @param report The report.
* @param isVerbose True if this is verbose.
*/
public static void expand
(
final Description description,
final UserSelections userSelections,
final Report report,
final boolean isVerbose
)
{
if (isVerbose)
{
//System.out.println("+++++++++++++++++++++\nExpanding:\n" + description.raw());
report.addLogLine("+++++++++++++++++++++\nExpanding:\n" + description.raw());
}
String str = new String(description.raw());
// Remove comments before any expansions
str = removeComments(str);
checkDefineCase(str, report);
// Must realise options before expanding defines -- not sure why
str = realiseOptions(str, description, userSelections, report);
if (report.isError())
return;
str = realiseRulesets(str, description, report);
if (report.isError())
return;
// // Store interim result as the "options expanded" description
// String strOptions = cleanUp(str, report);
// if (report.isError())
// return;
//
// final int c = strOptions.indexOf("(metadata");
// if (c >= 0)
// {
// // Remove metadata
// strOptions = strOptions.substring(0, c).trim();
// }
//
// System.out.println("strOptions expanded:\n" + strOptions);
//
// tokenise(strOptions, description, report, isVerbose);
// description.setOptionsExpanded(new String(description.tokenForest().toString())); // format tokens nicely
//
// System.out.println("Options expanded:\n" + description.optionsExpanded());
// Continue expanding defines for full description
str = expandDefines(str, report, description.defineInstances());
if (report.isError())
return;
// Do again after expanding defines, as external defines could have comments
str = removeComments(str);
// Do after expanding defines, as external defines could have ranges
str = expandRanges(str, report);
if (report.isError())
return;
str = expandSiteRanges(str, report);
if (report.isError())
return;
// Do metadata string extraction here rather than in compiler,
// as the metadata text needs defines and options expanded.
// Result is stored in expandedMetadataString.
str = extractMetadata(str, description, userSelections, report);
if (report.isError())
return;
str = cleanUp(str, report);
if (report.isError())
return;
if (isVerbose)
{
//System.out.println("Cleaned up:\n" + str);
report.addLogLine("Cleaned up:\n" + str);
}
// Tokenise expanded string to get full description
if (str == null || str.trim().isEmpty())
str = description.metadata(); // no game description, try tokenising metadata instead
tokenise(str, description, report, isVerbose);
// System.out.println("Token errors = " + report.isError());
description.setExpanded(new String(description.tokenForest().toString())); // format tokens nicely
// System.out.println(description.tokenTree().dump(""));
}
//-------------------------------------------------------------------------
public static String cleanUp(final String strIn, final Report report)
{
String str = strIn;
// Remove unneeded internal spaces
str = str.replaceAll("\n", " ");
str = str.replaceAll("\r", " ");
str = str.replaceAll("\t", " ");
while (str.contains(" "))
str = str.replaceAll(" ", " ");
while (str.contains(" "))
str = str.replaceAll(" ", " ");
str = str.replaceAll(" \\)", "\\)"); // regex doesn't like ")"
str = str.replaceAll("\\( ", "\\("); // regex doesn't like "("
str = str.replaceAll(" \\}", "\\}");
str = str.replaceAll("\\{ ", "\\{");
while (str.contains(": "))
str = str.replaceAll(": ", ":");
// // Hack so that ItemCount() objects don't need to be be named.
// // Do this AFTER all defines have been expanded!
// str = str.replaceAll("\\(\"", "\\(itemCount \"");
str = handleDoubleBrackets(str, report); // do this after reducing spaces
if (report != null && report.isError())
return null;
return str;
}
//-------------------------------------------------------------------------
/**
* Create token tree from the specified (expanded) string.
*
* @param str The string.
* @param description The description.
* @param report The report.
* @param isVerbose True if this is verbose.
*/
public static void tokenise
(
final String str,
final Description description,
final Report report,
final boolean isVerbose
)
{
//description.setTokenTree(new Token(str, report));
description.tokenForest().populate(str, report);
if (isVerbose)
{
//System.out.println("\nToken tree:\n" + description.tokenForest().tokenTree());
report.addLogLine("\nToken tree:\n" + description.tokenForest().tokenTree());
}
if
(
description.tokenForest().tokenTree() == null
||
description.tokenForest().tokenTree().type() == null
)
{
//System.out.println(description.tokenTree());
//throw new CantDecomposeException("Expander.tokenise()");
report.addError("Expander can't tokenise the game description.");
return; // not necessary but good practice
}
}
//-------------------------------------------------------------------------
/**
* Check for lowercase define labels.
*/
public static void checkDefineCase(final String str, final Report report)
{
// System.out.println(str);
int c = 0;
while (true)
{
c = str.indexOf("(define \"", c);
if (c < 0)
break;
final char ch = str.charAt(c + 9);
if (!Character.isUpperCase(ch))
{
// First char in define is not an uppercase letter
int cc = c + 9;
while (cc < str.length() && StringRoutines.isTokenChar(str.charAt(cc)))
cc++;
final String name = str.substring(c+9, cc);
final String msg = "Lowercase define name \"" + name + ".";
report.addLogLine(msg);
report.addWarning(msg);
report.addNote(msg);
//report.addError(msg);
System.out.println(msg);
}
c++;
}
}
//-------------------------------------------------------------------------
/**
* Handle double brackets.
* These will typically occur when a bracketed ("Define") is expanded.
* @return Game description with double brackets removed.
*/
private static String handleDoubleBrackets
(
final String strIn,
final Report report
)
{
if (!strIn.contains("(("))
return new String(strIn); // nothing to do
String str = new String(strIn);
while (true)
{
final int c = str.indexOf("((");
if (c < 0)
break; // all done
final int cc = StringRoutines.matchingBracketAt(str, c);
if (cc < 0 || cc >= str.length())
{
//throw new UnclosedClauseException(str.substring(c));
if (report != null)
report.addError("Couldn't close clause '" + Report.clippedString(str.substring(c), 20) + "'.");
return null;
}
if (str.charAt(cc) == ')' && str.charAt(cc-1) == ')')
{
// Remove outer brackets (front and back)
str = str.substring(0, cc) + str.substring(cc+1); // remove trailing duplicates
str = str.substring(0, c) + str.substring(c+1); // remove leading duplicates
}
else
{
// Opening pair do not have closing pair, should never occur
if (report != null)
report.addError("Opening bracket pair '((' in '" + Report.clippedString(str.substring(c), 20) + "' does not have closing pair.");
return null;
}
}
return str;
}
//-------------------------------------------------------------------------
/**
* Realise options.
* @return Game description with defines expanded in-place.
*/
public static String realiseOptions
(
final String strIn,
final Description description,
final UserSelections userSelections,
final Report report
)
{
description.gameOptions().clear();
if (!strIn.contains("(option \""))
return new String(strIn); // nothing to do
String str = new String(strIn);
str = extractOptions(str, description, report);
if (report.isError() || str == null)
return null;
int[] optionSelections;
try
{
optionSelections = description.gameOptions().computeOptionSelections(userSelections.selectedOptionStrings());
}
catch (final UnusedOptionException e)
{
// Revert to default options for this game
//e.printStackTrace();
System.err.println("Reverting to default options for game due to unrecognised option being specified!");
userSelections.setSelectOptionStrings(new ArrayList<String>());
optionSelections = description.gameOptions().computeOptionSelections(userSelections.selectedOptionStrings());
}
// Expand the user-selected choice (or default) in each option group
for (int cat = 0; cat < description.gameOptions().numCategories(); cat++)
{
final OptionCategory category = description.gameOptions().categories().get(cat);
if (category.options().size() > 0)
{
final Option option = category.options().get(optionSelections[cat]);
if (option.arguments().isEmpty())
{
// Can be valid if options are being used to define headings in the metadata
return str;
}
str = expandOption(str, option, report);
if (report.isError() || str == null)
return null;
}
}
return str;
}
//-------------------------------------------------------------------------
/**
* Stores a copy of each option and removes their definition from the game description.
* @return Game description with options removed and stored in list.
*/
private static final String extractOptions
(
final String strIn,
final Description description,
final Report report
)
{
// Extracts options in this format:
//
// (option "Board Size" <Size> args:{ <dim> <start> <end> }
// {
// ("3x3" <3 3> <9> <4> "Played on a square 3x3 board.")
// ("4x4" <4 4> <16> <8> "Played on a square 4x4 board.")*
// ("5x5" <5 5> <25> <12> "Played on a square 5x5 board.")**
// }
// )
String str = new String(strIn);
while (str.contains("(option \""))
{
final int c = str.indexOf("(option \"");
// Find matching closing bracket
int cc = StringRoutines.matchingBracketAt(str, c);
if (cc < 0 || cc >= str.length())
{
//throw new UnclosedClauseException(str.substring(c));
report.addError("Couldn't close clause '" + Report.clippedString(str.substring(c), 20) + "'.");
return null;
}
cc++;
final OptionCategory category = new OptionCategory(str.substring(c, cc));
// Check whether option args are well formed, e.g. "Step/hop move" is a bad label
for (final Option option : category.options())
{
for (final String header : option.menuHeadings())
if (header.contains("/"))
{
report.addError("Bad '/' in option header \"" + header + "\".");
return null;
}
}
description.gameOptions().add(category);
str = str.substring(0, c) + str.substring(cc); // remove from source string
}
return str;
}
//-------------------------------------------------------------------------
/**
* @param strIn
* @return Game description with all occurrences of option expanded.
*/
private static String expandOption
(
final String strIn,
final Option option,
final Report report
)
{
String str = new String(strIn);
// Pass 1: Match all <Category:arg> instances first
for (final OptionArgument arg : option.arguments())
{
final String name = arg.name();
if (name == null)
{
//throw new IllegalArgumentException("Some option arguments are named but this one is not.");
report.addError("Some option arguments are named but this one is not.");
return null;
}
final String marker = "<" + option.tag() + ":" + name + ">";
int iterations = 0;
while (str.contains(marker))
{
if (++iterations > MAX_EXPANSIONS)
{
//throw new InvalidOptionException("An option has more than " + MAX_EXPANSIONS + " expansions.");
report.addError("An option has more than " + MAX_EXPANSIONS + " expansions.");
return null;
}
if (str.length() > MAX_CHARACTERS)
{
//throw new InvalidOptionException("The option " + option.toString() + " has more than " + MAX_CHARACTERS + " characters.");
report.addError("The option " + option.toString() + " has more than " + MAX_CHARACTERS + " characters.");
return null;
}
// Expand this instance in-place
final int c = str.indexOf(marker);
str = str.substring(0, c) + arg.expression() + str.substring(c + marker.length());
}
}
// **
// ** Don't do this test: rulesets can have primary tags without secondary tags!
// **
// // Check that author didn't forget to use names in instances.
// final String marker = "<" + option.label() + ">";
// if (str.contains(marker))
// {
// System.out.println("Marker " + marker + " but named markers expected, in: " + str);
// throw new InvalidOptionException("Option <label> should be in <label:name> format.");
// }
// Pass 2: Expand instances with <Category> as arg 0 (was modulus order)
final String marker = "<" + option.tag() + ">";
// final int numArgs = option.arguments().size();
// int count = 0;
int iterations = 0;
while (str.contains(marker))
{
if (++iterations > MAX_EXPANSIONS)
{
//throw new InvalidOptionException("An option has more than " + MAX_EXPANSIONS + " expansions.");
report.addError("An option has more than " + MAX_EXPANSIONS + " expansions.");
return null;
}
if (str.length() > MAX_CHARACTERS)
{
//throw new InvalidOptionException("The option " + option.toString() + " has more than " + MAX_CHARACTERS + " characters.");
report.addError("The option " + option.toString() + " has more than " + MAX_CHARACTERS + " characters.");
return null;
}
// Expand this instance in-place
final int c = str.indexOf(marker);
final int index = 0; //count++ % numArgs;
str = str.substring(0, c) + option.arguments().get(index).expression() + str.substring(c + marker.length());
}
return str;
}
//-------------------------------------------------------------------------
/**
* Realise rulesets.
*/
public static String realiseRulesets
(
final String strIn,
final Description description,
final Report report
)
{
if (!strIn.contains("(rulesets"))
return strIn; // nothing to do
final String str = extractRulesets(strIn, description, report);
return str;
}
/**
* Stores a copy of each ruleset and removes their definition from the game description.
* @return Game description with rulesets removed and stored in list.
*/
private static final String extractRulesets
(
final String strIn,
final Description description,
final Report report
)
{
description.clearRulesets();
String str = new String(strIn);
int c = str.indexOf("(rulesets");
if (c < 0)
{
//throw new BadSyntaxException("Rulesets not found.", str);
report.addError("Rulesets not found.");
return null;
}
int cc = StringRoutines.matchingBracketAt(str, c);
if (cc < 0)
{
//throw new BadSyntaxException("No closing bracket ')' in rulesets.", str);
report.addError("No closing bracket ')' in rulesets '" + Report.clippedString(str.substring(c), 20) + "'.");
return null;
}
String rulesetsStr = str.substring(c+8, cc-1).trim();
str = str.substring(0, c) + str.substring(cc); // remove rulesets from game description
// Process this rulesets string
while (true)
{
c = rulesetsStr.indexOf("(ruleset ");
if (c < 0)
break; // no more rulesets
cc = StringRoutines.matchingBracketAt(rulesetsStr, c);
if (cc < 0)
{
//throw new BadSyntaxException("No closing bracket ')' in ruleset.", rulesetsStr);
report.addError("No closing bracket ')' in ruleset '" + Report.clippedString(rulesetsStr.substring(c), 20) + "'.");
return null;
}
String rulesetStr = rulesetsStr.substring(c, cc+1);
int priorityIndex = cc + 1;
while (priorityIndex < rulesetsStr.length() && rulesetsStr.charAt(priorityIndex) == '*')
{
rulesetStr += '*'; // preserve priority markers
priorityIndex++;
}
final Ruleset ruleset = new Ruleset(rulesetStr);
description.add(ruleset);
rulesetsStr = rulesetsStr.substring(cc+1);
}
// Just delete any remaining rulesets in the game description
while (true)
{
c = str.indexOf("(rulesets");
if (c < 0)
break; // no more rulesets
cc = StringRoutines.matchingBracketAt(str, c);
if (cc < 0)
{
//throw new BadSyntaxException("No closing bracket ')' in extra rulesets.", str);
report.addError("No closing bracket ')' in extra rulesets '" + Report.clippedString(str.substring(c), 20) + "'.");
return null;
}
str = str.substring(0, c) + str.substring(cc); // remove this extra set of rulesets
}
return str;
}
//-------------------------------------------------------------------------
/**
* Expand defines iteratively until no more expansions occur.
*/
public static String expandDefines
(
final String strIn,
final Report report,
final Map<String, DefineInstances> defineInstances
)
{
// Load game AI metadata define (if any)
final Define knownAIDefine = loadKnownAIDefine(strIn, report);
if (report.isError())
return null;
// Expand defines
int defineIterations = 0;
String str = strIn;
while (true)
{
final String strDef = expandDefinesPass(str, knownAIDefine, report, defineInstances);
if (report.isError())
return null;
if (str.equals(strDef))
break; // no more defines
str = strDef;
if (++defineIterations > MAX_EXPANSIONS || str.length() > MAX_CHARACTERS)
{
// Probably an infinite loop, e.g. (define "A" "B") (define "B" "A")
//throw new DefineExpansionException("A suspected infinitely recursive define.");
report.addError("Suspected infinitely recursive define.");
return null;
}
}
return str;
}
/**
* Expand current set of defines, which may expand into more defines.
*/
private static String expandDefinesPass
(
final String strIn,
final Define knownAIDefine,
final Report report,
final Map<String, DefineInstances> defineInstances
)
{
final List<Define> defines = new ArrayList<>();
final Map<String, Define> knownDefines = KnownDefines.getKnownDefines().knownDefines();
String str = extractDefines(strIn, defines, report);
if (report.isError())
return null;
// Repeatedly: expand in-file defines as thoroughly as possible,
// then all predefined defines as thoroughly as possible.
boolean didExpandAny;
do
{
didExpandAny = false;
// First, expand all in-file defines as thoroughly as possible
final boolean[] didExpand = new boolean[1];
do
{
didExpand[0] = false;
for (final Define def : defines)
{
if (str.contains(def.tag()))
{
str = expandDefine(str, def, didExpand, report, defineInstances);
if (report.isError())
return null;
}
}
if (didExpand[0])
didExpandAny = true;
} while (didExpand[0]);
// Secondly, expand all predefined defines as thoroughly as possible except in the metadata
String metadata = "";
final int c = str.indexOf("(metadata");
if (c >= 0)
{
metadata = str.substring(c, StringRoutines.matchingBracketAt(str, c) + 1);
str = str.substring(0, c);
}
do
{
didExpand[0] = false;
for (final Map.Entry<String, Define> entry : knownDefines.entrySet())
{
final Define def = entry.getValue();
if (str.contains(def.tag()))
{
str = expandDefine(str, def, didExpand, report, defineInstances);
if (report.isError())
return null;
}
}
if (didExpand[0])
didExpandAny = true;
} while (didExpand[0]);
str = str + metadata;
// Thirdly, expand known game AI metadata define (if found)
if (knownAIDefine != null)
{
if (str.contains(knownAIDefine.tag()))
{
didExpand[0] = false;
str = expandDefine(str, knownAIDefine, didExpand, report, defineInstances);
if (report.isError())
return null;
if (didExpand[0])
didExpandAny = true;
}
}
} while (didExpandAny);
return str;
}
/**
* Stores a copy of each define and removes their definition from the game description.
* @param strIn
* @return Game description with defines removed and stored in list.
*/
public static String extractDefines
(
final String strIn,
final List<Define> defines,
final Report report
)
{
final int[] extent = new int[2]; // char indices of opening and closing brackets
String str = new String(strIn);
while (str.contains("(define "))
{
final Define define = interpretDefine(str, extent, report, false);
if (report != null && report.isError())
return null;
if (define == null)
{
System.out.println("** Failed to load define:\n" + str);
continue;
}
defines.add(define);
str = str.substring(0, extent[0]) + str.substring(extent[1]+1);
}
return str;
}
/**
* @param str
* @param extent
* @param report
*
* @return The real define.
*/
public static Define interpretDefine
(
final String str,
final int[] extent,
final Report report,
final boolean isKnown
)
{
// 1. Remove opening and closing brackets
int c = str.indexOf("(define ");
if (c < 0)
return null; // not a define
final int cc = StringRoutines.matchingBracketAt(str, c);
if (cc < 0)
{
// System.out.println("** Bad define string: " + str);
// throw new BadSyntaxException("define", "Badly formed define. Should start and end with `(define' and end with a bracket.");
if (report != null)
report.addError("Could not close '(define ...' in '" + Report.clippedString(str.substring(c), 20) + "'.");
return null;
}
String desc = str.substring(c+1, cc).trim();
if (extent != null)
{
// Store extent of define (char indices of opening and closing brackets)
extent[0] = c;
extent[1] = cc;
}
// 2. Remove header '(define "name"' which contains two quotes
c = 0;
int numQuotes = 0;
while (c < desc.length())
{
if (desc.charAt(c) == '"')
numQuotes++;
if (numQuotes >= 2)
break;
c++;
}
if (numQuotes < 2)
{
// throw new BadSyntaxException("define", "Badly formed define. Should be start (define \"name\".");
if (report != null)
report.addError("Badly fomred '(define \"name\"...' in '" + Report.clippedString(desc, 20) + "'.");
return null;
}
// Find the label for the define (first String in quotes)
final int openingQuoteIdx = desc.indexOf("\"");
final int closingQuoteIdx = desc.indexOf("\"", openingQuoteIdx + 1);
final String key = desc.substring(openingQuoteIdx, closingQuoteIdx + 1);
desc = desc.substring(c+1).trim();
final Define define = new Define(key, desc, isKnown);
//System.out.println("Define is: " + define);
return define;
}
/**
* @param strIn
* @return Game description with all occurrences of define expanded.
*/
private static String expandDefine
(
final String strIn,
final Define define,
final boolean[] didExpand,
final Report report,
final Map<String, DefineInstances> defineInstances
)
{
String str = new String(strIn);
// System.out.println("Expanding define: " + define.tag() + "...");
final int len = define.tag().length();
int iterations = 0;
int c = 0;
while (true)
{
if (++iterations > MAX_EXPANSIONS)
{
// throw new DefineExpansionException("A define has more than " + MAX_EXPANSIONS + " expansions.");
report.addError("Define has more than " + MAX_EXPANSIONS + " expansions '" + Report.clippedString(str, 20) + "'.");
return null;
}
if (str.length() > MAX_CHARACTERS)
{
// throw new DefineExpansionException("A define has more than " + MAX_CHARACTERS + " characters.");
report.addError("Define has more than " + MAX_CHARACTERS + " characters '" + Report.clippedString(str, 20) + "'.");
return null;
}
// Check for next occurrence of define label
c = str.indexOf(define.tag(), c+1);
if (c == -1)
break; // no more occurrences
if (protectedSubstring(str, c))
{
// Protected substring found
continue;
}
int cc = c + len-1; // if no brackets
if (str.charAt(c-1) == '(')
{
// Take brackets into account
c--;
cc = StringRoutines.matchingBracketAt(str, c);
if (cc < 0 || cc >= str.length())
{
// throw new BadSyntaxException("define", "Failed to handle parameter in define.");
report.addError("Failed to handle parameter in define '" + Report.clippedString(str.substring(c), 20) + "'.");
return null;
}
}
final String argString = str.substring(c, cc+1).trim();
final List<String> args = extractDefineArgs(argString, report);
if (report.isError())
return null;
final String exprn = expandDefineArgs(define, args, report);
if (report.isError())
return null;
if (defineInstances != null)
{
// Add this expression to the relevant DefineInstances record
DefineInstances defIn = defineInstances.get(define.tag());
if (defIn == null)
{
defIn = new DefineInstances(define);
defineInstances.put(define.tag(), defIn);
}
defIn.addInstance(new String(exprn));
}
// Do the expansion
str = str.substring(0, c) + exprn + str.substring(cc+1);
didExpand[0] = true;
}
str = str.replace("<DELETE_ME>", ""); // remove null parameter placeholders
return str;
}
//-------------------------------------------------------------------------
private static final List<String> extractDefineArgs
(
final String argString,
final Report report
)
{
final List<String> args = new ArrayList<String>();
String str = new String(argString.trim());
if (str.charAt(0) == '(')
{
final int cc = StringRoutines.matchingBracketAt(str, 0);
if (cc == -1)
{
// throw new BadSyntaxException("define", "Failed to read bracketed clause from: " + str + ".");
report.addError("Failed to read bracketed clause '(...)' from '" + Report.clippedString(str, 20) + "'.");
return null;
}
str = str.substring(1, cc);
}
// Move to first arg after label
int a = 0;
while (a < str.length() && !Character.isWhitespace(str.charAt(a)))
a++;
if (a >= str.length())
return args; // no arguments
str = str.substring(a).trim();
while (!str.isEmpty())
{
// Extract next parameter from head of list
int aTo = 0;
if (StringRoutines.isOpenBracket(str.charAt(0)))
{
// Read in bracketed clause
aTo = StringRoutines.matchingBracketAt(str, 0);
if (aTo == -1)
{
// throw new BadSyntaxException("define", "Failed to read bracketed clause from: " + str + ".");
report.addError("Failed to read bracketed clause from '" + Report.clippedString(str, 20) + "'.");
return null;
}
aTo++; // step past closing bracket
}
else if (str.charAt(0) == '"')
{
// Read in named bracketed clause
aTo = StringRoutines.matchingQuoteAt(str, 0);
if (aTo == -1)
{
// throw new BadSyntaxException("define", "Failed to read quoted clause \"...\" from: " + str + ".");
report.addError("Failed to read quoted clause '\"...\"' from '" + Report.clippedString(str, 20) + "'.");
return null;
}
aTo++; // step past closing bracket
}
else
{
// Read in next symbol
aTo = 0;
while (aTo < str.length() && !Character.isWhitespace(str.charAt(aTo)))
{
if (str.charAt(aTo) == ':')
{
// Named parameter, check if remaining of expression is bracketed
if (StringRoutines.isOpenBracket(str.charAt(aTo+1)))
{
aTo = StringRoutines.matchingBracketAt(str, aTo+1);
if (aTo == -1)
{
// throw new BadSyntaxException("define", "Failed to read bracketed clause '{...}' from: " + str + ".");
report.addError("Failed to read bracketed clause '{...}' from '" +
Report.clippedString(str, 20) + "'.");
return null;
}
aTo++; // step past closing bracket
break;
}
}
aTo++;
}
}
if (aTo >= str.length())
aTo = str.length();
final String arg = str.substring(0, aTo);
args.add(new String(arg));
str = str.substring(aTo).trim();
}
return args;
}
private static String expandDefineArgs
(
final Define define,
final List<String> args,
final Report report
)
{
String exprn = new String(define.expression());
for (int n = 0; n < MAX_DEFINE_ARGS; n++)
{
final String marker = "#" + (n+1);
if (!exprn.contains(marker))
break; // no more args
int innerIterations = 0;
while (exprn.contains(marker))
{
if (++innerIterations > MAX_EXPANSIONS)
{
// throw new DefineExpansionException("A define has more than " + MAX_EXPANSIONS + " expansions (inner loop).");
report.addError("Define has more than " + MAX_EXPANSIONS + " expansions '" +
Report.clippedString(exprn, 20) + "'.");
return null;
}
if (exprn.length() > MAX_CHARACTERS)
{
// throw new DefineExpansionException("A define has more than " + MAX_CHARACTERS + " characters (inner loop exprn).");
report.addError("Define has more than " + MAX_CHARACTERS + " characters '" +
Report.clippedString(exprn, 20) + "'.");
return null;
}
final int m = exprn.indexOf(marker);
String arg = "<DELETE_ME>"; // mark for deletion
if (n < args.size() && !args.get(n).equals(DEFINE_PARAMETER_PLACEHOLDER))
arg = args.get(n);
exprn = exprn.substring(0, m) + arg + exprn.substring(m+2);
// System.out.println("- expanding exprn: " + exprn);
if (arg.charAt(0) == '#')
break; // arg is an arg itself
}
}
return exprn;
}
//-------------------------------------------------------------------------
/**
* @param str String to check.
* @param fromIndex Index of substring.
* @return Whether the specified substring within str should be protected
* from expansion by a define.
* These include "(game", "(match", "(instance", etc.
*/
public static boolean protectedSubstring
(
final String str,
final int fromIndex
)
{
// Tokens that protect the following string from being expanded as a define,
// in case the string accidentally matches a known define.
final String[] safeTokens = { "game", "match", "instance" };
// Step back to previous token (might be a bracket)
int c = fromIndex-1;
while (c >= 0)
{
if (StringRoutines.isTokenChar(str.charAt(c)))
break;
c--;
}
if (c < 0)
{
System.out.println("** Warning: Failed to find previous token (probably from define).");
System.out.println("** fromIndex=" + fromIndex + ", str:=\n" + str);
return false;
}
// Get token string
String token = "";
while (c >= 0)
{
final char ch = str.charAt(c);
if (!StringRoutines.isTokenChar(ch))
break;
token = ch + token;
c--;
}
if (c < 0)
{
System.out.println("** Warning: Failed to read previous token (probably from define).");
System.out.println("** fromIndex=" + fromIndex + ", str:=\n" + str);
return false;
}
for (final String safeToken : safeTokens)
if (token.equals(safeToken))
return true; // this substring is protected
return false;
}
//-------------------------------------------------------------------------
/**
* Load known AI metadata define from file.
*/
private static Define loadKnownAIDefine
(
final String strIn,
final Report report
)
{
if (!strIn.contains("(ai") || !strIn.contains("_ai"))
return null;
Define knownAIDefine = null;
final String gameName = StringRoutines.gameName(strIn);
String aiName = gameName;
// Check that the ai file name, if any, matches the game name
final int c = strIn.indexOf("_ai\"");
if (c >= 0)
{
int cc = c;
while (cc >= 0 && strIn.charAt(cc) != '"')
cc--;
aiName = strIn.substring(cc + 1, c);
// if (!aiName.equals(gameName))
// {
// report.addWarning("Define '" + aiName + "_ai' found in AI metadata; use '" + gameName + "_ai' or remove it.");
// return Expander.interpretDefine("(define \"" + aiName + "_ai\")", null, report, true);
// }
}
final String[] defs = FileHandling.getResourceListingSingle(Expander.class, "def_ai/", aiName + "_ai.def");
if (defs == null)
{
// Not a JAR
try
{
// Start with known _ai.def file
final URL url = Expander.class.getResource("/def_ai/Chess_ai.def");
String path = new File(url.toURI()).getPath();
path = path.substring(0, path.length() - "Chess_ai.def".length());
final File root = new File(path);
final File[] list = root.listFiles();
if (list == null)
return null;
for (final File file : list)
if
(
file != null
&&
!file.isDirectory()
&&
file.getName() != null
&&
file.getName().equals(aiName + "_ai.def")
)
{
// Found the file
final String filePath = path + file.getName();
knownAIDefine = KnownDefines.processDefFile
(
filePath.replaceAll(Pattern.quote("\\"), "/"),
"/def_ai/",
report
);
if (report.isError())
return null;
}
}
catch (final Exception e)
{
e.printStackTrace();
}
}
else
{
for (String def : defs)
{
def = def.replaceAll(Pattern.quote("\\"), "/");
final String[] defSplit = def.split(Pattern.quote("/"));
final String filename = defSplit[defSplit.length - 1];
if (filename.equals(aiName + "_ai.def"))
{
knownAIDefine = KnownDefines.processDefFile(def, "/def_ai/", report);
if (report.isError())
return null;
}
}
}
if (knownAIDefine == null)
{
knownAIDefine = Expander.interpretDefine("(define \"" + aiName + "_ai\")", null, report, false);
report.addWarning("Failed to load AI define specified in metadata; reverting to default AI.");
}
return knownAIDefine;
}
//-------------------------------------------------------------------------
/**
* @param strIn
* @return Game description with all number range occurrences expanded.
*/
public static String expandRanges
(
final String strIn,
final Report report
)
{
if (!strIn.contains(".."))
return strIn; // nothing to do
String str = new String(strIn);
int ref = 1;
boolean inCompletion = false;
while (ref < str.length() - 2)
{
if(str.charAt(ref) == '[')
inCompletion = true;
if(str.charAt(ref) == ']')
inCompletion = false;
if(!inCompletion)
{
if
(
str.charAt(ref) == '.' && str.charAt(ref+1) == '.'
&&
Character.isDigit(str.charAt(ref-1))
&&
Character.isDigit(str.charAt(ref+2))
)
{
// Is a range: expand it
int c = ref - 1;
while (c >= 0 && Character.isDigit(str.charAt(c)))
c--;
c++;
final String strM = str.substring(c, ref);
final int m = Integer.parseInt(strM);
c = ref + 2;
while (c < str.length() && Character.isDigit(str.charAt(c)))
c++;
final String strN = str.substring(ref+2, c);
final int n = Integer.parseInt(strN);
if (Math.abs(n - m) > MAX_RANGE)
{
//throw new BadRangeException(MAX_RANGE);
report.addError("Range exceeded maximum of " + MAX_RANGE + ".");
return null;
}
// Generate the expanded range substring
String sub = " ";
final int inc = (m <= n) ? 1 : -1;
for (int step = m; step != n; step += inc)
{
if (step == m || step == n)
continue; // don't include end points
sub += step + " ";
}
str = str.substring(0, ref) + sub + str.substring(ref+2);
ref += sub.length();
}
}
ref++;
}
return str;
}
/**
* @param strIn
* @return Game description with all site range occurrences expanded.
*/
public static String expandSiteRanges
(
final String strIn,
final Report report
)
{
if (!strIn.contains(".."))
return strIn; // nothing to do
String str = new String(strIn);
boolean inCompletion = false;
int ref = 1;
while (ref < str.length() - 2)
{
if(str.charAt(ref) == '[')
inCompletion = true;
if(str.charAt(ref) == ']')
inCompletion = false;
if(!inCompletion)
{
if
(
str.charAt(ref) == '.' && str.charAt(ref+1) == '.'
&&
str.charAt(ref-1) == '"' && str.charAt(ref+2) == '"'
)
{
// Must be a site range
int c = ref - 2;
while (c >= 0 && str.charAt(c) != '"')
c--;
final String strC = str.substring(c+1, ref-1);
// System.out.println("strC: " + strC);
int d = ref + 3;
while (d < str.length() && str.charAt(d) != '"')
d++;
d++;
final String strD = str.substring(ref+3, d-1);
// System.out.println("strD: " + strD);
// System.out.println("Range: " + str.substring(c, d));
if (strC.length() < 2 || !StringRoutines.isLetter(strC.charAt(0)))
{
report.addError("Bad 'from' coordinate in site range: " + str.substring(c, d));
return null;
}
final int fromChar = Character.toUpperCase(strC.charAt(0)) - 'A';
if (strD.length() < 2 || !StringRoutines.isLetter(strD.charAt(0)))
{
report.addError("Bad 'to' coordinate in site range: " + str.substring(c, d));
return null;
}
final int toChar = Character.toUpperCase(strD.charAt(0)) - 'A';
// System.out.println("fromChar=" + fromChar + ", toChar=" + toChar + ".");
final int fromNum = Integer.parseInt(strC.substring(1));
final int toNum = Integer.parseInt(strD.substring(1));
// System.out.println("fromNum=" + fromNum + ", toNum=" + toNum + ".");
// Generate the expanded range substring
String sub = "";
for (int m = fromChar; m < toChar + 1; m++)
for (int n = fromNum; n < toNum + 1; n++)
sub += "\"" + (char)('A' + m) + (n) + "\" ";
str = str.substring(0, c) + sub.trim() + str.substring(d);
ref += sub.length();
}
}
ref++;
}
// System.out.println(str);
return str;
}
//-------------------------------------------------------------------------
/**
* Extracts metadata and stores it in expandedMetadataString.
* @param strIn The complete expanded game description.
* @param options The Game options with which we're compiling.
* @return Game description with metadata removed and stored in expandedMetadataString.
*/
private static String extractMetadata
(
final String strIn,
final Description description,
final UserSelections userSelections,
final Report report
)
{
final int c = strIn.indexOf("(metadata");
if (c < 0)
return strIn; // no metadata to extract
// Find matching closing bracket
final int cc = StringRoutines.matchingBracketAt(strIn, c);
if (cc < 0)
{
//throw new BadSyntaxException("metadata", "Failed to close (metadata...");
report.addError("Failed to close '(metadata' in '" +
Report.clippedString(strIn.substring(c), 20) + "'.");
return null;
}
String str = strIn.substring(c, cc+1);
// // Check if next char is '{'
// int b = 9; // skip "(metadata "
// char ch = ' ';
// while (b < str.length())
// {
// ch = str.charAt(b);
// if (ch == '{' || ch == '(' || StringRoutines.isNameChar(ch))
// break;
// b++;
// }
// if (ch == '{')
// {
// final int bb = StringRoutines.matchingBracketAt(str, b);
// str = str.substring(0, b) + str.substring(bb+1);
// }
str = removeUnselectedOptionParts(str, description, userSelections, report);
if (report.isError())
return null;
description.setMetadata(new String(str));
final String removed = strIn.substring(0, c) + strIn.substring(cc+1);
return removed;
}
/**
* Remove parts that require different game options from those selected.
* @return game description with unselected option parts removed.
*/
private static String removeUnselectedOptionParts
(
final String strIn,
final Description description,
final UserSelections userSelections,
final Report report
)
{
String str = new String(strIn);
// First thing we'll do; try to auto-select ruleset based on options if
// we do not already have a selected ruleset
int activeRuleset = userSelections.ruleset();
if (activeRuleset < 0)
{
activeRuleset = description.autoSelectRuleset(userSelections.selectedOptionStrings());
if (activeRuleset >= 0)
userSelections.setRuleset(activeRuleset);
}
final List<String> active = description.gameOptions().allOptionStrings
(
userSelections.selectedOptionStrings()
);
while (true)
{
final int optsCondStartIdx = str.indexOf("(useFor ");
if (optsCondStartIdx < 0)
break; // no more chunks of metadata that are restricted by options
final int optsCondClosingBracketIdx = StringRoutines.matchingBracketAt(str, optsCondStartIdx);
if (optsCondClosingBracketIdx < 0)
{
// throw new BadSyntaxException("metadata", "Failed to close (useFor ...");
report.addError("Failed to close '(useFor' in '" +
Report.clippedString(str.substring(optsCondStartIdx), 20) + "'.");
return null;
}
// Find the substring that specifies all the required rulesets / options
final int requirementsSubstrIdxStart;
final int requirementsSubstrIdxEnd;
final int nextOpeningCurlyIdx = str.indexOf('{', optsCondStartIdx);
final int nextQuoteIdx = str.indexOf('"', optsCondStartIdx);
if (nextQuoteIdx < 0)
{
// throw new BadSyntaxException("metadata", "There must always be a quote somewhere after (useFor ");
report.addError("No quote after '(useFor' in '" +
Report.clippedString(str.substring(optsCondStartIdx), 20) + "'.");
return null;
}
if (nextOpeningCurlyIdx >= 0 && nextOpeningCurlyIdx < nextQuoteIdx)
{
// We have curly braces
final int openCurlyBracketIdx = nextOpeningCurlyIdx;
final int closCurlyBracketIdx = StringRoutines.matchingBracketAt(str, openCurlyBracketIdx);
if (closCurlyBracketIdx < 0)
{
// throw new BadSyntaxException("metadata", "Failed to close curly bracket of (useFor {...");
report.addError("Failed to close curly bracket '{' in '" +
Report.clippedString(str.substring(optsCondStartIdx), 20) + "'.");
return null;
}
requirementsSubstrIdxStart = openCurlyBracketIdx + 1;
requirementsSubstrIdxEnd = closCurlyBracketIdx;
}
else
{
// We don't have curly braces
final int openingQuoteIdx = nextQuoteIdx;
int closingQuoteIdx = str.indexOf('"', openingQuoteIdx + 1);
while (closingQuoteIdx >= 0 && str.charAt(closingQuoteIdx - 1) == '\\')
{
// Escaped quote, so keep moving on
closingQuoteIdx = str.indexOf('"', closingQuoteIdx + 1);
}
if (closingQuoteIdx < 0)
{
//throw new BadSyntaxException("metadata", "Failed to close quote after (useFor \"...");
report.addError("Failed to close quote after '(useFor' in '" +
Report.clippedString(str.substring(openingQuoteIdx), 20) + "'.");
return null;
}
requirementsSubstrIdxStart = openingQuoteIdx;
requirementsSubstrIdxEnd = closingQuoteIdx + 1;
}
// Extract the required options
final List<String> requiredOptions = new ArrayList<String>();
final String requirementsSubstr = str.substring(requirementsSubstrIdxStart, requirementsSubstrIdxEnd);
int requiredOptOpenQuoteIdx = requirementsSubstr.indexOf('"');
while (requiredOptOpenQuoteIdx >= 0)
{
int requiredOptClosingQuoteIdx = requirementsSubstr.indexOf('"', requiredOptOpenQuoteIdx + 1);
while (requirementsSubstr.charAt(requiredOptClosingQuoteIdx - 1) == '\\')
requiredOptClosingQuoteIdx = requirementsSubstr.indexOf('"', requiredOptClosingQuoteIdx + 1);
if (requiredOptClosingQuoteIdx < 0)
{
//throw new BadSyntaxException("metadata", "Failed to close quote of a String in (useFor ...)");
report.addError("Failed to close String quote in '" +
Report.clippedString(requirementsSubstr.substring(requiredOptClosingQuoteIdx), 20) + "'.");
return null;
}
requiredOptions.add(requirementsSubstr.substring(requiredOptOpenQuoteIdx + 1, requiredOptClosingQuoteIdx));
// Move on to next pair of quotes (if it exists)
requiredOptOpenQuoteIdx = requirementsSubstr.indexOf('"', requiredOptClosingQuoteIdx + 1);
}
// Safety check to make sure that all the required options also actually really exist (as options or rulesets)
for (final String requiredOption : requiredOptions)
{
if (!description.gameOptions().optionExists(requiredOption))
{
boolean foundMatch = false;
for (final Ruleset ruleset : description.rulesets())
{
if (requiredOption.equals(ruleset.heading()))
{
foundMatch = true;
break;
}
}
if (!foundMatch)
{
// throw new RuntimeException("Metadata has option requirement for option or ruleset that does not exist: " + requiredOption);
report.addError("Metadata has option requirement for option or ruleset that does not exist: " + requiredOption);
return null;
}
}
}
// Check if fail any of the requirements for options
boolean failedRequirement = false;
for (final String requiredOpt : requiredOptions)
{
// Each of these requiredOpt strings is quoted, need to remove those when checking condition
if (!active.contains(requiredOpt.replaceAll(Pattern.quote("\""), "")))
{
// Also try ruleset
if
(
activeRuleset < 0
||
!description.rulesets().get(activeRuleset).heading().equals
(
requiredOpt.replaceAll(Pattern.quote("\""), "")
)
)
{
failedRequirement = true;
break;
}
}
}
final StringBuffer stringBuffer = new StringBuffer(str);
if (failedRequirement)
{
// We have to delete this entire block of metadata
stringBuffer.replace(optsCondStartIdx, optsCondClosingBracketIdx + 1, "");
}
else
{
// We satisfy option requirements, so should only cut out the little
// parts used to describe those requirements: (useFor {...} and the closing bracket )
//
// Note: we first cut away stuff at the end, and afterwards stuff in the beginning,
// because if we cut in the beginning first, the later indices would need shifting
stringBuffer.replace(optsCondClosingBracketIdx, optsCondClosingBracketIdx + 1, "");
stringBuffer.replace(optsCondStartIdx, requirementsSubstrIdxEnd + 1, "");
}
str = stringBuffer.toString();
}
return str;
}
//-------------------------------------------------------------------------
/**
* Remove user comments from file (but not from within strings).
*
* @param strIn The string in entry.
* @return The new comment.
*/
public static String removeComments(final String strIn)
{
// TODO: Only remove comments outside strings!
String str = new String(strIn);
int c = 0;
while (c < str.length()-1)
{
if (str.charAt(c) == '"')
{
c = StringRoutines.matchingQuoteAt(str, c) + 1;
if (c <= 0)
{
// Something went wrong: probably not a comment, might be
// an embedded string or ruleset name in quotes
return str;
}
}
else if (str.charAt(c) == '/' && str.charAt(c+1) == '/')
{
// Is a comment
int cc = c + 2;
while (cc < str.length() && str.charAt(cc) != '\n')
cc++;
str = str.substring(0, c) + str.substring(cc); // remove to end of line
}
else
{
c++;
}
}
return str;
}
//-------------------------------------------------------------------------
}
| 50,225 | 27.749857 | 134 |
java
|
Ludii
|
Ludii-master/Language/src/parser/KnownDefines.java
|
package parser;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import main.FileHandling;
import main.grammar.Define;
import main.grammar.Report;
//-----------------------------------------------------------------------------
/**
* Record of known defines from Common/res/def and below.
*
* @author cambolbro
*/
public class KnownDefines
{
// Map of known defines from bin/def/ and below
private final Map<String, Define> knownDefines = new HashMap<String, Define>();
//-------------------------------------------------------------------------
/**
* Singleton class for known defines.
* @author cambolbro
*/
private static class KnownDefinesProvider
{
public static final KnownDefines KNOWN_DEFINES = new KnownDefines();
}
//-------------------------------------------------------------------------
/**
* Private constructor: access class as singleton through getKnownDefines().
*/
KnownDefines()
{
final Report report = new Report();
loadKnownDefines(report);
if (report.isError())
System.out.println(report);
}
//-------------------------------------------------------------------------
/**
* Access point for getting known defines.
* @return Map of known defines.
*/
public static KnownDefines getKnownDefines()
{
return KnownDefinesProvider.KNOWN_DEFINES;
}
/**
* @return The known defines.
*/
public Map<String, Define> knownDefines()
{
return knownDefines;
}
//-------------------------------------------------------------------------
/**
* Load known defines from file.
*/
void loadKnownDefines(final Report report)
{
knownDefines.clear();
// System.out.println("File.separator is '" + File.separator + "'.");
// Try loading from JAR file
final String[] defs = FileHandling.getResourceListing(KnownDefines.class, "def/", ".def");
if (defs == null)
{
// Not a JAR
try
{
// Start with known .def file
final URL url = KnownDefines.class.getResource("def/rules/play/moves/StepToEmpty.def");
String path = new File(url.toURI()).getPath();
path = path.substring(0, path.length() - "rules/play/moves/StepToEmpty.def".length());
// Get the list of .def files in this directory and subdirectories
try
{
recurseKnownDefines(path, report);
if (report.isError())
return;
}
catch (final Exception e)
{
e.printStackTrace();
}
}
catch (final URISyntaxException exception)
{
exception.printStackTrace();
}
}
else
{
// JAR file
for (final String def : defs)
{
final Define define = processDefFile(def.replaceAll(Pattern.quote("\\"), "/"), "/def/", report);
if (report.isError())
return;
knownDefines.put(define.tag(), define);
}
}
// System.out.println(knownDefines.size() + " known defines loaded:");
// for (final Define define : knownDefines.values())
// System.out.println("+ " + define.tag());
}
void recurseKnownDefines
(
final String path,
final Report report
) throws Exception
{
final File root = new File(path);
final File[] list = root.listFiles();
if (list == null)
return;
for (final File file : list)
{
if (file.isDirectory())
{
// Recurse to subdirectory
recurseKnownDefines(path + file.getName() + File.separator, report);
if (report.isError())
return;
}
else
{
if (!file.getName().contains(".def"))
continue; // not a define file
final String filePath = path + file.getName();
final Define define = processDefFile(filePath.replaceAll(Pattern.quote("\\"), "/"), "/def/", report);
if (report.isError())
return;
knownDefines.put(define.tag(), define);
}
}
}
//-------------------------------------------------------------------------
/**
* Processes a potential define file.
*
* @param defRoot
* @param defFilePath
* @param report
*
* @return The define.
*/
public static Define processDefFile
(
final String defFilePath,
final String defRoot,
final Report report
)
{
final InputStream in = KnownDefines.class.getResourceAsStream(defFilePath.substring(defFilePath.indexOf(defRoot)));
// Extract the definition text from file
final StringBuilder sb = new StringBuilder();
try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(in, "UTF-8")))
{
String line;
while ((line = rdr.readLine()) != null)
sb.append(line + "\n");
}
catch (final IOException e)
{
e.printStackTrace();
}
final Define define = Expander.interpretDefine(sb.toString(), null, report, true);
return define;
}
//-------------------------------------------------------------------------
}
| 5,298 | 24.475962 | 117 |
java
|
Ludii
|
Ludii-master/Language/src/parser/Parser.java
|
package parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import compiler.Arg;
import compiler.ArgClass;
import compiler.ArgTerminal;
import compiler.exceptions.CompilerException;
import completer.Completer;
import completer.Completion;
import grammar.Grammar;
import main.Constants;
import main.StringRoutines;
import main.grammar.DefineInstances;
import main.grammar.Description;
import main.grammar.GrammarRule;
import main.grammar.Instance;
import main.grammar.ParseItem;
import main.grammar.Report;
import main.options.UserSelections;
//-----------------------------------------------------------------------------
/**
* Parses .lud game descriptions according to the current Ludii grammar.
*
* @author cambolbro
*/
public class Parser
{
//-------------------------------------------------------------------------
/**
* Private constructor; don't allow class to be constructed.
*/
private Parser()
{
}
//-------------------------------------------------------------------------
/**
* Compile option for testing purposes. Does not interact with UI settings. Not
* for release! Create and throws away GameOptions each time.
*
* @param description
* @param userSelections
* @param report
* @param isVerbose
* @return Executable Game object if can be compiled, else null.
*/
public static boolean parseTest
(
final Description description,
final UserSelections userSelections,
final Report report,
final boolean isVerbose
)
{
return expandAndParse(description, userSelections, report, true, isVerbose);
}
//-------------------------------------------------------------------------
/**
* @param description
* @param userSelections
* @param report
* @param isVerbose
* @return Whether the .lud can be parsed.
*/
public static boolean expandAndParse
(
final Description description,
final UserSelections userSelections,
final Report report,
final boolean isVerbose
)
{
final boolean allowExamples = false;
return expandAndParse(description, userSelections, report, allowExamples, isVerbose);
}
/**
* @param description
* @param userSelections
* @param report
* @param allowExamples Suppress warnings for ludeme examples, e.g. for LLR.
* @param isVerbose
* @return Whether the .lud can be parsed.
*/
public static boolean expandAndParse
(
final Description description,
final UserSelections userSelections,
final Report report,
final boolean allowExamples,
final boolean isVerbose
)
{
if (Completer.needsCompleting(description.rawGameDescription()))
{
String rawGame = description.rawGameDescription();
// System.out.println("Raw game description is: \n" + rawGame);
// Remove formatting so that string matching during completion is more likely to work.
rawGame = Expander.cleanUp(rawGame, report);
// System.out.println("Raw game description after cleaning up is: \n" + rawGame);
//final List<Completion> completions = Completer.completeExhaustive(rawGame, description.maxReconstructions(), report);
final List<Completion> completions = Completer.completeSampled(rawGame, description.maxReconstructions(), report);
System.out.println(completions.size() + " completions found.");
if (!completions.isEmpty())
{
// Replace raw description string passed in with best completion
description.setRaw(completions.get(0).raw());
}
description.setIsRecontruction(true);
}
try
{
try
{
//report.clear();
Expander.expand(description, userSelections, report, isVerbose);
if (report.isError())
{
// System.out.println("Errors while expanding (A):");
// for (final String error : report.errors())
// System.out.println("* " + error);
return false; // failed to expand -- return error
}
if (isVerbose)
{
System.out.println("Define instances:");
for (final DefineInstances defIn : description.defineInstances().values())
System.out.println(defIn + "\n");
}
}
catch (final Exception e)
{
if (report.isError())
{
// System.out.println("Errors while expanding (B):");
// for (final String error : report.errors())
// System.out.println("* " + error);
return false; // failed to expand -- return error
}
//errors.add("Catching exception from Expander..."); //new String(e.getMessage()));
//errors.add("Could not expand game description. Maybe a misplaced bracket pair '(..)' or '{..}'?");
}
return parseExpanded(description, userSelections, report, allowExamples, isVerbose);
}
catch (final CompilerException e)
{
if (isVerbose)
e.printStackTrace();
throw new CompilerException(e.getMessageBody(description.raw()), e);
}
catch (final Exception e)
{
e.printStackTrace();
throw new IllegalArgumentException(e);
}
}
//-------------------------------------------------------------------------
/**
* Public function that calling code should use.
*
* Note: Assumes that Expander has already been called to expand the game description.
*
* @param allowExamples Suppress warnings for ludeme examples, e.g. for LLR.
* @return Whether .lud file parses the current grammar.
*/
private static boolean parseExpanded
(
final Description description,
final UserSelections userSelections,
final Report report,
final boolean allowExamples,
final boolean isVerbose
)
{
//report.clear();
// if (Constants.argCombos == null)
// Constants.createCombos();
//--------------- Check raw game text ----------------
if (description.raw() == null || description.raw().isEmpty())
{
report.addError("Could not expand empty game description. This message was brought to you by Dennis.");
return false;
}
// Extract the raw game description without metadata (assume metadata is after all game description)
String rawGame = description.raw();
//final boolean topLevelRaw = isTopLevelLudeme(rawGame);
if (!allowExamples) // || topLevelRaw)
{
// Check version info
checkVersion(rawGame, report);
}
// Remove comments
rawGame = Expander.removeComments(rawGame);
// Remove metadata
final int mdc = rawGame.indexOf("(metadata");
if (mdc != -1)
rawGame = rawGame.substring(0, mdc).trim();
// Check for matching quotes in raw description
checkQuotes(rawGame, report);
if (report.isError())
return false;
// Check for matching brackets
checkBrackets(rawGame, report);
if (report.isError())
return false;
//--------------- Check expanded text ----------------
if (description.expanded() == null)
{
// Allow more specific tests above to check the problem
report.addError("Could not expand. Check that bracket pairs '(..)' and '{..}' match.");
return false;
}
// Check for matching quotes in expanded description
checkQuotes(description.expanded(), report);
if (report.isError())
return false;
// Check for matching brackets
checkBrackets(description.expanded(), report);
if (report.isError())
return false;
if (!allowExamples)
{
checkOptionsExpanded(description.expanded(), report);
if (report.isError())
return false;
}
//--------------- Check token tree ----------------
// Check token tree was created successfully
if
(
description.tokenForest().tokenTree() == null
||
description.tokenForest().tokenTree().type() == null
)
{
//System.out.println("** Parser.parse(): No token tree.");
report.addLogLine("** Parser.parse(): No token tree.");
report.addError("Couldn't generate token tree from expanded game description.");
return false;
}
if (isVerbose)
{
//System.out.println("+++++++++++++++++++++\nParsing:\n" + description.expanded());
report.addLogLine("+++++++++++++++++++++\nParsing:\n" + description.expanded());
}
//--------------- Check parse tree ----------------
// Create parse tree
description.createParseTree();
if (description.parseTree() == null)
{
report.addError("Couldn't generate parse tree from token tree.");
return false;
}
// Check can match tokens with symbols
matchTokensWithSymbols(description.parseTree(), Grammar.grammar(), report);
if (report.isError())
return false;
final boolean gameOrMatch = isGameOrMatch(description.expanded());
if (!allowExamples || gameOrMatch)
{
checkStrings(description.expanded(), report);
if (report.isError())
return false;
}
//--------------- Check against grammar ----------------
//System.out.println("\n" + parseTree.compare());
//System.out.println("\n" + parseTree.dump(""));
// Check against grammar
description.parseTree().parse(null, report, null);
//description.parseTree().parse(null, report, "");
//System.out.println("\n" + description.parseTree().dump(""));
// Look for deepest failure and report all errors at that level
final int failureDepth = description.parseTree().deepestFailure();
if (failureDepth >= 0)
description.parseTree().reportFailures(report, failureDepth);
return !report.isError();
}
//-------------------------------------------------------------------------
/**
* Finds symbols that match this item's token.
*/
private static void checkQuotes(final String str, final Report report)
{
// Check quotations
final int numQuotes = StringRoutines.numChar(str, '"');
// System.out.println(numQuotes + " quotes.");
if (numQuotes % 2 != 0)
{
report.addError("Mismatched quotation marks '\"'.");
return;
}
}
//-------------------------------------------------------------------------
/**
* Finds symbols that match this item's token.
*/
private static void checkBrackets(final String str, final Report report)
{
// Check brackets
int numOpen = StringRoutines.numChar(str, '(');
int numClose = StringRoutines.numChar(str, ')');
// System.out.println("numOpen=" + numOpen + ", numClose=" + numClose + " '()'.");
if (numOpen < numClose)
{
if (numClose - numOpen == 1)
report.addError("Missing an open bracket '('.");
else
report.addError("Missing " + (numClose - numOpen) + " open brackets '('.");
return;
}
if (numOpen > numClose)
{
if (numOpen - numClose == 1)
report.addError("Missing a close bracket ')'.");
else
report.addError("Missing " + (numOpen - numClose) + " close brackets ')'.");
return;
}
// Check braces
numOpen = StringRoutines.numChar(str, '{');
numClose = StringRoutines.numChar(str, '}');
// System.out.println("numOpen=" + numOpen + ", numClose=" + numClose + " '{}'.");
if (numOpen < numClose)
{
if (numClose - numOpen == 1)
report.addError("Missing an open brace '{'.");
else
report.addError("Missing " + (numClose - numOpen) + " open braces '{'.");
return;
}
if (numOpen > numClose)
{
if (numOpen - numClose == 1)
report.addError("Missing a close brace '}'.");
else
report.addError("Missing " + (numOpen - numClose) + " close braces '}'.");
return;
}
}
//-------------------------------------------------------------------------
/**
* Check that all options have been expanded.
*/
private static void checkOptionsExpanded(final String expanded, final Report report)
{
int c = -1; // start at char 0 (c+1)
while (true)
{
c = expanded.indexOf("<", c+1);
if (c == -1)
break;
int cc = StringRoutines.matchingBracketAt(expanded, c);
if (cc == -1)
cc = c + 5;
final char ch = expanded.charAt(c+1);
if (StringRoutines.isNameChar(ch))
{
report.addError("Option tag " + (expanded.substring(c, cc+1)) + " not expanded.");
return;
}
}
}
//-------------------------------------------------------------------------
/**
* Finds symbols that match this item's token.
*/
private static void matchTokensWithSymbols
(
final ParseItem item,
final Grammar grammar,
final Report report
)
{
if (item.token() == null)
{
//System.out.println("Null token for item: " + item.dump(" "));
report.addError("Null token for item: " + item.dump(" "));
return;
}
try
{
// item.matchSymbols(grammar, report);
matchSymbols(item, grammar, report);
}
catch (final Exception e)
{
//errors.add("Catching exception...");
//System.out.println("- Catching matchSymbols() exception...");
}
if (item.instances().isEmpty())
{
switch (item.token().type())
{
case Terminal:
String error = "Couldn't find token '" + item.token().name() + "'.";
if (Character.isLowerCase(item.token().name().charAt(0)))
error += " Maybe missing bracket '(" + item.token().name() + " ...)'?";
report.addError(error);
break;
case Class:
report.addError("Couldn't find ludeme class for token '" + item.token().name() + "'.");
break;
case Array:
// Not an error
break;
}
}
for (final ParseItem arg : item.arguments())
matchTokensWithSymbols(arg, grammar, report);
}
/**
* @param item
* @param grammar
* @param report
*/
public static void matchSymbols(final ParseItem item, final Grammar grammar, final Report report)
{
item.clearInstances();
Arg arg;
switch (item.token().type())
{
case Terminal: // String, number, enum, True, False
arg = new ArgTerminal(item.token().name(), item.token().parameterLabel());
arg.matchSymbols(grammar, report); // instantiates actual object(s), not need for clauses
final String str = arg.symbolName();
if (!str.isEmpty() && Character.isLowerCase(str.charAt(0)))
{
final String msg = "Terminal constant '" + str + "' is lowercase.";
report.addWarning(msg);
System.out.println(msg); // to remind us to tidy up the game descriptions
}
for (final Instance instance : arg.instances())
item.add(instance);
break;
case Class:
// Find matching symbols and their clauses
arg = new ArgClass(item.token().name(), item.token().parameterLabel());
arg.matchSymbols(grammar, report);
for (final Instance instance : arg.instances())
item.add(instance);
// Associate clauses with each instance of arg
for (final Instance instance : item.instances())
{
final GrammarRule rule = instance.symbol().rule();
if (rule != null)
instance.setClauses(rule.rhs());
}
break;
case Array:
// Do nothing: use instances of each element on a case-by-case basis
break;
}
}
//-------------------------------------------------------------------------
private static void checkStrings(final String expanded, final Report report)
{
// Get number of players?
int numPlayers = 0;
final int playersFrom = expanded.indexOf("(players");
if (playersFrom >= 0)
{
final int playersTo = StringRoutines.matchingBracketAt(expanded, playersFrom);
if (playersTo >= 0)
{
// Check if defined in form (players { (player ...) (player ...) })
int p = 0;
while (true)
{
p = expanded.indexOf("(player", p+1);
if (p == -1)
break;
// Check that "(player":
// 1. is within scope of (players ...) as more than one Player class
// 2. but doesn't match "(players"
if (p > playersFrom && p < playersTo && expanded.charAt(p + 7) != 's')
numPlayers++;
}
if (numPlayers == 0)
{
// Check if defined in form (players N)
p = expanded.indexOf("(players");
if (p != -1)
{
final int pp = StringRoutines.matchingBracketAt(expanded, p);
if (pp == -1)
{
report.addError("No closing bracket for '(players ...'.");
return;
}
final String playerString = expanded.substring(p, pp+1).trim();
final String countString = expanded.substring(p+8, pp).trim();
final String[] subs = countString.split(" ");
// System.out.println("countString is '" + countString + "', subs[0] is '" + subs[0] + "'.");
try
{
numPlayers = Integer.parseInt(subs[0]);
}
catch (final Exception e)
{
// System.out.println(numPlayers + " players.");
report.addError("Couldn't extract player count from '" + playerString + "'.");
return;
}
}
}
}
}
//System.out.println(numPlayers + " players.");
// Get list of known strings: player names, named items, phases, coordinates, etc.
final Map<Integer, String> knownStrings = new HashMap<Integer, String>();
// Add known defaults
final String[] defaults =
{ "Player", "Board", "Hand", "Ball", "Bag", "Domino" };
for (final String def : defaults)
knownStrings.put(Integer.valueOf(def.hashCode()), def);
extractKnownStrings(expanded, "(game", true, knownStrings, report);
extractKnownStrings(expanded, "(match", true, knownStrings, report);
extractKnownStrings(expanded, "(subgame", true, knownStrings, report);
extractKnownStrings(expanded, "(subgame", false, knownStrings, report);
extractKnownStrings(expanded, "(players", false, knownStrings, report);
extractKnownStrings(expanded, "(equipment", false, knownStrings, report);
extractKnownStrings(expanded, "(phase", true, knownStrings, report);
extractKnownStrings(expanded, "(vote", true, knownStrings, report);
extractKnownStrings(expanded, "(move Vote", true, knownStrings, report);
extractKnownStrings(expanded, "(is Proposed", true, knownStrings, report);
extractKnownStrings(expanded, "(is Decided", true, knownStrings, report);
extractKnownStrings(expanded, "(note", true, knownStrings, report);
extractKnownStrings(expanded, "(trigger", true, knownStrings, report);
extractKnownStrings(expanded, "(is Trigger", true, knownStrings, report);
extractKnownStrings(expanded, "(trackSite", false, knownStrings, report);
extractKnownStrings(expanded, "(set Var", false, knownStrings, report);
extractKnownStrings(expanded, "(var", false, knownStrings, report);
extractKnownStrings(expanded, "(remember", false, knownStrings, report);
extractKnownStrings(expanded, "(set RememberValue", false, knownStrings, report);
extractKnownStrings(expanded, "(values Remembered", false, knownStrings, report);
// System.out.println("Known strings:");
// for (final String known : knownStrings.values())
// System.out.println("> " + known);
// Check rest of description for strings
//int c = ee; // start at end of (equipment ...)
int c = -1;
while (true)
{
c = expanded.indexOf('"', c+1);
if (c == -1)
break; // no more strings in description
final int cc = StringRoutines.matchingQuoteAt(expanded, c);
if (cc == -1)
{
report.addError("Couldn't close string: " + expanded.substring(c));
return;
}
final String str = expanded.substring(c+1, cc);
// System.out.println("Checking clause: " + str);
if (!StringRoutines.isCoordinate(str)) //str.length() > 2) // ignore trivial coordinates
{
// Check whether this string is known
boolean match = false;
final int key = str.hashCode();
if (knownStrings.containsKey(Integer.valueOf(key)))
match = true;
if (!match)
{
// Compare each individual string
//for (final String item : knownStrings)
for (final String known : knownStrings.values())
{
if (known.equals(str))
{
match = true;
break;
}
// System.out.println("str=" + str + ", known=" + known);
if (!known.contains(str) && !str.contains(known))
continue; // not a possible match
if (Math.abs(str.length() - known.length()) > 2)
continue; // not a numbered variant
// Check player index is in player range
// final int pid = StringRoutines.numberAtEnd(str);
//System.out.println("pid=" + pid + ", numPlayers=" + numPlayers);
// if (pid < 0 || pid > numPlayers + 1)
// {
// errors.add("Bad player index " + pid + " on item '" + str + "'.");
// return;
// }
// if (pid > numPlayers && !str.contains("Hand"))
// report.addWarning("Item '" + str + "' is numbered " + pid + " but only " + numPlayers + " players.");
match = true;
break;
}
}
if (!match && str.length() <= 5 && StringRoutines.isCoordinate(str))
continue; // allow any coordinate to match
if (!match)
{
report.addError("Could not match string '" + str + "'. Misspelt define or item?");
return;
}
}
c = cc + 1;
}
}
/**
* Extracts strings from within the specified clause(s).
* Set 'firstStringPerClause' to false if only want to pick up first String, e.g. game or phase name.
*/
private static void extractKnownStrings
(
final String expanded,
final String targetClause,
final boolean firstStringPerClause,
final Map<Integer, String> knownStrings,
final Report report
)
{
int e = -1;
while (true)
{
// Find next instance of target clause
e = expanded.indexOf(targetClause, e+1);
if (e == -1)
return;
// System.out.println("Found clause starting " + targetClause + "...");
// Extract clause
final int ee = StringRoutines.matchingBracketAt(expanded, e);
if (ee == -1)
{
report.addError("Couldn't close string: " + expanded.substring(e));
return;
}
final String clause = expanded.substring(e, ee+1);
// System.out.println("Clause is: " + expanded.substring(e));
// Get substrings within clause
int i = -1;
while (true)
{
i = clause.indexOf('"', i+1);
if (i == -1)
break; // no more substrings in clause
// System.out.println("substring from: " + clause.substring(i));
final int ii = StringRoutines.matchingQuoteAt(clause, i);
if (ii == -1)
{
report.addError("Couldn't close item string: " + clause.substring(i));
return;
}
final String known = clause.substring(i+1, ii);
// System.out.println("known: " + known);
if (!StringRoutines.isCoordinate(known))
{
// Ignore coordinates (e.g. "A1", "A123", "AA123", "123")
// System.out.println("Putting: " + known);
knownStrings.put(Integer.valueOf(known.hashCode()), known);
if (firstStringPerClause)
break; // exit this clause, but still check for subsequent clauses
}
i = ii; // + 1;
}
}
}
//-------------------------------------------------------------------------
private static void checkVersion(final String raw, final Report report)
{
final int v = raw.indexOf("(version");
if (v == -1)
{
// System.out.println("** No version info.");
report.addWarning("No version info.");
return; // no version info
}
int s = v;
while (s < raw.length() && raw.charAt(s) != '"')
s++;
if (s >= raw.length())
{
//System.out.println("** Parser.checkVersion(): Couldn't find version string.");
report.addError("Couldn't find version string in (version ...) entry.");
return;
}
final int ss = StringRoutines.matchingQuoteAt(raw, s);
if (ss == -1)
{
report.addError("Couldn't close version string in (version ...) entry.");
return;
}
final String version = raw.substring(s+1, ss);
// Integer value representing the version number of the game description.
final int gameVersionInteger = Integer.valueOf(version.split("\\.")[0]).intValue() * 1000000
+ Integer.valueOf(version.split("\\.")[1]).intValue() * 1000
+ Integer.valueOf(version.split("\\.")[2]).intValue();
// Integer value representing the version number of the app.
final int appVersionInteger = Integer.valueOf(Constants.LUDEME_VERSION.split("\\.")[0]).intValue() * 1000000
+ Integer.valueOf(Constants.LUDEME_VERSION.split("\\.")[1]).intValue() * 1000
+ Integer.valueOf(Constants.LUDEME_VERSION.split("\\.")[2]).intValue();
final int result = appVersionInteger - gameVersionInteger;
if (result < 0)
report.addWarning("Game version (" + version + ") newer than app version (" + Constants.LUDEME_VERSION + ").");
else if (result > 0)
report.addWarning("Game version (" + version + ") older than app version (" + Constants.LUDEME_VERSION + ").");
}
//-------------------------------------------------------------------------
/**
* @param cls
* @return Formatted tooltip help string for the specified class. For use in the
* ludeme editors.
*/
public static String tooltipHelp(final Class<?> cls)
{
if (cls.getSimpleName().equalsIgnoreCase("add"))
{
return
"add\n" +
"Add a piece...\n" +
"\n" +
"Format\n" +
"(add ...)\n" +
"where:\n" +
"• <int>: Minimum length of lines.\n" +
"• [<absoluteDirection>]: Direction category that potential lines must belong to.\n" +
"\n" +
"Example\n" +
"(add ...)\n";
}
return "No tooltip found for class " + cls.getName();
}
//-------------------------------------------------------------------------
/**
* @param cls
* @return List of ludemes (or terminal objects) that could be used as
* alternatives for the specified class. For use in the ludeme editors.
*/
public static List<Class<?>> alternativeClasses(final Class<?> cls)
{
final List<Class<?>> alternatives = new ArrayList<Class<?>>();
if (cls.getSimpleName().equalsIgnoreCase("and"))
{
// A sampling of some ludemes that can be used instead of Line
Class<?> alternative = null;
try { alternative = Class.forName("game.functions.booleans.math.And"); }
catch (final ClassNotFoundException e) { e.printStackTrace(); }
alternatives.add(alternative);
}
return alternatives;
}
/**
* @param cls
* @return List of ludemes (or terminal objects) that could be used as
* alternatives for the specified class. For use in the ludeme editors.
*/
public static List<Object> alternativeInstances(final Class<?> cls)
{
final List<Object> alternatives = new ArrayList<Object>();
// if (cls.getSimpleName().equalsIgnoreCase("and"))
// {
// // A sampling of some ludemes that can be used instead of Line
// alternatives.add(new And(null, null));
// }
// TODO: Implement alternative ludemes list.
System.out.println("* Note: Alternative ludemes list not implemented yet.");
return alternatives;
}
//-------------------------------------------------------------------------
/**
* @param description Game description (may be expanded or not).
* @param cursorAt Character position of cursor.
* @param isSelect True if selected.
* @param type Type of selection.
* @return Range of scope of current token.
*/
public static TokenRange tokenScope
(
final String description, final int cursorAt, final boolean isSelect,
final SelectionType type
)
{
System.out.println("Selection type: " + type);
if (cursorAt <= 0 || cursorAt >= description.length())
{
System.out.println("** Grammar.classPaths(): Invalid cursor position " + cursorAt + " specified.");
return null;
}
// Get full keyword at cursor
int c = cursorAt - 1;
char ch = description.charAt(c);
if (!StringRoutines.isTokenChar(ch))
{
// Not currently on a token (or at the start of one): return nothing
return null;
}
while (c > 0 && StringRoutines.isTokenChar(ch))
{
c--;
ch = description.charAt(c);
if (ch == '<' && StringRoutines.isLetter(description.charAt(c + 1)))
break; // should be a rule
}
// Get token
int cc = cursorAt;
char ch2 = description.charAt(cc);
while (cc < description.length() && StringRoutines.isTokenChar(ch2))
{
cc++;
if (cc < description.length())
ch2 = description.charAt(cc);
}
if (cc >= description.length())
{
System.out.println("** Grammar.classPaths(): Couldn't find end of token scope from position " + cursorAt + ".");
return null;
}
// if (ch2 == ':')
// {
// // Token is a parameter name: return nothing
// return null;
// }
final String token = description.substring(c+1, cc);
System.out.println("token: " + token);
if (isSelect)
{
// Select entire entry
// System.out.println("isSelect substring is: " + description.substring(c, cc));
if (description.charAt(c) == ':' || description.charAt(c - 1) == ':')
{
// Is named parameter (second test is to catch "name:<rule>")
c -= 2;
while (c > 0 && StringRoutines.isTokenChar(description.charAt(c)))
c--;
c++;
// System.out.println("....new substring ':' is: " + description.substring(c, cc));
}
if (description.charAt(cc) == ':' || description.charAt(cc + 1) == ':')
{
// Is named parameter (clicked on name, not value)
cc++;
while (cc < description.length() && StringRoutines.isTokenChar(description.charAt(cc)))
cc++;
// System.out.println("....new substring 'name:' is: " + description.substring(c, cc));
}
if (c > 0 && description.charAt(c - 1) == '[')
{
// Is an optional parameter
c--;
cc = StringRoutines.matchingBracketAt(description, c) + 1;
// System.out.println("....new substring '[' A is: " + description.substring(c, cc));
}
else if (c > 0 && description.charAt(c) == '[')
{
// Is an optional parameter
cc = StringRoutines.matchingBracketAt(description, c) + 1;
// System.out.println("....new substring '[' B is: " + description.substring(c, cc));
}
else if (description.charAt(cc + 1) == ']')
{
cc++;
c = cc - 1;
while (c > 0 && description.charAt(c) != '[')
c--;
// System.out.println("....new substring ']' is: " + description.substring(c, cc));
}
}
// Handle primitive and predefined types
if (token.charAt(0) == '"')
{
// Is a string: note that quotes '"' are a valid token character
System.out.println("String scope includes: " + description.substring(c, cc));
return new TokenRange(c, cc);
}
if (token.equalsIgnoreCase("true"))
{
if (description.charAt(c) == ':')
c++; // named parameter
System.out.println("True scope includes: " + description.substring(c, cc));
return new TokenRange(c, cc);
}
if (token.equalsIgnoreCase("false"))
{
if (description.charAt(c) == ':')
c++; // named parameter
System.out.println("False scope includes: " + description.substring(c, cc));
return new TokenRange(c, cc);
}
if (StringRoutines.isInteger(token))
{
System.out.println("Int scope includes: " + description.substring(c, cc));
return new TokenRange(c, cc);
}
if (StringRoutines.isFloat(token) || StringRoutines.isDouble(token))
{
System.out.println("Float scope includes: " + description.substring(c, cc));
return new TokenRange(c, cc);
}
if (type == SelectionType.SELECTION || type == SelectionType.TYPING)
{
// Return scope of token, not entire ludeme
if (ch == '(')
c++;
System.out.println("Selected token scope includes: '" + description.substring(c, cc) +"'");
return new TokenRange(c, cc);
}
// Filter out unwanted matches
if (ch == '(')
{
// Is a class constructor: match to end of scope
// System.out.println("Is a constructor '" + partialKeyword + "'...");
final int closing = StringRoutines.matchingBracketAt(description, c);
if (closing < 0)
{
System.out.println("** Couldn't close token: " + token);
return null;
}
System.out.println("Class scope includes: " + description.substring(c, closing+1));
return new TokenRange(c, closing+1);
}
if (ch == '<')
{
// Is a rule
System.out.println("Rule scope includes: " + description.substring(c, cc));
return new TokenRange(c, cc);
}
if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == ':' || ch == '{')
{
// Is a terminal (probably an enum)
System.out.println("Enum constant scope includes: '" + description.substring(c+1, cc) +"'");
return new TokenRange(c+1, cc);
}
//return null;
return new TokenRange(c, cc);
}
//-------------------------------------------------------------------------
// /**
// * @return Whether string describes a top-level ludeme (Game, Match or Metadata).
// */
// public static boolean isTopLevelLudeme(final String str)
// {
// return str.contains("(game") || str.contains("(match") || str.contains("(metadata");
// }
/**
* @param str Game description.
* @return Whether string describes a Game or Match.
*/
public static boolean isGameOrMatch(final String str)
{
return str.contains("(game") || str.contains("(match");
}
//-------------------------------------------------------------------------
}
| 33,029 | 28.464764 | 122 |
java
|
Ludii
|
Ludii-master/Language/src/parser/SelectionType.java
|
package parser;
/**
* Types of ways in which editor text can be replaced.
*
* @author cambolbro
*/
public enum SelectionType
{
/** Replacement through right-click context selection. */
CONTEXT,
/** Replacement of selected text. */
SELECTION,
/** Replacement through autosuggest in response to typing. */
TYPING
}
| 329 | 16.368421 | 62 |
java
|
Ludii
|
Ludii-master/Language/src/parser/TokenRange.java
|
package parser;
/**
* Specifies a token's range within a String.
* @author cambolbro
*/
public class TokenRange
{
final int from;
final int to;
//-------------------------------------------------------------------------
/**
* @param from Range from (inclusive).
* @param to Range to (exclusive).
*/
public TokenRange(final int from, final int to)
{
this.from = from;
this.to = to;
}
//-------------------------------------------------------------------------
/**
* @return Range from (inclusive).
*/
public int from()
{
return from;
}
/**
* @return Range to (exclusive).
*/
public int to()
{
return to;
}
//-------------------------------------------------------------------------
}
| 743 | 15.533333 | 76 |
java
|
Ludii
|
Ludii-master/LudiiDocGen/src/help/GenerateLudiiEditorHelpFile.java
|
package help;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import annotations.Hide;
import gnu.trove.list.array.TIntArrayList;
import grammar.ClassEnumerator;
import grammar.Grammar;
import main.Constants;
import main.StringRoutines;
import main.grammar.Symbol;
import metadata.MetadataItem;
import other.Ludeme;
/**
* Code to generate a help file for generating auto-complete etc. in Ludii's editor.
*
* @author Dennis Soemers
*/
public class GenerateLudiiEditorHelpFile
{
private static final Grammar grammar = Grammar.grammar();
private static final String HELP_FILE_NAME = "../Common/res/help/EditorHelp.txt";
private static final String DEFS_DIR = "../Common/res/def";
/** Map of pieces of text to replace in documentation */
private static final Map<String, String> TEXT_TO_REPLACE = new HashMap<String, String>();
/** All the game classes (under the game package) */
private static List<Class<?>> gameClasses;
/** All the metadata classes (under the metadata package) */
private static List<Class<?>> metadataClasses;
static
{
TEXT_TO_REPLACE.put("MAX_DISTANCE", "" + Constants.MAX_DISTANCE);
TEXT_TO_REPLACE.put("\\\\url", "\\url");
TEXT_TO_REPLACE.put("\\\\texttt{", "\\texttt{");
TEXT_TO_REPLACE.put("$\\\\leq$", "<=");
TEXT_TO_REPLACE.put("$\\\\geq$", ">=");
TEXT_TO_REPLACE.put("$\\\\neq$", "$=/=");
TEXT_TO_REPLACE.put("\\\\frac{", "\\frac{");
TEXT_TO_REPLACE.put("\\\\exp(", "\\exp(");
TEXT_TO_REPLACE.put("\\\\tanh", "\\tanh");
try
{
gameClasses = ClassEnumerator.getClassesForPackage(Class.forName("game.Game").getPackage());
metadataClasses = ClassEnumerator.getClassesForPackage(Class.forName("metadata.Metadata").getPackage());
}
catch (final ClassNotFoundException e)
{
e.printStackTrace();
}
}
/**
* Main method
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws ClassNotFoundException
*/
public static void generateHelp() throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException
{
// First we'll read the XML file we generated
final File inputFile = new File("../LudiiDocGen/out/xml/jel.xml");
final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
final Document doc = dBuilder.parse(inputFile);
final Element root = doc.getDocumentElement();
final List<ClassTreeNode> rootPackages = new ArrayList<ClassTreeNode>();
final List<Node> classNodes = xmlChildrenForName(root, "jelclass");
for (int i = 0; i < classNodes.size(); ++i)
{
final Node child = classNodes.get(i);
if (hasAnnotation(child, "Hide") || hasAnnotation(child, "ImpliedRule"))
continue;
final NamedNodeMap attributes = child.getAttributes();
final String packageStr = attributes.getNamedItem("package").getTextContent();
String type = attributes.getNamedItem("type").getTextContent();
final String fullType = packageStr + "." + type.replaceAll(Pattern.quote("."), Matcher.quoteReplacement("$"));
final Class<?> clazz = Class.forName(fullType);
if (!Ludeme.class.isAssignableFrom(clazz) && !MetadataItem.class.isAssignableFrom(clazz) && !clazz.isEnum())
continue; // We skip classes that are neither Ludemes nor enums
// if ((clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) && !clazz.isEnum())
// continue; // We skip interfaces and abstract classes
if (type.contains("."))
{
if (!clazz.isEnum())
{
System.out.println("Skipping inner class type: " + fullType);
continue;
}
else
{
// Need to get rid of outer class
final String[] typeSplit = type.split(Pattern.quote("."));
type = typeSplit[typeSplit.length - 1];
}
}
boolean grammarSymbolUsed = false;
boolean metadataSymbolUsed = false;
final List<Symbol> grammarSymbols = grammar.symbolListFromClassName(type);
if (grammarSymbols != null)
{
for (final Symbol symbol : grammarSymbols)
{
if (symbol.usedInDescription())
grammarSymbolUsed = true;
if (symbol.usedInGrammar())
grammarSymbolUsed = true;
if (symbol.usedInMetadata())
metadataSymbolUsed = true;
if (grammarSymbolUsed && metadataSymbolUsed)
break;
}
}
if (!grammarSymbolUsed && !metadataSymbolUsed && !MetadataItem.class.isAssignableFrom(clazz))
{
System.out.println("Ignoring type not used in grammar or metadata: " + fullType);
continue;
}
final String[] subpackages = packageStr.split(Pattern.quote("."));
// Find matching package in our list of root packages
ClassTreeNode currentNode = null;
List<ClassTreeNode> currentPackages = rootPackages;
final List<String> fullTypeStrParts = new ArrayList<String>();
for (int j = 0; j < subpackages.length; ++j)
{
boolean foundPackage = false;
fullTypeStrParts.add(subpackages[j]);
for (final ClassTreeNode pckg : currentPackages)
{
if (subpackages[j].equals(pckg.name))
{
currentNode = pckg;
foundPackage = true;
break;
}
}
if (!foundPackage)
{
// Didn't find a match, so have to instantiate a new root package
currentNode = new ClassTreeNode(subpackages[j], true, StringRoutines.join(".", fullTypeStrParts), clazz.isEnum(), child);
currentPackages.add(currentNode);
}
currentPackages = currentNode.children;
}
// Create new node for this type
fullTypeStrParts.add(type);
currentPackages.add(new ClassTreeNode(type, false, attributes.getNamedItem("fulltype").getTextContent(), clazz.isEnum(), child));
}
// Try to nicely sort all packages; first classes in alphabetical order, then subpackages
sortPackages(rootPackages);
// Create StringBuilder to contain all our help info
final StringBuilder sb = new StringBuilder();
// Process all our packages in a depth-first manner
for (final ClassTreeNode node : rootPackages)
{
process(node, sb);
}
// Also process all our def files
processDefFiles(sb);
// Postprocess our full string to fix type names,
// and replace other keywords that need replacing
while (true)
{
final int paramStartIdx = sb.indexOf("<PARAM:");
if (paramStartIdx < 0) // we're done
break;
final int paramEndIdx = sb.indexOf(">", paramStartIdx);
String paramTypeStr = sb.substring(paramStartIdx, paramEndIdx);
paramTypeStr = paramTypeStr.substring("<PARAM:".length(), paramTypeStr.length());
if (paramTypeStr.endsWith("[]"))
paramTypeStr = paramTypeStr.substring(0, paramTypeStr.length() - "[]".length());
final String[] paramTypeStrSplit = paramTypeStr.split(Pattern.quote("."));
final String paramTypeText = typeString(StringRoutines.lowerCaseInitial(paramTypeStrSplit[paramTypeStrSplit.length - 1]));
sb.replace(paramStartIdx, paramEndIdx + 1, paramTypeText);
}
// Remove \texttt{} LaTeX commands
while (true)
{
final int textttStartIdx = sb.indexOf("\\texttt{");
if (textttStartIdx < 0) // we're done
break;
final int textttEndIdx = sb.indexOf("}", textttStartIdx);
sb.replace
(
textttStartIdx,
textttEndIdx + 1,
sb.substring(textttStartIdx + "\\texttt{".length(), textttEndIdx)
);
}
for (final String key : TEXT_TO_REPLACE.keySet())
{
while (true)
{
final int startIdx = sb.indexOf(key);
if (startIdx < 0) // we're done
break;
final int endIdx = startIdx + key.length();
sb.replace(startIdx, endIdx, TEXT_TO_REPLACE.get(key));
}
}
// Write our help file
final File outFile = new File(HELP_FILE_NAME);
outFile.getParentFile().mkdirs();
System.out.println("Writing file: " + outFile.getCanonicalPath());
try (final PrintWriter writer = new PrintWriter(outFile))
{
writer.write(sb.toString());
}
}
/**
* Processes the given node
* @param node
* @param sb
* @throws ClassNotFoundException
*/
private static void process(final ClassTreeNode node, final StringBuilder sb) throws ClassNotFoundException
{
if (node.isPackage)
{
for (final ClassTreeNode child : node.children)
{
process(child, sb);
}
}
else
{
if (node.isEnum)
processEnumNode(node, sb);
else
processClassNode(node, sb);
}
}
/**
* Processes the given class node
* @param node
* @param sb
* @throws ClassNotFoundException
*/
private static void processClassNode(final ClassTreeNode node, final StringBuilder sb) throws ClassNotFoundException
{
// We're starting a new class
final Class<?> clazz = Class.forName(node.fullType);
final String ludemeName = StringRoutines.lowerCaseInitial(node.name);
appendLine(sb, "TYPE: " + node.fullType);
// Handle @Alias annotation
String unformattedAlias = null;
if (hasAnnotation(node.xmlNode, "Alias"))
{
final Node annotationsNode = xmlChildForName(node.xmlNode, "annotations");
if (annotationsNode != null)
{
final List<Node> annotationNodes = xmlChildrenForName(annotationsNode, "annotation");
for (final Node annotationNode : annotationNodes)
{
final String annotationType = annotationNode.getAttributes().getNamedItem("type").getTextContent();
if (annotationType.equals("Alias"))
{
final Node valuesNode = xmlChildForName(annotationNode, "values");
final Node valueNode = xmlChildForName(valuesNode, "value");
unformattedAlias = valueNode.getAttributes().getNamedItem("value").getTextContent();
break;
}
}
}
}
// Write the comments on top of class
final Node classCommentNode = xmlChildForName(node.xmlNode, "comment");
if (classCommentNode != null)
{
final Node descriptionNode = xmlChildForName(classCommentNode, "description");
if (descriptionNode != null)
appendLine(sb, "TYPE JAVADOC: " + descriptionNode.getTextContent().replaceAll(Pattern.quote("\n"), " ").trim());
}
if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()))
{
// Interface or abstract class
final List<Class<?>> potentialSubclasses;
if (node.fullType.startsWith("game"))
{
potentialSubclasses = gameClasses;
}
else if (node.fullType.startsWith("metadata"))
{
potentialSubclasses = metadataClasses;
}
else
{
potentialSubclasses = null;
System.err.println("Interface / abstract class starts with neither game nor metadata!");
}
final List<String> subclassTypes = new ArrayList<String>();
for (final Class<?> cls : potentialSubclasses)
{
if (clazz.isAssignableFrom(cls))
{
if (cls.isAssignableFrom(clazz))
continue; // Same class, skip this
if (cls.isAnnotationPresent(Hide.class))
continue; // Skip hidden classes
subclassTypes.add(cls.getName());
}
}
for (final String subclassType : subclassTypes)
{
appendLine(sb, "SUBCLASS: " + subclassType);
}
}
else
{
// Just a normal class
final Node methodsNode = xmlChildForName(node.xmlNode, "methods");
final List<Node> constructors = xmlChildrenForName(methodsNode, "constructor");
// also add public static create() methods to the constructors
final List<Node> createMethods = xmlChildrenForName(methodsNode, "method");
for (final Node methodNode : createMethods)
{
final Node staticAttribute = methodNode.getAttributes().getNamedItem("static");
if
(
staticAttribute != null &&
staticAttribute.getTextContent().equals("true") &&
methodNode.getAttributes().getNamedItem("visibility").getTextContent().equals("public") &&
methodNode.getAttributes().getNamedItem("name").getTextContent().equals("construct")
)
{
constructors.add(methodNode);
}
}
// Remove constructors with @Hide annotations
constructors.removeIf((final Node ctor) -> { return hasAnnotation(ctor, "Hide"); });
for (int ctorIdx = 0; ctorIdx < constructors.size(); ++ctorIdx)
{
final Node ctor = constructors.get(ctorIdx);
if (ctor.getAttributes().getNamedItem("visibility").getTextContent().equals("public"))
{
// A public constructor
appendLine(sb, "NEW CTOR");
final StringBuilder ctorSb = new StringBuilder();
if (unformattedAlias != null)
ctorSb.append("(" + unformattedAlias + "");
else
ctorSb.append("(" + ludemeName + "");
final Node paramsNode = xmlChildForName(ctor, "params");
final List<String> paramSymbols = new ArrayList<String>();
final TIntArrayList singleValueEnumParamIndices = new TIntArrayList();
if (paramsNode != null)
{
final List<Node> paramNodes = xmlChildrenForName(paramsNode, "param");
boolean orSequence = false;
boolean or2Sequence = false;
for (int paramNodeIdx = 0; paramNodeIdx < paramNodes.size(); ++paramNodeIdx)
{
final Node paramNode = paramNodes.get(paramNodeIdx);
// Figure out how to write this param
final String paramName = paramNode.getAttributes().getNamedItem("name").getTextContent();
String paramFullType = paramNode.getAttributes().getNamedItem("fulltype").getTextContent();
boolean named = false;
boolean optional = false;
int numArrayDims = 0;
boolean startNewOrSequence = false;
boolean endPreviousOrSequence = (orSequence || or2Sequence);
while (paramFullType.endsWith("[]"))
{
paramFullType = paramFullType.substring(0, paramFullType.length() - "[]".length());
numArrayDims += 1;
}
final Node annotationsNode = xmlChildForName(paramNode, "annotations");
if (annotationsNode != null)
{
final List<Node> annotationNodes = xmlChildrenForName(annotationsNode, "annotation");
for (final Node annotationNode : annotationNodes)
{
final String annotationType = annotationNode.getAttributes().getNamedItem("type").getTextContent();
if (annotationType.equals("Name"))
{
named = true;
}
else if (annotationType.equals("Opt"))
{
optional = true;
}
else if (annotationType.equals("Or"))
{
if (orSequence)
endPreviousOrSequence = false;
else
startNewOrSequence = true;
orSequence = true;
or2Sequence = false;
}
else if (annotationType.equals("Or2"))
{
if (or2Sequence)
endPreviousOrSequence = false;
else
startNewOrSequence = true;
orSequence = false;
or2Sequence = true;
}
}
}
if (endPreviousOrSequence)
{
orSequence = false;
or2Sequence = false;
ctorSb.append(")");
}
// Write this param
ctorSb.append(" ");
if (startNewOrSequence)
ctorSb.append("(");
else if (orSequence || or2Sequence)
ctorSb.append(" | ");
final StringBuilder paramSymbolSb = new StringBuilder();
if (optional)
paramSymbolSb.append("[");
if (named)
paramSymbolSb.append(paramName + ":");
for (int i = 0; i < numArrayDims; ++i)
{
paramSymbolSb.append("{");
}
final Class<?> paramClass = Class.forName(paramFullType);
if (Enum.class.isAssignableFrom(paramClass))
{
if (paramClass.getEnumConstants().length == 1)
{
paramSymbolSb.append(paramClass.getEnumConstants()[0].toString());
singleValueEnumParamIndices.add(paramNodeIdx);
}
else
{
paramSymbolSb.append("<PARAM:" + paramFullType + ">");
}
}
else
{
paramSymbolSb.append("<PARAM:" + paramFullType + ">");
}
for (int i = 0; i < numArrayDims; ++i)
{
paramSymbolSb.append("}");
}
if (optional)
paramSymbolSb.append("]");
paramSymbols.add(paramSymbolSb.toString());
ctorSb.append(paramSymbolSb);
}
if (orSequence || or2Sequence) // close final or sequence
ctorSb.append(")");
}
ctorSb.append(")");
appendLine(sb, ctorSb.toString());
if (paramSymbols.size() > 0)
{
// Add explanations of all the params
final List<Node> paramNodes = xmlChildrenForName(paramsNode, "param");
for (int paramNodeIdx = 0; paramNodeIdx < paramNodes.size(); ++paramNodeIdx)
{
if (singleValueEnumParamIndices.contains(paramNodeIdx))
continue; // Skip this param, it's a single-value enum
final Node paramNode = paramNodes.get(paramNodeIdx);
final Node commentNode = paramNode.getAttributes().getNamedItem("comment");
if (commentNode == null)
System.err.println("WARNING: No Javadoc comment for " + (paramNodeIdx + 1) + "th param of " + (ctorIdx + 1) + "th constructor of " + node.fullType);
String paramDescription = commentNode != null ? commentNode.getTextContent() : "";
paramDescription = StringRoutines.cleanWhitespace(paramDescription);
appendLine(sb, "PARAM JAVADOC: " + paramSymbols.get(paramNodeIdx) + ": " + paramDescription);
}
}
final Node ctorCommentNode = xmlChildForName(ctor, "comment");
if (ctorCommentNode != null)
{
final List<Node> attributes = xmlChildrenForName(ctorCommentNode, "attribute");
// Collect constructor-specific examples
boolean foundExample = false;
for (final Node attribute : attributes)
{
if (attribute.getAttributes().getNamedItem("name").getTextContent().equals("@example"))
{
final Node descriptionNode = xmlChildForName(attribute, "description");
appendLine
(
sb,
"EXAMPLE: " + StringRoutines.cleanWhitespace(descriptionNode.getTextContent())
);
foundExample = true;
}
}
if (!foundExample)
System.err.println("WARNING: Found no example for one of the constructors of ludeme: " + node.fullType);
}
}
}
}
if (classCommentNode != null)
{
final List<Node> attributes = xmlChildrenForName(classCommentNode, "attribute");
// Write remarks
for (final Node attribute : attributes)
{
if (attribute.getAttributes().getNamedItem("name").getTextContent().equals("@remarks"))
{
final Node descriptionNode = xmlChildForName(attribute, "description");
appendLine(sb, "REMARKS: " + StringRoutines.cleanWhitespace(descriptionNode.getTextContent()));
}
}
}
}
/**
* Processes the given enum node
* @param node
* @param sb
*/
private static void processEnumNode(final ClassTreeNode node, final StringBuilder sb)
{
// We're starting a new enum type
appendLine(sb, "TYPE: " + node.fullType);
// Write the comments on top of enum
final Node commentNode = xmlChildForName(node.xmlNode, "comment");
if (commentNode != null)
{
final Node descriptionNode = xmlChildForName(commentNode, "description");
if (descriptionNode != null)
appendLine(sb, "TYPE JAVADOC: " + StringRoutines.cleanWhitespace(descriptionNode.getTextContent()));
}
// Write enum value comments
final Node enumerationNode = xmlChildForName(node.xmlNode, "enumeration");
final List<Node> values = xmlChildrenForName(enumerationNode, "value");
if (!values.isEmpty())
{
for (final Node valueNode : values)
{
final String valueName = valueNode.getAttributes().getNamedItem("name").getTextContent();
final Node descriptionNode = valueNode.getAttributes().getNamedItem("description");
final String description = (descriptionNode != null) ? descriptionNode.getTextContent() : null;
if (description == null)
System.err.println("WARNING: no javadoc for value " + valueName + " of enum: " + node.fullType);
else if (StringRoutines.cleanWhitespace(description).equals(""))
System.err.println("WARNING: empty javadoc for value " + valueName + " of enum: " + node.fullType);
if (description != null)
appendLine(sb, "CONST JAVADOC: " + valueName + ": " + description);
}
}
}
/**
* @param xmlNode
* @param name
* @return Child of given XML node with given name
*/
private static final Node xmlChildForName(final Node xmlNode, final String name)
{
final NodeList childNodes = xmlNode.getChildNodes();
for (int i = 0; i < childNodes.getLength(); ++i)
{
if (name.equals(childNodes.item(i).getNodeName()))
return childNodes.item(i);
}
return null;
}
/**
* @param xmlNode
* @param name
* @return Children of given XML node with given name
*/
private static final List<Node> xmlChildrenForName(final Node xmlNode, final String name)
{
final List<Node> ret = new ArrayList<Node>();
final NodeList childNodes = xmlNode.getChildNodes();
for (int i = 0; i < childNodes.getLength(); ++i)
{
if (name.equals(childNodes.item(i).getNodeName()))
ret.add(childNodes.item(i));
}
return ret;
}
/**
* @param type
* @return Generates a String for a given type, as it would also appear in grammar
*/
private static final String typeString(final String type)
{
final String str = StringRoutines.lowerCaseInitial(type);
if (str.equals("integer"))
return "int";
else if (str.equals("intFunction"))
return "<int>";
else if (str.equals("booleanFunction"))
return "<boolean>";
else if (str.equals("regionFunction"))
return "<region>";
return "<" + str + ">";
}
/**
* @param node
* @param type
* @return True if the given node contains an annotation of given type
*/
private static final boolean hasAnnotation(final Node node, final String type)
{
final Node annotationsNode = xmlChildForName(node, "annotations");
if (annotationsNode != null)
{
final List<Node> annotationNodes = xmlChildrenForName(annotationsNode, "annotation");
for (final Node annotationNode : annotationNodes)
{
final String annotationType = annotationNode.getAttributes().getNamedItem("type").getTextContent();
if (annotationType.equals(type))
return true;
}
}
return false;
}
/**
* Processes all our .def files
* @param sb
*/
private static final void processDefFiles(final StringBuilder sb)
{
// Get list of directories
final List<File> dirs = new ArrayList<File>();
final File folder = new File(DEFS_DIR);
dirs.add(folder);
for (int i = 0; i < dirs.size(); ++i)
{
final File dir = dirs.get(i);
for (final File file : dir.listFiles())
if (file.isDirectory())
dirs.add(file);
}
Collections.sort(dirs);
// Visit files in each directory
for (final File dir : dirs)
{
for (final File file : dir.listFiles())
if (!file.isDirectory())
processDefFile(file, sb);
}
}
/**
* Processes a single given .def file
* @param file
* @param sb
*/
private static final void processDefFile(final File file, final StringBuilder sb)
{
if (!file.getPath().contains(".def"))
{
System.err.println("Bad file: " + file.getPath());
return;
}
// Read lines in
final List<String> lines = new ArrayList<String>();
try
(
final BufferedReader reader =
new BufferedReader
(
new InputStreamReader
(
new FileInputStream(file),
StandardCharsets.UTF_8
)
)
)
{
String line = reader.readLine();
while (line != null)
{
lines.add(line);
line = reader.readLine();
}
}
catch (final IOException e)
{
e.printStackTrace();
}
// Write .def name
final String name = file.getName().substring(0, file.getName().length() - ".def".length());
appendLine(sb, "DEFINE: " + name);
// Write def comments
appendLine(sb, "DEFINE JAVADOC: " + commentsFromLines(lines));
// Write examples
for (final String example : examplesFromLines(lines))
{
appendLine(sb, "DEFINE EXAMPLE: " + StringRoutines.cleanWhitespace(example));
}
}
//-------------------------------------------------------------------------
final static String commentsFromLines(final List<String> lines)
{
final StringBuilder sb = new StringBuilder();
for (final String line : lines)
{
final int c = line.indexOf("//");
if (c < 0)
break; // not a comment
if (line.contains("@example"))
break; // don't include examples in comments
sb.append(line.substring(c + 2).trim() + " ");
}
return sb.toString();
}
//-------------------------------------------------------------------------
final static List<String> examplesFromLines(final List<String> lines)
{
final List<String> examples = new ArrayList<String>();
for (final String line : lines)
{
final int c = line.indexOf("@example");
if (c < 0)
continue; // not an example
examples.add(line.substring(c + 8).trim());
}
return examples;
}
//-------------------------------------------------------------------------
/**
* Appends given line to StringBuilder (+ newline character)
* @param sb
* @param line
*/
private static final void appendLine(final StringBuilder sb, final String line)
{
sb.append(line + "\n");
}
/**
* Makes sure all packages that are somewhere in the given list (including
* subpackages of these packages) are all nicely sorted: first classes,
* then subpackages, with each of those being sorted alphabetically.
* @param packages
*/
private static void sortPackages(final List<ClassTreeNode> packages)
{
packages.sort(new Comparator<ClassTreeNode>()
{
@Override
public int compare(final ClassTreeNode o1, final ClassTreeNode o2)
{
if (!o1.isPackage && o2.isPackage)
return -1;
if (o1.isPackage && !o2.isPackage)
return 1;
return o1.name.compareTo(o2.name);
}
});
for (final ClassTreeNode p : packages)
{
sortPackages(p.children);
}
}
/**
* Class for node in our tree of classes (and packages)
*
* @author Dennis Soemers
*/
private static class ClassTreeNode
{
/** Full package + type name */
public final String fullType;
/** Name of package or class */
public final String name;
/** True if we're a package, false if we're a class */
public boolean isPackage;
/** True if this is an enum (instead of a Ludeme class or package) */
public boolean isEnum;
/** The XML node */
public Node xmlNode;
/** List of child nodes (with subpackages and classes) */
public final List<ClassTreeNode> children = new ArrayList<ClassTreeNode>();
/**
* Constructor
* @param name
* @param isPackage
* @param fullType
* @param isEnum
* @param xmlNode
*/
public ClassTreeNode
(
final String name,
final boolean isPackage,
final String fullType,
final boolean isEnum,
final Node xmlNode
)
{
this.name = name;
this.isPackage = isPackage;
this.fullType = fullType;
this.isEnum = isEnum;
this.xmlNode = xmlNode;
}
@Override
public String toString()
{
return "[Node: " + fullType + "]";
}
}
}
| 28,267 | 27.815494 | 156 |
java
|
Ludii
|
Ludii-master/LudiiDocGen/src/main/GenerateLudiiEditorHelpFileMain.java
|
package main;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import help.GenerateLudiiEditorHelpFile;
import xml.GenerateLudiiDocXML;
/**
* Main method to generate (an updated version of) the help file for
* tooltips/autocomplete in the Ludii editor.
*
* @author Dennis Soemers
*/
public class GenerateLudiiEditorHelpFileMain
{
/**
* Main method
* @param args
* @throws IOException
* @throws InterruptedException
* @throws SAXException
* @throws ParserConfigurationException
* @throws ClassNotFoundException
*/
public static void main(final String[] args)
throws InterruptedException, IOException, ClassNotFoundException,
ParserConfigurationException, SAXException
{
GenerateLudiiDocXML.generateXML();
GenerateLudiiEditorHelpFile.generateHelp();
}
}
| 869 | 21.307692 | 69 |
java
|
Ludii
|
Ludii-master/LudiiDocGen/src/main/GenerateLudiiLanguageReference.java
|
package main;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import tex.GenerateLudiiDocTex;
import xml.GenerateLudiiDocXML;
/**
* Main method to go through full process for generating Ludii language reference
*
* @author Dennis Soemers
*/
public class GenerateLudiiLanguageReference
{
/**
* Main method
* @param args
* @throws IOException
* @throws InterruptedException
* @throws SAXException
* @throws ParserConfigurationException
* @throws ClassNotFoundException
*/
public static void main(final String[] args)
throws InterruptedException, IOException, ClassNotFoundException,
ParserConfigurationException, SAXException
{
GenerateLudiiDocXML.generateXML();
GenerateLudiiDocTex.generateTex();
}
}
| 817 | 20.526316 | 81 |
java
|
Ludii
|
Ludii-master/LudiiDocGen/src/tex/GenerateLudiiDocTex.java
|
package tex;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import gnu.trove.list.array.TIntArrayList;
import grammar.Grammar;
import graphics.svg.SVGLoader;
import main.Constants;
import main.StringRoutines;
import main.grammar.Description;
import main.grammar.Report;
import main.grammar.Symbol;
import main.grammar.Token;
import main.options.UserSelections;
import metadata.MetadataItem;
import other.Ludeme;
import parser.Parser;
//-----------------------------------------------------------------------------
/**
* Code to generate .tex files for Ludii Language Reference
*
* @author Dennis Soemers and cambolbro
*/
public class GenerateLudiiDocTex
{
private static final Grammar grammar = Grammar.grammar();
private static final int CHAPTER_GAME = 0;
private static final int CHAPTER_EQUIPMENT = 1;
private static final int CHAPTER_GRAPH_FUNCS = 2;
private static final int CHAPTER_DIM_FUNCS = 3;
private static final int CHAPTER_FLOAT_FUNCS = 4;
private static final int CHAPTER_RULES = 5;
private static final int CHAPTER_MOVES = 6;
private static final int CHAPTER_BOOLEAN_FUNCS = 7;
private static final int CHAPTER_INT_FUNCS = 8;
private static final int CHAPTER_INT_ARRAY_FUNCS = 9;
private static final int CHAPTER_REGION_FUNCS = 10;
private static final int CHAPTER_DIRECTION_FUNCS = 11;
private static final int CHAPTER_RANGE_FUNCS = 12;
private static final int CHAPTER_UTILITIES = 13;
private static final int CHAPTER_TYPES = 14;
private static final int CHAPTER_INFO_METADATA = 15;
private static final int CHAPTER_GRAPHICS_METADATA = 16;
private static final int CHAPTER_AI_METADATA = 17;
// private static final int CHAPTER_DEFINES = 15;
// private static final int CHAPTER_OPTIONS = 16;
// private static final int CHAPTER_RULESETS = 17;
// private static final int CHAPTER_RANGES = 18;
//
// private static final int APPENDIX_KNOWN_DEFINES = 19;
// private static final int APPENDIX_LUDII_GRAMMAR = 14;
private static final String[] CHAPTER_FILENAMES = new String[]
{
"out/tex/Chapter2GameLudemes.tex",
"out/tex/Chapter3Equipment.tex",
"out/tex/Chapter4GraphFuncs.tex",
"out/tex/Chapter5DimFuncs.tex",
"out/tex/Chapter6FloatFuncs.tex",
"out/tex/Chapter7Rules.tex",
"out/tex/Chapter8Moves.tex",
"out/tex/Chapter9BooleanFuncs.tex",
"out/tex/Chapter10IntFuncs.tex",
"out/tex/Chapter11IntArrayFuncs.tex",
"out/tex/Chapter12RegionFuncs.tex",
"out/tex/Chapter13DirectionFuncs.tex",
"out/tex/Chapter14RangeFuncs.tex",
"out/tex/Chapter15Utilities.tex",
"out/tex/Chapter16Types.tex",
"out/tex/Chapter17InfoMetadata.tex",
"out/tex/Chapter18GraphicsMetadata.tex",
"out/tex/Chapter19AIMetadata.tex",
// No! Overwrites source files
//"out/tex/ChapterXDefines.tex",
//"out/tex/ChapterXOptions.tex",
//"out/tex/ChapterXRulesets.tex",
//"out/tex/ChapterXRanges.tex",
//"out/tex/ChapterXConstants.tex",
//"out/tex/AppendixAKnownDefines.tex",
//"out/tex/AppendixBLudiiGrammar.tex",
};
private static final String[] CHAPTER_NAMES = new String[]
{
"Game",
"Equipment",
"Graph Functions",
"Dimension Functions",
"Float Functions",
"Rules",
"Moves",
"Boolean Functions",
"Integer Functions",
"Integer Array Functions",
"Region Functions",
"Direction Functions",
"Range Functions",
"Utilities",
"Types",
"Info Metadata",
"Graphics Metadata",
"AI Metadata",
"Defines",
"Options",
"Rulesets",
"Ranges",
"Constants",
"B -- Known Defines",
"A -- Ludii Grammar",
};
private static final String[] CHAPTER_LABELS = new String[]
{
"\\label{Chapter:GameLudemes}",
"\\label{Chapter:EquipmentLudemes}",
"\\label{Chapter:GraphFunctions}",
"\\label{Chapter:DimFunctions}",
"\\label{Chapter:FloatFunctions}",
"\\label{Chapter:RuleLudemes}",
"\\label{Chapter:MoveLudemes}",
"\\label{Chapter:BooleanLudemes}",
"\\label{Chapter:IntegerLudemes}",
"\\label{Chapter:IntegerArrayLudemes}",
"\\label{Chapter:RegionLudemes}",
"\\label{Chapter:DirectionLudemes}",
"\\label{Chapter:RangeLudemes}",
"\\label{Chapter:Utilities}",
"\\label{Chapter:Types}",
"\\label{Chapter:InfoMetadata}",
"\\label{Chapter:GraphicsMetadata}",
"\\label{Chapter:AIMetadata}",
"\\label{Chapter:Defines}",
"\\label{Chapter:Options}",
"\\label{Chapter:Rulesets}",
"\\label{Chapter:Ranges}",
"\\label{Chapter:Constants}",
"\\label{Appendix:KnownDefines}",
"\\label{Appendix:LudiiGrammar}",
};
/** Map from packages to chapters in which they should be included */
private static final Map<String, Integer> PACKAGE_TO_CHAPTER = new HashMap<String, Integer>();
static
{
PACKAGE_TO_CHAPTER.put("game", Integer.valueOf(CHAPTER_GAME));
PACKAGE_TO_CHAPTER.put("game.equipment", Integer.valueOf(CHAPTER_EQUIPMENT));
PACKAGE_TO_CHAPTER.put("game.functions.graph", Integer.valueOf(CHAPTER_GRAPH_FUNCS));
PACKAGE_TO_CHAPTER.put("game.functions.dim", Integer.valueOf(CHAPTER_DIM_FUNCS));
PACKAGE_TO_CHAPTER.put("game.functions.floats", Integer.valueOf(CHAPTER_FLOAT_FUNCS));
PACKAGE_TO_CHAPTER.put("game.functions.booleans", Integer.valueOf(CHAPTER_BOOLEAN_FUNCS));
PACKAGE_TO_CHAPTER.put("game.functions.intArray", Integer.valueOf(CHAPTER_INT_ARRAY_FUNCS));
PACKAGE_TO_CHAPTER.put("game.functions.ints", Integer.valueOf(CHAPTER_INT_FUNCS));
PACKAGE_TO_CHAPTER.put("game.functions.region", Integer.valueOf(CHAPTER_REGION_FUNCS));
PACKAGE_TO_CHAPTER.put("game.rules", Integer.valueOf(CHAPTER_RULES));
PACKAGE_TO_CHAPTER.put("game.rules.play.moves", Integer.valueOf(CHAPTER_MOVES));
PACKAGE_TO_CHAPTER.put("game.functions.directions", Integer.valueOf(CHAPTER_DIRECTION_FUNCS));
PACKAGE_TO_CHAPTER.put("game.functions.range", Integer.valueOf(CHAPTER_RANGE_FUNCS));
PACKAGE_TO_CHAPTER.put("game.types", Integer.valueOf(CHAPTER_TYPES));
PACKAGE_TO_CHAPTER.put("game.util", Integer.valueOf(CHAPTER_UTILITIES));
PACKAGE_TO_CHAPTER.put("metadata", Integer.valueOf(CHAPTER_INFO_METADATA));
PACKAGE_TO_CHAPTER.put("metadata.graphics", Integer.valueOf(CHAPTER_GRAPHICS_METADATA));
PACKAGE_TO_CHAPTER.put("metadata.ai", Integer.valueOf(CHAPTER_AI_METADATA));
}
/** Map from type descriptions in documentation strings to labels they should link to */
private static final Map<String, String> TYPE_TO_LABEL = new HashMap<String, String>();
static
{
TYPE_TO_LABEL.put("java.lang.Integer", "Sec:Introduction.Integers");
TYPE_TO_LABEL.put("java.lang.Boolean", "Sec:Introduction.Booleans");
TYPE_TO_LABEL.put("java.lang.Float", "Sec:Introduction.Floats");
TYPE_TO_LABEL.put("java.lang.String", "Sec:Introduction.Strings");
TYPE_TO_LABEL.put("game.equipment.container.board.shape.Shape", "Sec:game.equipment.container.board.shape");
TYPE_TO_LABEL.put("game.equipment.container.board.tiling.Tiling", "Sec:game.equipment.container.board.tiling.flat");
TYPE_TO_LABEL.put("game.equipment.container.board.tiling.flat.FlatTiling", "Sec:game.equipment.container.board.tiling.flat");
TYPE_TO_LABEL.put("game.equipment.container.board.tiling.pyramidal.PyramidalTiling", "Sec:game.equipment.container.board.tiling.pyramidal");
TYPE_TO_LABEL.put("game.equipment.container.board.modify.Modify", "Sec:game.equipment.container.board.modify");
TYPE_TO_LABEL.put("game.equipment.Item", "Chapter:EquipmentLudemes");
TYPE_TO_LABEL.put("game.functions.ints.IntFunction", "Chapter:IntegerLudemes");
TYPE_TO_LABEL.put("game.functions.intArray.IntArrayFunction", "Chapter:IntegerArrayLudemes");
TYPE_TO_LABEL.put("game.functions.booleans.BooleanFunction", "Chapter:BooleanLudemes");
TYPE_TO_LABEL.put("game.functions.range.RangeFunction", "Chapter:RangeLudemes");
TYPE_TO_LABEL.put("game.functions.region.RegionFunction", "Chapter:RegionLudemes");
TYPE_TO_LABEL.put("game.functions.directions.DirectionsFunction", "Chapter:DirectionLudemes");
TYPE_TO_LABEL.put("game.functions.graph.GraphFunction", "Chapter:GraphFunctions");
TYPE_TO_LABEL.put("game.functions.floats.FloatFunction", "Chapter:FloatFunctions");
TYPE_TO_LABEL.put("game.functions.dim.DimFunction", "Chapter:DimFunctions");
TYPE_TO_LABEL.put("game.rules.end.EndRule", "Sec:game.rules.end");
TYPE_TO_LABEL.put("game.rules.meta.MetaRule", "Sec:game.rules.meta");
TYPE_TO_LABEL.put("game.rules.play.moves.effect.Effects", "Sec:game.rules.play.moves.effect");
TYPE_TO_LABEL.put("game.rules.play.moves.Moves", "Chapter:MoveLudemes");
TYPE_TO_LABEL.put("game.rules.play.moves.nonDecision.NonDecision", "Chapter:MoveLudemes");
TYPE_TO_LABEL.put("game.rules.start.StartRule", "Sec:game.rules.start");
TYPE_TO_LABEL.put("game.util.directions.Direction", "Sec:game.util.directions");
TYPE_TO_LABEL.put("metadata.ai.heuristics.transformations.HeuristicTransformation", "Sec:metadata.ai.heuristics.transformations");
TYPE_TO_LABEL.put("metadata.ai.heuristics.terms.HeuristicTerm", "Sec:metadata.ai.heuristics.terms");
TYPE_TO_LABEL.put("metadata.graphics.Graphics", "Chapter:GraphicsMetadata");
TYPE_TO_LABEL.put("metadata.info.Info", "Chapter:InfoMetadata");
TYPE_TO_LABEL.put("metadata.info.InfoItem", "Sec:metadata.info.database");
}
/** Map of pieces of text to replace in documentation */
private static final Map<String, String> TEXT_TO_REPLACE = new HashMap<String, String>();
static
{
TEXT_TO_REPLACE.put("MAX_DISTANCE", "$" + Constants.MAX_DISTANCE + "$");
TEXT_TO_REPLACE.put("\\section{Ai}", "\\section{AI}");
TEXT_TO_REPLACE.put("\\\\url", "\\url");
TEXT_TO_REPLACE.put("\\\\texttt{", "\\texttt{");
TEXT_TO_REPLACE.put("$\\\\leq$", "$\\leq$");
TEXT_TO_REPLACE.put("$\\\\geq$", "$\\geq$");
TEXT_TO_REPLACE.put("$\\\\neq$", "$\\neq$");
TEXT_TO_REPLACE.put("\\\\frac{", "\\frac{");
TEXT_TO_REPLACE.put("\\\\exp(", "\\exp(");
TEXT_TO_REPLACE.put("\\\\tanh", "\\tanh");
}
/**
* For every package with package-info.java comments, a string containing its comments
* with @chapter annotation.
*/
private static final Map<String, String> CHAPTER_PACKAGE_INFOS = new HashMap<String, String>();
/**
* For every package with package-info.java comments, a string containing its comments
* without any specific annotations (or with @section annotations).
*/
private static final Map<String, String> SECTION_PACKAGE_INFOS = new HashMap<String, String>();
/** The Section that we're currently writing in (per chapter) */
private static String[] currentSections = new String[CHAPTER_NAMES.length];
/**
* Main method
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws ClassNotFoundException
*/
public static void generateTex() throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException
{
// First we'll read the XML file we generated
final File inputFile = new File("out/xml/jel.xml");
final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
final Document doc = dBuilder.parse(inputFile);
final Element root = doc.getDocumentElement();
final List<ClassTreeNode> rootPackages = new ArrayList<ClassTreeNode>();
final List<Node> packageInfoNodes = xmlChildrenForName(root, "jelpackage");
for (final Node packageInfoNode : packageInfoNodes)
{
final Node commentNode = xmlChildForName(packageInfoNode, "comment");
if (commentNode != null)
{
final String type = packageInfoNode.getAttributes().getNamedItem("type").getTextContent();
final Node descriptionNode = xmlChildForName(commentNode, "description");
final List<String> sectionComments = new ArrayList<String>();
final List<String> chapterComments = new ArrayList<String>();
if (descriptionNode != null)
sectionComments.add(descriptionNode.getTextContent());
final List<Node> attributeNodes = xmlChildrenForName(commentNode, "attribute");
for (final Node attributeNode : attributeNodes)
{
final String attributeName = attributeNode.getAttributes().getNamedItem("name").getTextContent();
final String attributeDescription = xmlChildForName(attributeNode, "description").getTextContent();
if (attributeName.equals("@chapter"))
chapterComments.add(attributeDescription);
else if (attributeName.equals("@section"))
sectionComments.add(attributeDescription);
}
SECTION_PACKAGE_INFOS.put(type, StringRoutines.join("\n\n", sectionComments));
CHAPTER_PACKAGE_INFOS.put(type, StringRoutines.join("\n\n", chapterComments));
}
}
final List<Node> classNodes = xmlChildrenForName(root, "jelclass");
for (int i = 0; i < classNodes.size(); ++i)
{
final Node child = classNodes.get(i);
if (hasAnnotation(child, "Hide") || hasAnnotation(child, "ImpliedRule"))
continue;
final NamedNodeMap attributes = child.getAttributes();
final String packageStr = attributes.getNamedItem("package").getTextContent();
String type = attributes.getNamedItem("type").getTextContent();
final String fullType = packageStr + "." + type.replaceAll(Pattern.quote("."), Matcher.quoteReplacement("$"));
final Class<?> clazz = Class.forName(fullType);
if (!Ludeme.class.isAssignableFrom(clazz) && !MetadataItem.class.isAssignableFrom(clazz) && !clazz.isEnum())
continue; // We skip classes that are neither Ludemes nor enums
if ((clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) && !clazz.isEnum())
continue; // We skip interfaces and abstract classes
if (type.contains("."))
{
if (!clazz.isEnum())
{
System.out.println("Skipping inner class type: " + fullType);
continue;
}
else
{
// Need to get rid of outer class
final String[] typeSplit = type.split(Pattern.quote("."));
type = typeSplit[typeSplit.length - 1];
}
}
boolean grammarSymbolUsed = false;
final List<Symbol> grammarSymbols = grammar.symbolListFromClassName(type);
if (grammarSymbols != null)
{
for (final Symbol symbol : grammarSymbols)
{
if
(
symbol.usedInDescription()
||
symbol.usedInMetadata()
||
(clazz.isEnum() && symbol.usedInGrammar())
)
{
grammarSymbolUsed = true;
break;
}
}
}
if (!grammarSymbolUsed && !MetadataItem.class.isAssignableFrom(clazz))
{
System.out.println("Ignoring type not used in grammar: " + fullType);
continue;
}
final String[] subpackages = packageStr.split(Pattern.quote("."));
// Find matching package in our list of root packages
ClassTreeNode currentNode = null;
List<ClassTreeNode> currentPackages = rootPackages;
final List<String> fullTypeStrParts = new ArrayList<String>();
for (int j = 0; j < subpackages.length; ++j)
{
boolean foundPackage = false;
fullTypeStrParts.add(subpackages[j]);
for (final ClassTreeNode pckg : currentPackages)
{
if (subpackages[j].equals(pckg.name))
{
currentNode = pckg;
foundPackage = true;
break;
}
}
if (!foundPackage)
{
// Didn't find a match, so have to instantiate a new root package
currentNode = new ClassTreeNode(subpackages[j], true, StringRoutines.join(".", fullTypeStrParts), clazz.isEnum(), child);
currentPackages.add(currentNode);
}
currentPackages = currentNode.children;
}
// Create new node for this type
fullTypeStrParts.add(type);
currentPackages.add(new ClassTreeNode(type, false, attributes.getNamedItem("fulltype").getTextContent(), clazz.isEnum(), child));
}
// Try to nicely sort all packages; first classes in alphabetical order, then subpackages
sortPackages(rootPackages);
// Create StringBuilders in which to collect text for all our chapters
final StringBuilder[] chapterStrings = new StringBuilder[CHAPTER_FILENAMES.length];
for (int i = 0; i < chapterStrings.length; ++i)
{
chapterStrings[i] = new StringBuilder();
appendLine(chapterStrings[i], "\\chapter{" + CHAPTER_NAMES[i] + "} " + CHAPTER_LABELS[i]);
// Write package info for this chapter
String chapterPackageStr = null;
for (final String key : PACKAGE_TO_CHAPTER.keySet())
{
if (PACKAGE_TO_CHAPTER.get(key).intValue() == i)
{
chapterPackageStr = key;
break;
}
}
final String packageInfo = CHAPTER_PACKAGE_INFOS.get(chapterPackageStr);
if (packageInfo != null)
appendLine(chapterStrings[i], packageInfo);
}
// Process all our packages in a depth-first manner
for (final ClassTreeNode node : rootPackages)
{
process(node, chapterStrings);
}
// Postprocess all our full chapter strings to set up hyperlinks, fix type names,
// and replace other keywords that need replacing
for (int i = 0; i < chapterStrings.length; ++i)
{
final StringBuilder sb = chapterStrings[i];
while (true)
{
final int paramStartIdx = sb.indexOf("<TO_LINK:");
if (paramStartIdx < 0) // we're done with this chapter
break;
final int paramEndIdx = sb.indexOf(">", paramStartIdx);
String paramTypeStr = sb.substring(paramStartIdx, paramEndIdx);
paramTypeStr = paramTypeStr.substring("<TO_LINK:".length(), paramTypeStr.length());
if (paramTypeStr.endsWith("[]"))
paramTypeStr = paramTypeStr.substring(0, paramTypeStr.length() - "[]".length());
final String[] paramTypeStrSplit = paramTypeStr.split(Pattern.quote("."));
final String paramTypeText = typeString(StringRoutines.lowerCaseInitial(paramTypeStrSplit[paramTypeStrSplit.length - 1]));
final String labelToLink = TYPE_TO_LABEL.get(paramTypeStr);
final String replaceStr;
if (labelToLink == null)
{
// No hyperlink
replaceStr = paramTypeText;
System.out.println("no hyperlink for: " + paramTypeStr);
}
else
{
replaceStr = "\\hyperref[" + labelToLink + "]{" + paramTypeText + "}";
}
sb.replace(paramStartIdx, paramEndIdx + 1, replaceStr);
}
for (final String key : TEXT_TO_REPLACE.keySet())
{
while (true)
{
final int startIdx = sb.indexOf(key);
if (startIdx < 0) // we're done with this key in this chapter
break;
final int endIdx = startIdx + key.length();
sb.replace(startIdx, endIdx, TEXT_TO_REPLACE.get(key));
}
}
}
// Write all our chapter files
for (int i = 0; i < chapterStrings.length; ++i)
{
try (final PrintWriter writer = new PrintWriter(new File(CHAPTER_FILENAMES[i]), "UTF-8"))
{
writer.write(chapterStrings[i].toString());
}
}
// for (final ClassTreeNode p : rootPackages)
// {
// p.print(0);
// }
// Write our appendix with list of images
writeImageList();
// Write our appendix of known defines
writeKnownDefines();
// Write out appendix containing grammar
writeGrammar();
}
/**
* Processes the given node
* @param node
* @param chapterStrings
*/
private static void process(final ClassTreeNode node, final StringBuilder[] chapterStrings)
{
if (node.isPackage)
{
for (final ClassTreeNode child : node.children)
{
process(child, chapterStrings);
}
}
else
{
if (node.isEnum)
processEnumNode(node, chapterStrings);
else
processClassNode(node, chapterStrings);
}
}
/**
* Processes the given class node
* @param node
* @param chapterStrings
*/
private static void processClassNode(final ClassTreeNode node, final StringBuilder[] chapterStrings)
{
// First figure out index of chapter in which we should write for this node
int chapter = -1;
String chapterPackages = node.fullType;
while (chapter < 0)
{
if (PACKAGE_TO_CHAPTER.containsKey(chapterPackages))
chapter = PACKAGE_TO_CHAPTER.get(chapterPackages).intValue();
else
chapterPackages = chapterPackages.substring(0, chapterPackages.lastIndexOf("."));
}
final StringBuilder sb = chapterStrings[chapter];
// Section headers will be based on what we didn't use for identifying chapter
final String sectionHeader = sectionHeader(chapterPackages + ".", node.fullType, chapter);
if (!sectionHeader.equals(currentSections[chapter]))
{
// We need to start writing a new section
currentSections[chapter] = sectionHeader;
final String packageStr = node.fullType.substring(0, node.fullType.length() - node.name.length() - 1);
final String packageInfo = SECTION_PACKAGE_INFOS.get(packageStr);
final String secLabelStr;
if (packageStr.contains(".") && !PACKAGE_TO_CHAPTER.containsKey(packageStr))
secLabelStr = packageStr;
else
secLabelStr = node.fullType + "." + node.name;
// System.out.println();
// System.out.println("node.fullType = " + node.fullType);
// System.out.println("node.name = " + node.name);
// System.out.println("packageStr = " + packageStr);
// System.out.println("sectionHeader = " + sectionHeader);
// System.out.println("secLabelStr = " + secLabelStr);
// System.out.println("chapter = " + chapter);
// System.out.println();
appendLine(sb, "");
//ruledLine(sb, 2);
appendLine(sb, "\\newpage");
appendLine(sb, "\\section{" + sectionHeader + "} \\label{Sec:" + secLabelStr + "}");
// Insert package info
if (packageInfo != null)
appendLine(sb, SECTION_PACKAGE_INFOS.get(packageStr));
else
System.err.println("null package info for: " + packageStr);
}
ruledLine(sb, 0.5);
//appendLine(sb, "\\newpage");
// Start a new subsection for specific ludeme
final String ludemeName = StringRoutines.lowerCaseInitial(node.name);
String subsectionHeader = ludemeName;
String alias = null;
String unformattedAlias = null;
// Check if we should modify subsection header due to @Alias annotation
if (hasAnnotation(node.xmlNode, "Alias"))
{
final Node annotationsNode = xmlChildForName(node.xmlNode, "annotations");
if (annotationsNode != null)
{
final List<Node> annotationNodes = xmlChildrenForName(annotationsNode, "annotation");
for (final Node annotationNode : annotationNodes)
{
final String annotationType = annotationNode.getAttributes().getNamedItem("type").getTextContent();
if (annotationType.equals("Alias"))
{
final Node valuesNode = xmlChildForName(annotationNode, "values");
final Node valueNode = xmlChildForName(valuesNode, "value");
alias = valueNode.getAttributes().getNamedItem("value").getTextContent();
unformattedAlias = alias;
alias = "$" + alias + "$";
alias = alias.replaceAll(Pattern.quote("%"), Matcher.quoteReplacement("\\%"));
alias = alias.replaceAll(Pattern.quote("^"), Matcher.quoteReplacement("\\wedge{}"));
subsectionHeader = "\\texorpdfstring{" + alias + "}{} (" + ludemeName + ")";
break;
}
}
}
}
appendLine(sb, "");
appendLine(sb, "\\subsection{" + subsectionHeader + "} \\label{Subsec:" + node.fullType + "}");
TYPE_TO_LABEL.put(node.fullType, "Subsec:" + node.fullType);
// First write the comments on top of class
final Node classCommentNode = xmlChildForName(node.xmlNode, "comment");
if (classCommentNode != null)
{
final Node descriptionNode = xmlChildForName(classCommentNode, "description");
if (descriptionNode != null)
{
if (descriptionNode.getTextContent().charAt(descriptionNode.getTextContent().length() - 1) != '.')
System.err.println("WARNING: comment with no full stop for the description of " + ludemeName);
appendLine(sb, descriptionNode.getTextContent());
}
}
// Add a separating line before "Format" box
// sb.append("\n\\phantom{}\n\n");
// Write the constructors
final Node methodsNode = xmlChildForName(node.xmlNode, "methods");
final List<Node> constructors = xmlChildrenForName(methodsNode, "constructor");
// also add public static create() methods to the constructors
final List<Node> createMethods = xmlChildrenForName(methodsNode, "method");
for (final Node methodNode : createMethods)
{
final Node staticAttribute = methodNode.getAttributes().getNamedItem("static");
if
(
staticAttribute != null &&
staticAttribute.getTextContent().equals("true") &&
methodNode.getAttributes().getNamedItem("visibility").getTextContent().equals("public") &&
methodNode.getAttributes().getNamedItem("name").getTextContent().equals("construct")
)
{
constructors.add(methodNode);
}
}
// Remove constructors with @Hide annotations
constructors.removeIf((final Node ctor) -> { return hasAnnotation(ctor, "Hide"); });
// Remove non-public constructors
constructors.removeIf((final Node ctor) ->
{
return !ctor.getAttributes().getNamedItem("visibility").getTextContent().equals("public");
});
if (constructors.size() >= 1)
{
appendLine(sb, "\\vspace{-1mm}");
appendLine(sb, "\\subsubsection*{Format}");
}
// This will collect examples over all constructors
final List<Node> exampleDescriptionNodes = new ArrayList<Node>();
for (int ctorIdx = 0; ctorIdx < constructors.size(); ++ctorIdx)
{
final Node ctor = constructors.get(ctorIdx);
appendLine(sb, "\\begin{formatbox}");
if (constructors.size() > 1)
{
// Need to add constructor-level javadoc
final Node commentNode = xmlChildForName(ctor, "comment");
if (commentNode != null)
{
final Node descriptionNode = xmlChildForName(commentNode, "description");
if (descriptionNode != null)
{
final String description = descriptionNode.getTextContent();
if (description.length() > 0)
appendLine(sb, description + "\n\n\\vspace{.2cm}\n");
else
System.err.println("WARNING: No Javadoc comment for " + (ctorIdx + 1) + "th constructor of " + node.fullType);
if (description.toLowerCase().contains("constructor"))
System.err.println("WARNING: Javadoc comment for " + (ctorIdx + 1) + "th constructor of " + node.fullType + " uses the word Constructor!");
}
else
{
System.err.println("WARNING: No Javadoc comment for " + (ctorIdx + 1) + "th constructor of " + node.fullType);
}
}
else
{
System.err.println("WARNING: No Javadoc comment for " + (ctorIdx + 1) + "th constructor of " + node.fullType);
}
}
appendLine(sb, "\\noindent\\begin{minipage}{\\textwidth}");
final StringBuilder ctorSb = new StringBuilder();
appendLine(sb, "\\begin{ttquote}");
//appendLine(sb, "\\noindent");
appendLine(sb, "\\hspace{-7mm}");
if (alias != null)
ctorSb.append("(" + alias + "");
else
ctorSb.append("(" + ludemeName + "");
final Node paramsNode = xmlChildForName(ctor, "params");
final List<String> paramSymbols = new ArrayList<String>();
final TIntArrayList singleValueEnumParamIndices = new TIntArrayList();
if (paramsNode != null)
{
final List<Node> paramNodes = xmlChildrenForName(paramsNode, "param");
boolean orSequence = false;
boolean or2Sequence = false;
for (int paramNodeIdx = 0; paramNodeIdx < paramNodes.size(); ++paramNodeIdx)
{
final Node paramNode = paramNodes.get(paramNodeIdx);
// Figure out how to write this param
final String paramName = paramNode.getAttributes().getNamedItem("name").getTextContent();
String paramFullType = paramNode.getAttributes().getNamedItem("fulltype").getTextContent();
boolean named = false;
boolean optional = false;
int numArrayDims = 0;
boolean startNewOrSequence = false;
boolean endPreviousOrSequence = (orSequence || or2Sequence);
while (paramFullType.endsWith("[]"))
{
paramFullType = paramFullType.substring(0, paramFullType.length() - "[]".length());
numArrayDims += 1;
}
final Node annotationsNode = xmlChildForName(paramNode, "annotations");
if (annotationsNode != null)
{
final List<Node> annotationNodes = xmlChildrenForName(annotationsNode, "annotation");
for (final Node annotationNode : annotationNodes)
{
final String annotationType = annotationNode.getAttributes().getNamedItem("type").getTextContent();
if (annotationType.equals("Name"))
{
named = true;
}
else if (annotationType.equals("Opt"))
{
optional = true;
}
else if (annotationType.equals("Or"))
{
if (orSequence)
endPreviousOrSequence = false;
else
startNewOrSequence = true;
orSequence = true;
or2Sequence = false;
}
else if (annotationType.equals("Or2"))
{
if (or2Sequence)
endPreviousOrSequence = false;
else
startNewOrSequence = true;
orSequence = false;
or2Sequence = true;
}
}
}
if (endPreviousOrSequence)
{
orSequence = false;
or2Sequence = false;
ctorSb.append(")");
}
// Write this param
ctorSb.append(" ");
if (startNewOrSequence)
ctorSb.append("(");
else if (orSequence || or2Sequence)
ctorSb.append(" | ");
final StringBuilder paramSymbolSb = new StringBuilder();
if (optional)
paramSymbolSb.append("[");
if (named)
paramSymbolSb.append(StringRoutines.lowerCaseInitial(paramName) + ":");
for (int i = 0; i < numArrayDims; ++i)
{
paramSymbolSb.append("\\{");
}
try
{
final Class<?> paramClass = Class.forName(paramFullType);
if (Enum.class.isAssignableFrom(paramClass))
{
if (paramClass.getEnumConstants().length == 1)
{
paramSymbolSb.append(paramClass.getEnumConstants()[0].toString());
singleValueEnumParamIndices.add(paramNodeIdx);
}
else
{
paramSymbolSb.append("<TO_LINK:" + paramFullType + ">");
}
}
else
{
paramSymbolSb.append("<TO_LINK:" + paramFullType + ">");
}
}
catch (final ClassNotFoundException e)
{
e.printStackTrace();
}
for (int i = 0; i < numArrayDims; ++i)
{
paramSymbolSb.append("\\}");
}
if (optional)
paramSymbolSb.append("]");
paramSymbols.add(paramSymbolSb.toString());
ctorSb.append(paramSymbolSb);
}
if (orSequence || or2Sequence) // close final or sequence
ctorSb.append(")");
}
ctorSb.append(")");
appendLine(sb, ctorSb.toString());
appendLine(sb, "\\end{ttquote}");
if (paramSymbols.size() > 0)
appendLine(sb, "\\vspace{\\parskip}");
appendLine(sb, "\\end{minipage}");
if (paramSymbols.size() - singleValueEnumParamIndices.size() > 0)
{
// Add explanations of all the params
appendLine(sb, "\\noindent where:");
appendLine(sb, "\\begin{itemize}");
final List<Node> paramNodes = xmlChildrenForName(paramsNode, "param");
for (int paramNodeIdx = 0; paramNodeIdx < paramNodes.size(); ++paramNodeIdx)
{
if (singleValueEnumParamIndices.contains(paramNodeIdx))
{
// Skip this param, it's a single-value enum
continue;
}
final Node paramNode = paramNodes.get(paramNodeIdx);
final Node commentNode = paramNode.getAttributes().getNamedItem("comment");
if (commentNode == null)
System.err.println("WARNING: No Javadoc comment for " + (paramNodeIdx + 1) + "th param of " + (ctorIdx + 1) + "th constructor of " + node.fullType);
else if (StringRoutines.cleanWhitespace(commentNode.getTextContent()).equals(""))
System.err.println("WARNING: Empty Javadoc comment for " + (paramNodeIdx + 1) + "th param of " + (ctorIdx + 1) + "th constructor of " + node.fullType);
else if (commentNode.getTextContent().charAt(commentNode.getTextContent().length() - 1) != '.')
System.err.println("WARNING: comment with no full stop for " + (paramNodeIdx + 1)
+ "th param of " + (ctorIdx + 1) + "th constructor of " + node.fullType);
final String paramDescription = commentNode != null ? commentNode.getTextContent() : "";
appendLine(sb, "\\item \\texttt{" + paramSymbols.get(paramNodeIdx) + "}: " + paramDescription);
final int openSquareBracketIdx = paramDescription.indexOf("[");
if (openSquareBracketIdx >= 0)
{
final int closingSquareBracketIdx = StringRoutines.matchingBracketAt(paramDescription, openSquareBracketIdx);
if (closingSquareBracketIdx < 0)
{
System.err.println("WARNING: No closing square bracket in " + (paramNodeIdx + 1) + "th param of " + (ctorIdx + 1) + "th constructor of " + node.fullType);
}
}
}
appendLine(sb, "\\end{itemize}");
}
final Node ctorCommentNode = xmlChildForName(ctor, "comment");
if (ctorCommentNode != null)
{
final List<Node> attributes = xmlChildrenForName(ctorCommentNode, "attribute");
// Collect constructor-specific examples
boolean foundExample = false;
for (final Node attribute : attributes)
{
if (attribute.getAttributes().getNamedItem("name").getTextContent().equals("@example"))
{
final Node descriptionNode = xmlChildForName(attribute, "description");
exampleDescriptionNodes.add(descriptionNode);
foundExample = true;
}
}
if (!foundExample)
System.err.println("WARNING: Found no example for one of the constructors of ludeme: " + node.fullType);
// We don't want to support constructor-specific remarks anymore
for (final Node attribute : attributes)
{
if (attribute.getAttributes().getNamedItem("name").getTextContent().equals("@remarks"))
System.err.println("WARNING: Found constructor-specific remark in ludeme: " + ludemeName);
}
}
appendLine(sb, "\\vspace{.2cm}");
appendLine(sb, "\\end{formatbox}");
if (ctorIdx + 1 < constructors.size())
appendLine(sb, "\\phantom{}");
appendLine(sb, "");
}
// Collect nodes with remarks to print here
final List<Node> remarkNodes = new ArrayList<Node>();
// And same for images
final List<Node> imageNodes = new ArrayList<Node>();
if (classCommentNode != null)
{
final List<Node> attributes = xmlChildrenForName(classCommentNode, "attribute");
// Collect class-wide examples
for (final Node attribute : attributes)
{
if (attribute.getAttributes().getNamedItem("name").getTextContent().equals("@example"))
{
final Node descriptionNode = xmlChildForName(attribute, "description");
exampleDescriptionNodes.add(descriptionNode);
}
}
// Collect remarks
for (final Node attribute : attributes)
{
if (attribute.getAttributes().getNamedItem("name").getTextContent().equals("@remarks"))
{
final Node descriptionNode = xmlChildForName(attribute, "description");
if (descriptionNode.getTextContent().charAt(descriptionNode.getTextContent().length() - 1) != '.')
System.err.println("WARNING: comment with no full stop for the remarks of " + ludemeName);
remarkNodes.add(descriptionNode);
}
}
// Collect images
for (final Node attribute : attributes)
{
if (attribute.getAttributes().getNamedItem("name").getTextContent().equals("@image"))
{
final Node descriptionNode = xmlChildForName(attribute, "description");
imageNodes.add(descriptionNode);
}
}
}
if (exampleDescriptionNodes.size() > 0)
{
appendLine(sb, "\\vspace{-2mm}");
if (exampleDescriptionNodes.size() == 1)
appendLine(sb, "\\subsubsection*{Example}");
else
appendLine(sb, "\\subsubsection*{Examples}");
appendLine(sb, "\\begin{formatbox}");
appendLine(sb, "\\noindent\\begin{minipage}{\\textwidth}");
for (final Node exampleNode : exampleDescriptionNodes)
{
final Report report = new Report();
final Token token = new Token(exampleNode.getTextContent(), report);
String exampleCode = token.toString();
// Try to compile our example code
Object compiledObject = null;
try
{
final Description description = new Description(exampleCode);
final String className = node.fullType;
final String symbolName;
if (unformattedAlias == null)
{
final String[] classNameSplit = className.split(Pattern.quote("."));
symbolName = StringRoutines.lowerCaseInitial(classNameSplit[classNameSplit.length - 1]);
}
else
{
symbolName = unformattedAlias;
}
//Expander.expand(description, new UserSelections(new ArrayList<String>()), report, false);
Parser.expandAndParse
(
description,
new UserSelections(new ArrayList<String>()),
report,
true, // allow examples
false
);
compiledObject = compiler.Compiler.compileObject(description.expanded(), symbolName, className, report);
if (report.isWarning())
{
System.err.println("Encountered warnings compiling example code:");
System.err.println(exampleCode);
System.err.println();
for (final String warning : report.warnings())
{
System.err.println(warning);
}
}
if (report.isError())
{
System.err.println("Encountered errors compiling example code:");
System.err.println(exampleCode);
System.err.println();
for (final String error : report.errors())
{
System.err.println(error);
}
}
//compiledObject = compiler.Compiler.compileObject(exampleCode, node.fullType);
}
catch (final Exception e)
{
// Do nothing
}
if (exampleCode.endsWith("\n"))
exampleCode = exampleCode.substring(0, exampleCode.lastIndexOf('\n'));
if (compiledObject == null)
{
System.err.println("Failed to compile example code in " + ludemeName);
System.err.println("Expected type = " + node.fullType);
System.err.println("Example code: \n" + exampleCode);
System.err.println("exampleNode.getTextContent() = " + exampleNode.getTextContent());
}
appendLine(sb, "\\begin{verbatim}");
// TO PRINT ALL THE EXAMPLES UNCOMMENT THAT.
// System.out.println(exampleNode.getTextContent() + "\n");
appendLine(sb, exampleCode);
appendLine(sb, "\\end{verbatim}");
}
appendLine(sb, "\\end{minipage}");
if (exampleDescriptionNodes.size() > 1)
appendLine(sb, "\\vspace{.2cm}");
else
appendLine(sb, "\\vspace{.001cm}");
appendLine(sb, "\\end{formatbox}");
appendLine(sb, "");
}
for (final Node remarksNode : remarkNodes)
{
appendLine(sb, "");
appendLine(sb, "\\vspace{-2mm}");
appendLine(sb, "\\subsubsection*{Remarks}");
appendLine(sb, remarksNode.getTextContent());
}
if (imageNodes.size() > 0)
{
appendLine(sb, "");
appendLine(sb, "\\subsection*{Images}");
for (final Node imageNode : imageNodes)
{
final String contents = imageNode.getTextContent();
final int startIdxFilepath = contents.indexOf("IMAGE=");
final int startIdxCaption = contents.indexOf("CAPTION=");
final int startIdxLabel = contents.indexOf("LABEL=");
if (startIdxFilepath < 0)
{
System.err.println("WARNING: Image filepath not found for image in ludeme: " + node.fullType);
continue;
}
if (startIdxCaption < 0)
{
System.err.println("WARNING: Image caption not found for image in ludeme: " + node.fullType);
continue;
}
if (startIdxLabel < startIdxCaption || startIdxCaption < startIdxFilepath)
{
System.err.println("WARNING: Ignoring image for ludeme: " + node.fullType + ". We require file first, then caption, then (optionally) label.");
continue;
}
appendLine(sb, "\\begin{figure} [H]");
appendLine(sb, "\\centering");
final int endIdxFilepath;
if (startIdxLabel >= 0)
endIdxFilepath = Math.min(startIdxCaption, startIdxLabel);
else
endIdxFilepath = startIdxCaption;
appendLine(sb, "\\includegraphics[max height=6cm,max width=\\textwidth]{" + contents.substring(startIdxFilepath + "IMAGE=".length(), endIdxFilepath).trim() + "}");
final int endIdxCaption = (startIdxLabel >= 0) ? startIdxLabel : contents.length();
appendLine(sb, "\\caption{" + contents.substring(startIdxCaption + "CAPTION=".length(), endIdxCaption).trim() + "}");
if (startIdxLabel >= 0)
appendLine(sb, "\\label{" + contents.substring(startIdxLabel + "LABEL=".length(), contents.length()).trim() + "}");
appendLine(sb, "\\end{figure}");
}
}
// if (exampleDescriptionNodes.size() > 0 || remarkNodes.size() > 0)
// ruledLine(sb);
}
static void ruledLine(final StringBuilder sb, final double width)
{
appendLine(sb, "");
appendLine(sb, "\\vskip10pt");
appendLine(sb, "\\noindent\\rule{\\textwidth}{" + width + "pt}");
appendLine(sb, "\\vskip0pt");
appendLine(sb, "\\vspace{-2mm}");
}
/**
* Processes the given enum node
* @param node
* @param chapterStrings
*/
private static void processEnumNode(final ClassTreeNode node, final StringBuilder[] chapterStrings)
{
// First figure out index of chapter in which we should write for this node
int chapter = -1;
String chapterPackages = node.fullType;
while (chapter < 0)
{
if (PACKAGE_TO_CHAPTER.containsKey(chapterPackages))
chapter = PACKAGE_TO_CHAPTER.get(chapterPackages).intValue();
else
chapterPackages = chapterPackages.substring(0, chapterPackages.lastIndexOf("."));
}
final StringBuilder sb = chapterStrings[chapter];
// Section headers will be based on what we didn't use for identifying chapter
final String sectionHeader = sectionHeader(chapterPackages + ".", node.fullType, chapter);
final String currentSection = currentSections[chapter];
if (!sectionHeader.equals(currentSection))
{
// We need to start writing a new section
currentSections[chapter] = sectionHeader;
appendLine(sb, "");
ruledLine(sb, 0.5);
//appendLine(sb, "\\newpage");
final String packageStr = node.fullType.substring(0, node.fullType.length() - node.name.length() - 1);
final String secLabelStr;
if (packageStr.contains(".") && !PACKAGE_TO_CHAPTER.containsKey(packageStr))
secLabelStr = packageStr;
else
secLabelStr = node.fullType + "." + node.name;
appendLine(sb, "\\section{" + sectionHeader + "} \\label{Sec:" + secLabelStr + "}");
final String packageInfo = SECTION_PACKAGE_INFOS.get(packageStr);
// Insert package info
if (packageInfo != null)
appendLine(sb, SECTION_PACKAGE_INFOS.get(packageStr));
else
System.err.println("null package info for: " + packageStr);
}
// Start a new subsection for specific enum
final String ludemeName = StringRoutines.lowerCaseInitial(node.name);
appendLine(sb, "");
appendLine(sb, "\\subsection{" + ludemeName + "} \\label{Subsec:" + node.fullType + "}");
TYPE_TO_LABEL.put(node.fullType, "Subsec:" + node.fullType);
// First write the comments on top of class
final Node commentNode = xmlChildForName(node.xmlNode, "comment");
if (commentNode != null)
{
final Node descriptionNode = xmlChildForName(commentNode, "description");
if (descriptionNode != null)
appendLine(sb, descriptionNode.getTextContent());
}
// Write enum values
final Node enumerationNode = xmlChildForName(node.xmlNode, "enumeration");
appendLine(sb, "");
// appendLine(sb, "\\subsubsection*{Type values}");
// appendLine(sb, "\\vspace{-4mm}");
final List<Node> values = xmlChildrenForName(enumerationNode, "value");
if (!values.isEmpty())
{
appendLine(sb, "\\renewcommand{\\arraystretch}{1.3}");
appendLine(sb, "\\arrayrulecolor{white}");
appendLine(sb, "\\rowcolors{2}{gray!25}{gray!10}");
appendLine(sb, "\\begin{longtable}{@{}p{.2\\textwidth} | p{.76\\textwidth}@{}}");
appendLine(sb, "\\rowcolor{gray!50}");
appendLine(sb, "\\textbf{Value} & \\textbf{Description} \\\\");
for (final Node valueNode : values)
{
String valueName = valueNode.getAttributes().getNamedItem("name").getTextContent();
valueName = valueName.replaceAll(Pattern.quote("_"), Matcher.quoteReplacement("\\_")); // escape underscores
final Node descriptionNode = valueNode.getAttributes().getNamedItem("description");
final String description = (descriptionNode != null) ? descriptionNode.getTextContent() : null;
if (description == null)
System.err.println("WARNING: no javadoc for value " + valueName + " of enum: " + node.fullType);
else if (StringRoutines.cleanWhitespace(description).equals(""))
System.err.println("WARNING: empty javadoc for value " + valueName + " of enum: " + node.fullType);
if (description == null)
appendLine(sb, valueName + " & \\\\");
else
appendLine(sb, valueName + " & " + description + " \\\\");
}
appendLine(sb, "\\end{longtable}");
}
}
/**
* @param prefixToRemove Prefix from fullType that we'll remove before determining section header
* @param fullType
* @param chapter
* @return Section header for node with given full type in given chapter
*/
private static final String sectionHeader(final String prefixToRemove, final String fullType, final int chapter)
{
String sectionHeaderStr = fullType.replace(prefixToRemove, "");
final int lastDotIdx = sectionHeaderStr.lastIndexOf(".");
if (lastDotIdx >= 0)
sectionHeaderStr = sectionHeaderStr.substring(0, lastDotIdx);
final String[] sectionHeaderParts = sectionHeaderStr.split(Pattern.quote("."));
String sectionHeader = StringRoutines.join(" - ", StringRoutines.upperCaseInitialEach(sectionHeaderParts));
if (sectionHeader.length() == 0)
{
// We'll just reuse the chapter name as section header
sectionHeader = CHAPTER_NAMES[chapter];
}
return sectionHeader;
}
/**
* @param xmlNode
* @param name
* @return Child of given XML node with given name
*/
private static final Node xmlChildForName(final Node xmlNode, final String name)
{
final NodeList childNodes = xmlNode.getChildNodes();
for (int i = 0; i < childNodes.getLength(); ++i)
{
if (name.equals(childNodes.item(i).getNodeName()))
return childNodes.item(i);
}
return null;
}
/**
* @param xmlNode
* @param name
* @return Children of given XML node with given name
*/
private static final List<Node> xmlChildrenForName(final Node xmlNode, final String name)
{
final List<Node> ret = new ArrayList<Node>();
final NodeList childNodes = xmlNode.getChildNodes();
for (int i = 0; i < childNodes.getLength(); ++i)
{
if (name.equals(childNodes.item(i).getNodeName()))
ret.add(childNodes.item(i));
}
return ret;
}
/**
* @param type
* @return Generates a String for a given type, as it would also appear in grammar
*/
private static final String typeString(final String type)
{
final String str = StringRoutines.lowerCaseInitial(type);
if (str.equals("integer"))
return "int";
else if (str.equals("intFunction"))
return "<int>";
else if (str.equals("booleanFunction"))
return "<boolean>";
else if (str.equals("regionFunction"))
return "<region>";
return "<" + str + ">";
}
/**
* @param node
* @param type
* @return True if the given node contains an annotation of given type
*/
private static final boolean hasAnnotation(final Node node, final String type)
{
final Node annotationsNode = xmlChildForName(node, "annotations");
if (annotationsNode != null)
{
final List<Node> annotationNodes = xmlChildrenForName(annotationsNode, "annotation");
for (final Node annotationNode : annotationNodes)
{
final String annotationType = annotationNode.getAttributes().getNamedItem("type").getTextContent();
if (annotationType.equals(type))
return true;
}
}
return false;
}
/**
* Writes our appendix with list of images
*/
private static void writeImageList()
{
final String imageAppendixFilepath = "out/tex/AppendixAImageList.tex";
final StringBuilder sb = new StringBuilder();
// Write introductory part
appendLine(sb, "% WARNING: Do NOT manually modify this file! Instead modify writeImageList() in GenerateLudiiDocTex.java!");
appendLine(sb, "");
appendLine(sb, "\\chapter{Image List} \\label{Appendix:ImageList}");
appendLine(sb, "\\fancyhead[C]{\\leftmark}");
appendLine(sb, "");
appendLine(sb, "This Appendix lists the image files provided with the Ludii distribution.");
appendLine(sb, "These image names can be used in .lud files to associate particular images with named pieces "
+ "or board symbols.");
appendLine(sb, "For pieces, the app tries to find the image whose file name is closest to the defined name, e.g. "
+ "``QueenLeft'' will match the image file ``queen.svg''.");
appendLine(sb, "For board symbols, an exact name match is required.");
appendLine(sb, "");
appendLine(sb, "\\phantom{}");
appendLine(sb, "");
appendLine(sb, "\\noindent");
appendLine(sb, "Credits for images appear in the About dialog for games in which they are used.");
appendLine(sb, "");
appendLine(sb, "\\phantom{}");
appendLine(sb, "");
appendLine(sb, "\\noindent");
appendLine(sb, "Image list as of Ludii v" + Constants.LUDEME_VERSION + ".");
appendLine(sb, "");
appendLine(sb, "\\vspace{3mm}");
appendLine(sb, "\\noindent\\rule{\\textwidth}{2pt}");
appendLine(sb, "\\vspace{-6mm}");
appendLine(sb, "");
appendLine(sb, "\\begin{multicols}{2}");
final String[] svgs = SVGLoader.listSVGs();
String currSubsec = null;
for (final String svg : svgs)
{
final String[] svgSplit = svg.replaceAll(Pattern.quote("/svg/"), "").split(Pattern.quote("/"));
final String subsec = StringRoutines.join("/", Arrays.copyOf(svgSplit, svgSplit.length - 1));
if (!subsec.equals(currSubsec))
{
currSubsec = subsec;
appendLine(sb, "\\subsection*{" + subsec + "}");
appendLine(sb, "\\hspace{4mm}");
}
appendLine(sb, svgSplit[svgSplit.length - 1].replaceAll(Pattern.quote("_"), Matcher.quoteReplacement("\\_")));
appendLine(sb, "");
}
appendLine(sb, "\\end{multicols}");
try (final PrintWriter writer = new PrintWriter(new File(imageAppendixFilepath), "UTF-8"))
{
writer.write(sb.toString());
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
private static void writeKnownDefines()
{
final String definesAppendixFilepath = "out/tex/AppendixBKnownDefines.tex";
final StringBuilder sb = new StringBuilder();
// Write introductory part
appendLine(sb, "% WARNING: Do NOT manually modify this file! Instead modify writeKnownDefines() in "
+ "GenerateLudiiDocTex.java!");
appendLine(sb, "");
appendLine(sb, "\\chapter{Known Defines} \\label{Appendix:KnownDefines}");
appendLine(sb, "");
appendLine(sb, "This Appendix lists the known {\\tt define} structures provided with the Ludii distribution, "
+ "which are available for use by game authors. ");
appendLine(sb, "Known defines can be found in the ``def'' package area (or below) with file extension *.def.");
appendLine(sb, "See Chapter~\\ref{Chapter:Defines} for details on the {\\tt define} syntax.");
appendLine(sb, "");
appendLine(sb, "\\vspace{3mm}");
appendLine(sb, "\\noindent\\rule{\\textwidth}{2pt}");
appendLine(sb, "\\vspace{-7mm}");
appendLine(sb, "");
appendLine(sb, convertAllDefToTex("../Common/res/def"));
try (final PrintWriter writer = new PrintWriter(new File(definesAppendixFilepath), "UTF-8"))
{
writer.write(sb.toString());
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
private static void writeGrammar()
{
final String grammarAppendixFilepath = "out/tex/AppendixCLudiiGrammar.tex";
final StringBuilder sb = new StringBuilder();
// Write introductory part
appendLine(sb, "% WARNING: Do NOT manually modify this file! Instead modify writeGrammar() in "
+ "GenerateLudiiDocTex.java!");
appendLine(sb, "");
appendLine(sb, "\\chapter{Ludii Grammar} \\label{Appendix:LudiiGrammar}");
appendLine(sb, "This Appendix lists the complete Ludii grammar for the current Ludii version.");
appendLine(sb, "The Ludii grammar is generated automatically from the hierarchy of Java classes that implement "
+ "the ludemes described in this document, using the {\\it class grammar} approach described in "
+ "C. Browne ``A Class Grammar for General Games'', {\\it Computers and Games (CG 2016)}, "
+ "Springer, LNCS 10068, pp.~169--184.");
appendLine(sb, "");
appendLine(sb, "Ludii game descriptions (*.lud files) {\\it must} conform to this grammar, but note that "
+ "conformance does not guarantee compilation. ");
appendLine(sb, "Many factors can stop game descriptions from compiling, such as attempting to access a "
+ "component using an undefined name, attempting to modify board sites that do not exist, and so on.");
appendLine(sb, "");
appendLine(sb, "%====================================================================");
appendLine(sb, "");
appendLine(sb, "\\section{Compilation}");
appendLine(sb, "");
appendLine(sb, "The steps for compiling a game according to the grammar, from a given *.lud game description "
+ "to an executable Java {\\tt Game} object, are as follows:");
appendLine(sb, "");
appendLine(sb, "\\begin{enumerate}");
appendLine(sb, "");
appendLine(sb, "\\item {\\it Expand}: The {\\it raw} text *.lud game description is expanded according to "
+ "the metalanguage features described in Part~\\ref{Part:MetalanguageFeatures} "
+ "(defines, options, rulesets, ranges, constants, etc.) to give an {\\it expanded} text description "
+ "of the game with current options and rulesets instantiated.");
appendLine(sb, "");
appendLine(sb, "\\item {\\it Tokenise}: The expanded text description is then {\\it tokenised} into a "
+ "{\\it symbolic expression} in the form of a tree of simple tokens.");
appendLine(sb, "");
appendLine(sb, "\\item {\\it Parse}: The token tree is parsed according to the current Ludii grammar for "
+ "correctness.");
appendLine(sb, "");
appendLine(sb, "\\item {\\it Compile}: The names of tokens in the token tree are then matched with known "
+ "ludeme Java classes and these are compiled with the specified arguments, if possible, to give "
+ "a {\\tt Game} object.");
appendLine(sb, "");
appendLine(sb, "\\item {\\it Create}: The {\\tt Game} object calls its {\\tt create()} method to perform "
+ "relevant preparations, such as deciding on an appropriate {\tt State} type, allocating required "
+ "memory, initialising necessary variables, etc. ");
appendLine(sb, "");
appendLine(sb, "\\end{enumerate}");
appendLine(sb, "");
appendLine(sb, "%====================================================================");
appendLine(sb, "");
appendLine(sb, "%\\section{Error Handling}");
appendLine(sb, "");
appendLine(sb, "% TODO: Notes on error handling.");
appendLine(sb, "");
appendLine(sb, "%====================================================================");
appendLine(sb, "");
appendLine(sb, "\\section{Listing}");
appendLine(sb, "");
appendLine(sb, "\\vspace{-2mm}");
appendLine(sb, "");
appendLine(sb, "\\begingroup");
appendLine(sb, "\\obeylines");
appendLine(sb, "{\\tt \\small");
appendLine(sb, "\\begin{verbatim}");
appendLine(sb, "");
appendLine(sb, Grammar.grammar().toString());
appendLine(sb, "");
appendLine(sb, "\\end{verbatim}");
appendLine(sb, "}");
appendLine(sb, "\\endgroup");
try (final PrintWriter writer = new PrintWriter(new File(grammarAppendixFilepath), "UTF-8"))
{
writer.write(sb.toString());
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Converts all .def into .tex from the specified folder and below.
* @return
*/
private static String convertAllDefToTex(final String folderPath)
{
final StringBuilder sb = new StringBuilder();
// Get list of directories
final List<File> dirs = new ArrayList<File>();
final File folder = new File(folderPath);
dirs.add(folder);
for (int i = 0; i < dirs.size(); ++i)
{
final File dir = dirs.get(i);
for (final File file : dir.listFiles())
if (file.isDirectory())
dirs.add(file);
}
Collections.sort(dirs);
try
{
// Visit files in each directory
for (final File dir : dirs)
{
final String path = dir.getCanonicalPath().replaceAll(Pattern.quote("\\"), "/");
if (path.indexOf("/def/") != -1)
{
// Add this section header
final String name = path.substring(path.indexOf("def/"));
sb.append(texSection(name));
}
for (final File file : dir.listFiles())
if (!file.isDirectory())
convertDefToTex(file, sb);
}
}
catch (final IOException e)
{
e.printStackTrace();
}
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* Converts the specified .def file to .tex.
*/
private static void convertDefToTex(final File file, final StringBuilder sb)
{
if (!file.getPath().contains(".def"))
{
System.err.println("Bad file: " + file.getPath());
return;
}
// Read lines in
final List<String> lines = new ArrayList<String>();
try
(
final BufferedReader reader =
new BufferedReader
(
new InputStreamReader
(
new FileInputStream(file),
StandardCharsets.UTF_8
)
)
)
{
String line = reader.readLine();
while (line != null)
{
// Process line for .tex safety
line = line.replace("&", "\\&");
line = line.replace("_", "\\_");
lines.add(new String(line));
line = reader.readLine();
}
}
catch (final IOException e)
{
e.printStackTrace();
}
// Handle subsection title for this define
final String name = file.getName().substring(0, file.getName().length() - 4);
sb.append(texSubsection(name));
// Handle comments in description
final String comments = commentsFromLines(lines);
if (comments == "")
sb.append("\\phantom{}\n");
else
sb.append("\n" + comments + "\n");
// Handle examples
final List<String> examples = examplesFromLines(lines);
if (!examples.isEmpty())
sb.append(texExample(examples));
// Handle define
final String define = defineFromLines(lines);
sb.append(texDefine(define));
}
//-------------------------------------------------------------------------
private final static String commentsFromLines(final List<String> lines)
{
final StringBuilder sb = new StringBuilder();
int commentLinesAdded = 0;
for (final String line : lines)
{
final int c = line.indexOf("//");
if (c < 0)
break; // not a comment
if (line.contains("@example"))
break; // don't include examples in comments
if (commentLinesAdded > 0)
sb.append(" \\\\ ");
sb.append(line.substring(c + 2).trim() + " ");
commentLinesAdded++;
}
final String comments = sb.toString().replace("#", "\\#");
return comments;
}
//-------------------------------------------------------------------------
private final static List<String> examplesFromLines(final List<String> lines)
{
final List<String> examples = new ArrayList<String>();
for (final String line : lines)
{
final int c = line.indexOf("@example");
if (c < 0)
continue; // not an example
examples.add(line.substring(c + 8).trim());
}
return examples;
}
//-------------------------------------------------------------------------
private final static String defineFromLines(final List<String> lines)
{
final StringBuilder sb = new StringBuilder();
boolean defineFound = false;
for (final String line : lines)
{
final int c = line.indexOf("(define ");
if (c >= 0)
defineFound = true;
if (defineFound)
sb.append(line + "\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
private static String texThinLine()
{
final StringBuilder sb = new StringBuilder();
sb.append("\n" + "\\vspace{-1mm}\n");
sb.append("\\noindent\\rule{\\textwidth}{0.5pt}\n");
sb.append("\\vspace{-6mm}\n");
return sb.toString();
}
private static String texThickLine()
{
final StringBuilder sb = new StringBuilder();
sb.append("\n" + "\\vspace{3mm}\n");
sb.append("\\noindent\\rule{\\textwidth}{2pt}\n");
sb.append("\\vspace{-7mm}\n");
return sb.toString();
}
private static String texSection(final String title)
{
final StringBuilder sb = new StringBuilder();
sb.append("\n" + "%==========================================================\n");
sb.append(texThickLine());
sb.append("\n" + "\\section{" + title + "}\n");
//sb.append("\n" + "%---------------------------------\n");
return sb.toString();
}
private static String texSubsection(final String name)
{
final StringBuilder sb = new StringBuilder();
sb.append("\n" + "%-----------------------------------------\n");
sb.append(texThinLine());
sb.append("\n" + "\\subsection{``" + name + "''}");
sb.append(" \\label{known:" + name + "}\n");
return sb.toString();
}
private static String texExample(final List<String> examples)
{
final StringBuilder sb = new StringBuilder();
if (examples.size() < 2)
sb.append("\n% Example\n");
else
sb.append("\n% Examples\n");
sb.append("\\vspace{-1mm}\n");
sb.append("\\subsubsection*{Example}\n");
sb.append("\\vspace{-3mm}\n");
sb.append("\n" + "\\begin{formatbox}\n");
sb.append("\\begin{verbatim}\n");
for (final String example : examples)
sb.append(example + "\n");
sb.append("\\end{verbatim}\n");
sb.append("\\vspace{-1mm}\n");
sb.append("\\end{formatbox}\n");
sb.append("\\vspace{-2mm}\n");
return sb.toString();
}
private static String texDefine(final String define)
{
final StringBuilder sb = new StringBuilder();
sb.append("\n% Define\n");
sb.append("{\\tt\n");
sb.append("\\begin{verbatim}\n");
sb.append(define + "\n");
sb.append("\\end{verbatim}\n");
sb.append("}\n");
sb.append("\\vspace{-4mm}\n");
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* Appends given line to StringBuilder (+ newline character)
* @param sb
* @param line
*/
private static final void appendLine(final StringBuilder sb, final String line)
{
sb.append(line + "\n");
}
/**
* Makes sure all packages that are somewhere in the given list (including
* subpackages of these packages) are all nicely sorted: first classes,
* then subpackages, with each of those being sorted alphabetically.
* @param packages
*/
private static void sortPackages(final List<ClassTreeNode> packages)
{
packages.sort(new Comparator<ClassTreeNode>()
{
@Override
public int compare(final ClassTreeNode o1, final ClassTreeNode o2)
{
if (!o1.isPackage && o2.isPackage)
return -1;
if (o1.isPackage && !o2.isPackage)
return 1;
return o1.name.compareToIgnoreCase(o2.name);
}
});
for (final ClassTreeNode p : packages)
{
sortPackages(p.children);
}
}
/**
* Class for node in our tree of classes (and packages)
*
* @author Dennis Soemers
*/
private static class ClassTreeNode
{
/** Full package + type name */
public final String fullType;
/** Name of package or class */
public final String name;
/** True if we're a package, false if we're a class */
public boolean isPackage;
/** True if this is an enum (instead of a Ludeme class or package) */
public boolean isEnum;
/** The XML node */
public Node xmlNode;
/** List of child nodes (with subpackages and classes) */
public final List<ClassTreeNode> children = new ArrayList<ClassTreeNode>();
/**
* Constructor
* @param name
* @param isPackage
* @param fullType
* @param isEnum
* @param xmlNode
*/
public ClassTreeNode
(
final String name,
final boolean isPackage,
final String fullType,
final boolean isEnum,
final Node xmlNode
)
{
this.name = name;
this.isPackage = isPackage;
this.fullType = fullType;
this.isEnum = isEnum;
this.xmlNode = xmlNode;
}
// /**
// * Prints this package and all subpackages
// * @param numIndents
// */
// protected void print(final int numIndents)
// {
// final StringBuilder sb = new StringBuilder();
// for (int i = 0; i < numIndents; ++i)
// {
// sb.append("\t");
// }
// sb.append(name);
// System.out.println(sb);
//
// for (final ClassTreeNode child : children)
// {
// child.print(numIndents + 1);
// }
// }
@Override
public String toString()
{
return "[Node: " + fullType + "]";
}
}
}
| 66,269 | 32.019432 | 167 |
java
|
Ludii
|
Ludii-master/LudiiDocGen/src/xml/GenerateLudiiDocXML.java
|
package xml;
import java.io.File;
import java.io.IOException;
import java.util.regex.Pattern;
import main.StringRoutines;
/**
* Code to generate XML representation of Ludii's
* javadoc documentation.
*
* @author Dennis Soemers
*/
public class GenerateLudiiDocXML
{
/** Filepath for our doclet JAR file */
private static final String DOCLET_FILEPATH = "../LudiiDocGen/lib/jeldoclet.jar";
/** Filepath for directory where we want to write XML Javadoc output */
private static final String XML_OUT_DIR = "../LudiiDocGen/out/xml";
/** Classpath (with class files) */
private static final String CLASSPATH = StringRoutines.join
(
File.pathSeparator,
"../Common/bin",
"../Common/lib/Trove4j_ApacheCommonsRNG.jar",
"../Language/bin",
"../Core/lib/jfreesvg-3.4.jar"
);
/** Sourcepath (with source files) */
private static final String SOURCEPATH = "../Core/src";
/**
* Main method
* @throws IOException
* @throws InterruptedException
*/
public static void generateXML() throws InterruptedException, IOException
{
final String executableName;
if (new File("C:/Program Files/Java/jdk1.8.0_301/bin/javadoc.exe").exists())
{
// Hardcoding this filepath for Dennis' desktop because otherwise Eclipse
// uses the wrong javadoc (the one packaged with Eclipse, which is version 13
// and incompatible with our doclet)
executableName = "C:/Program Files/Java/jdk1.8.0_301/bin/javadoc";
}
else
{
executableName = "javadoc";
}
final String command =
StringRoutines.join
(
" ",
executableName,
"-doclet",
"com.jeldoclet.JELDoclet",
"-docletpath",
new File(DOCLET_FILEPATH).getCanonicalPath(),
"-d",
new File(XML_OUT_DIR).getCanonicalPath(),
"-classpath",
CLASSPATH,
"-sourcepath",
new File(SOURCEPATH).getCanonicalPath(),
"-subpackages",
"game:metadata",
"-public",
"-encoding",
"UTF-8"//,
//"-verbose"
);
// System.out.println("where javadoc:");
// new ProcessBuilder("where javadoc".split(Pattern.quote(" "))).inheritIO().start().waitFor();
System.out.println("Executing command: " + command);
new ProcessBuilder(command.split(Pattern.quote(" "))).inheritIO().start().waitFor();
}
}
| 2,264 | 24.738636 | 96 |
java
|
Ludii
|
Ludii-master/Manager/src/manager/Manager.java
|
package manager;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.rng.core.RandomProviderDefaultState;
import main.Constants;
import manager.ai.AIDetails;
import manager.network.DatabaseFunctionsPublic;
import manager.network.SettingsNetwork;
import manager.utils.SettingsManager;
import other.AI;
import other.move.Move;
import tournament.Tournament;
/**
* The Manager class provides the link between the logic (Core/Referee) and the playerDesktop.
* I handles all aspects of Ludii that are not specific to the PC environment, e.g. Graphics2D.
*
* @author Matthew.Stephenson and cambolbro and Eric.Piette
*/
public final class Manager
{
private PlayerInterface playerInterface;
private final DatabaseFunctionsPublic databaseFunctionsPublic = DatabaseFunctionsPublic.construct();
/** Referee object that controls play. */
private final Referee ref;
/** Selects AI, based on player's choices in the Settings menu. */
private final AIDetails[] aiSelected = new AIDetails[Constants.MAX_PLAYERS + 1];
/** Our current tournament */
private Tournament tournament;
/** Internal state of Context's RNG at the beginning of the game currently in the App. */
private RandomProviderDefaultState currGameStartRngState = null;
/** References to AIs for which we're visualising what they're thinking live. */
private List<AI> liveAIs = null;
/** lud filename for the last loaded game. */
private String savedLudName;
/** list of the undoneMoves when viewing previous game states. */
private List<Move> undoneMoves = new ArrayList<>();
private final SettingsManager settingsManager = new SettingsManager();
private final SettingsNetwork settingsNetwork = new SettingsNetwork();
private boolean webApp = false;
//-------------------------------------------------------------------------
public Manager(final PlayerInterface playerInterface)
{
setPlayerInterface(playerInterface);
ref = new Referee();
}
//-------------------------------------------------------------------------
public Referee ref()
{
return ref;
}
public AIDetails[] aiSelected()
{
return aiSelected;
}
public Tournament tournament()
{
return tournament;
}
//-------------------------------------------------------------------------
public void updateCurrentGameRngInternalState()
{
setCurrGameStartRngState((RandomProviderDefaultState) ref().context().rng().saveState());
}
public RandomProviderDefaultState currGameStartRngState()
{
return currGameStartRngState;
}
public void setCurrGameStartRngState(final RandomProviderDefaultState newCurrGameStartRngState)
{
currGameStartRngState = newCurrGameStartRngState;
}
//-------------------------------------------------------------------------
/**
* @return The AIs for which we're visualising the thought process live
*/
public List<AI> liveAIs()
{
return liveAIs;
}
/**
* Sets the AIs for which we're visualising the thought process live
*
* @param ais
*/
public void setLiveAIs(final List<AI> ais)
{
liveAIs = ais;
}
//-------------------------------------------------------------------------
public String savedLudName()
{
return savedLudName;
}
public void setSavedLudName(final String savedLudName)
{
this.savedLudName = savedLudName;
}
//-------------------------------------------------------------------------
public void setUndoneMoves(final List<Move> moves)
{
undoneMoves = moves;
}
public List<Move> undoneMoves()
{
return undoneMoves;
}
//-------------------------------------------------------------------------
public SettingsManager settingsManager()
{
return settingsManager;
}
//-------------------------------------------------------------------------
public SettingsNetwork settingsNetwork()
{
return settingsNetwork;
}
//-------------------------------------------------------------------------
public PlayerInterface getPlayerInterface()
{
return playerInterface;
}
public void setPlayerInterface(final PlayerInterface playerInterface)
{
this.playerInterface = playerInterface;
}
//-------------------------------------------------------------------------
public Tournament getTournament()
{
return tournament;
}
public void setTournament(final Tournament tournament)
{
this.tournament = tournament;
}
//-------------------------------------------------------------------------
public DatabaseFunctionsPublic databaseFunctionsPublic()
{
return databaseFunctionsPublic;
}
//-------------------------------------------------------------------------
public boolean isWebApp()
{
return webApp;
}
public void setWebApp(final boolean webPlayer)
{
webApp = webPlayer;
}
//-------------------------------------------------------------------------
public int moverToAgent()
{
return ref().context().state().playerToAgent(ref().context().state().mover());
}
public int playerToAgent(final int i)
{
return ref().context().state().playerToAgent(i);
}
//-------------------------------------------------------------------------
}
| 5,129 | 23.084507 | 101 |
java
|
Ludii
|
Ludii-master/Manager/src/manager/PlayerInterface.java
|
package manager;
import java.util.List;
import org.json.JSONObject;
import other.context.Context;
import other.move.Move;
/**
* Interface for specifying functions within the PlayerApp, which can be called from within the Manager project.
*
* @author Matthew.Stephenson
*/
public interface PlayerInterface
{
JSONObject getNameFromJar();
JSONObject getNameFromJson();
JSONObject getNameFromAiDef();
void loadGameFromName(final String name, final List<String> options, final boolean debug);
void addTextToStatusPanel(final String text);
void addTextToAnalysisPanel(final String text);
void selectAnalysisTab();
void repaint();
void reportForfeit(int playerForfeitNumber);
void reportTimeout(int playerForfeitNumber);
void reportDrawAgreed();
void updateFrameTitle(boolean alsoUpdateMenu);
void updateTabs(Context context);
void restartGame();
void repaintTimerForPlayer(int playerId);
void setTemporaryMessage(final String text);
void refreshNetworkDialog();
void postMoveUpdates(Move move, boolean noAnimation);
}
| 1,039 | 27.888889 | 112 |
java
|
Ludii
|
Ludii-master/Manager/src/manager/Referee.java
|
package manager;
import java.awt.EventQueue;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import org.json.JSONObject;
import game.Game;
import game.rules.play.moves.Moves;
import game.types.play.ModeType;
import main.Constants;
import manager.ai.AIDetails;
import manager.ai.AIUtil;
import other.AI;
import other.context.Context;
import other.model.Model;
import other.model.Model.AgentMoveCallback;
import other.model.Model.MoveMessageCallback;
import other.move.Move;
import other.trial.Trial;
import utils.AIUtils;
import utils.DoNothingAI;
/**
* The Referee class coordinates all aspects of game play including self-play
* tournaments.
*
* @author cambolbro and Eric.Piette and Matthew.Stephenson
*/
public class Referee
{
//---------------------------------------------------------
/** The game instance. */
Context context;
/** True if human input is allowed to cause a new step to start */
final AtomicBoolean allowHumanBasedStepStart = new AtomicBoolean(true);
/** Set to true if we want a new nextMove(false) call */
final AtomicBoolean wantNextMoveCall = new AtomicBoolean(false);
/** Update visualisation of what AI is thinking every x milliseconds */
public static final int AI_VIS_UPDATE_TIME = 40;
/** Thread for checking model to make moves. */
private RefereeStepThread moveThread = null;
//-------------------------------------------------------------------------
/**
* @return Current context
*/
public Context context()
{
return context;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return The current game object.
*/
public Referee setGame(final Manager manager, final Game game)
{
context = new Context(game, new Trial(game));
manager.updateCurrentGameRngInternalState();
return this;
}
//-------------------------------------------------------------------------
/**
* Apply a saved move to the game. Used only when viewing prior states. No
* validity checks.
*/
public void makeSavedMoves(final Manager manager, final List<Move> moves)
{
Move move = null;
for (int i = context.trial().numMoves(); i < moves.size(); i++)
{
move = moves.get(i);
preMoveApplication(manager, move);
context.game().apply(context, move);
}
if (move != null)
postMoveApplication(manager, move, true);
}
//-------------------------------------------------------------------------
/**
* Apply human move to game.
*/
public synchronized void applyHumanMoveToGame(final Manager manager, final Move move)
{
final Model model = context.model();
if (model.isReady())
if (!nextMove(manager, true))
return;
final boolean autoPass = move.isPass() && context.game().moves(context).moves().isEmpty();
if (!autoPass)
{
while (model.isReady() || !model.isRunning())
{
try
{
Thread.sleep(10L);
}
catch (final InterruptedException e)
{
e.printStackTrace();
}
}
}
// Wrap the code that we want to run in a Runnable.
final Runnable runnable = () ->
{
preMoveApplication(manager, move);
final Move appliedMove = model.applyHumanMove(context(), move, move.mover());
if (model.movesPerPlayer() != null)
{
// We might be waiting for the moves of other players.
final ArrayList<Integer> playerIdsWaitingFor = new ArrayList<>();
for (int i = 1; i < model.movesPerPlayer().length; i++)
{
final Move m = model.movesPerPlayer()[i];
if (m == null)
playerIdsWaitingFor.add(Integer.valueOf(i));
}
if (playerIdsWaitingFor.size() > 0)
{
String tempMessage = "Waiting for moves from";
for (final int index : playerIdsWaitingFor)
tempMessage += " P" + index + " and";
tempMessage = tempMessage.substring(0, tempMessage.length()-4);
tempMessage += ".\n";
manager.getPlayerInterface().addTextToStatusPanel(tempMessage);
}
}
if (appliedMove != null)
postMoveApplication(manager, appliedMove, false);
};
runnable.run();
}
//-------------------------------------------------------------------------
/**
* Apply remote move that we received from the network.
*/
public synchronized boolean applyNetworkMoveToGame(final Manager manager, final Move move)
{
// Check that the model is ready to apply this move.
final Model model = context.model();
if (model.isReady() && !nextMove(manager, true))
{
System.out.println("Waiting on the model: " + move);
return false;
}
// Get the real move from the set of legal moves that matches the fetched move information.
final Move realMoveToApply = context.game().getMatchingLegalMove(context, move);
// If the move was not valid, tell the user and try again
if (realMoveToApply == null)
{
manager.getPlayerInterface().addTextToStatusPanel("received move was not legal: " + move + "\n");
manager.getPlayerInterface().addTextToStatusPanel("currentTrialLength: " + context.trial().moveNumber() + "\n");
return false;
}
// If the move was valid, try and apply it.
applyHumanMoveToGame(manager, realMoveToApply);
return true;
}
//-------------------------------------------------------------------------
/**
* Plays a random move in the current position.
*/
public void randomMove(final Manager manager)
{
final Moves legal = context.game().moves(context);
if (legal.moves().size() > 0)
{
final int moveIndex = ThreadLocalRandom.current().nextInt(0, legal.moves().size());
final Move randomMove = legal.get(moveIndex);
applyHumanMoveToGame(manager, randomMove);
}
}
//-------------------------------------------------------------------------
/**
* Time random playouts.
*
* @return Average number of playouts per second.
*/
public double timeRandomPlayouts()
{
// Use a copy of our context for all the playouts
final Context timingContext = new Context(context);
final Game game = timingContext.game();
// Warming
long stopAt = 0;
long start = System.nanoTime();
double abortAt = start + 10 * 1000000000.0;
while (stopAt < abortAt)
{
game.start(timingContext);
game.playout(timingContext, null, 1.0, null, 0, -1, ThreadLocalRandom.current());
stopAt = System.nanoTime();
}
stopAt = 0;
System.gc();
start = System.nanoTime();
abortAt = start + 30 * 1000000000.0;
int playouts = 0;
int moveDone = 0;
while (stopAt < abortAt)
{
game.start(timingContext);
game.playout(timingContext, null, 1.0, null, 0, -1, ThreadLocalRandom.current());
stopAt = System.nanoTime();
moveDone += timingContext.trial().numMoves();
playouts++;
}
final double secs = (stopAt - start) / 1000000000.0;
final double rate = (playouts / secs);
final double rateMove = (moveDone / secs);
System.out.println(String.format(Locale.US, "%.2f", Double.valueOf(rate)) + "p/s");
System.out.println(String.format(Locale.US, "%.2f", Double.valueOf(rateMove)) + "m/s");
return rate;
}
//-------------------------------------------------------------------------
/**
* Perform a random playout.
*/
public void randomPlayout(final Manager manager)
{
interruptAI(manager);
final Game gameToPlayout = context.game();
gameToPlayout.playout(context, null, 1.0, null, 0, -1, ThreadLocalRandom.current());
EventQueue.invokeLater(() ->
{
manager.getPlayerInterface().postMoveUpdates(context.trial().lastMove(), true);
});
}
/**
* Perform a random playout only for the current instance within a Match
*/
public void randomPlayoutSingleInstance(final Manager manager)
{
final Context instanceContext = context.currentInstanceContext();
final Trial instanceTrial = instanceContext.trial();
if (!instanceTrial.over())
{
interruptAI(manager);
final Trial startInstanceTrial = context.currentInstanceContext().trial();
int currentMovesMade = startInstanceTrial.numMoves();
// if (manager.savedTrial() != null)
// {
// final List<Move> tempActions = context.trial().generateCompleteMovesList();
// manager.getPlayerInterface().restartGame();
// makeSavedMoves(manager, tempActions);
// }
final Game gameToPlayout = instanceContext.game();
gameToPlayout.playout(instanceContext, null, 1.0, null, 0, -1, ThreadLocalRandom.current());
// Will likely have to append some extra moves to the match-wide trial
final List<Move> subtrialMoves = instanceContext.trial().generateCompleteMovesList();
final int numMovesAfterPlayout = subtrialMoves.size();
final int numMovesToAppend = numMovesAfterPlayout - currentMovesMade;
for (int i = 0; i < numMovesToAppend; ++i)
context.trial().addMove(subtrialMoves.get(subtrialMoves.size() - numMovesToAppend + i));
// If the instance we over, we have to advance here in this Match
if (instanceTrial.over())
{
final Moves legalMatchMoves = context.game().moves(context);
assert (legalMatchMoves.moves().size() == 1);
assert (legalMatchMoves.moves().get(0).containsNextInstance());
context.game().apply(context, legalMatchMoves.moves().get(0));
}
// We only want to print moves in moves tab from the last trial
if (context().currentInstanceContext().trial() != startInstanceTrial)
currentMovesMade = context().currentInstanceContext().trial().numInitialPlacementMoves();
}
}
//-------------------------------------------------------------------------
/**
* Triggers a move from the next player. If the next player is human then
* control drops through to wait for input.
*
* @param humanBasedStepStart True if the caller responds to human input
* @return True if we started a new step in the model
*/
public synchronized boolean nextMove(final Manager manager, final boolean humanBasedStepStart)
{
wantNextMoveCall.set(false);
if (!allowHumanBasedStepStart.get() && humanBasedStepStart)
return false;
try
{
if (!context().trial().over())
{
final Model model = context.model();
// In case of a simulation.
if (context.game().mode().mode().equals(ModeType.Simulation))
{
final List<AI> list = new ArrayList<AI>();
list.add(new DoNothingAI());
model.unpauseAgents
(
context,
list,
new double[]{ manager.settingsManager().tickLength() },
Constants.UNDEFINED,
Constants.UNDEFINED,
0.0,
null,
null,
true,
new MoveMessageCallback()
{
@Override
public void call(final String message)
{
manager.getPlayerInterface().addTextToStatusPanel(message);
}
}
);
postMoveApplication(manager, context.trial().lastMove(), false);
}
if (!model.isReady() && model.isRunning() && !manager.settingsManager().agentsPaused())
{
final double[] thinkTime = AIDetails.convertToThinkTimeArray(manager.aiSelected());
List<AI> agents = null;
if (!manager.settingsManager().agentsPaused())
agents = AIDetails.convertToAIList(manager.aiSelected());
if (agents != null)
AIUtil.checkAISupported(manager, context);
model.unpauseAgents
(
context,
agents,
thinkTime,
-1, -1,
0.4,
new AgentMoveCallback()
{
@Override
public long call(final Move move)
{
preMoveApplication(manager, move);
return 0L;
}
},
new AgentMoveCallback()
{
@Override
public long call(final Move move)
{
postMoveApplication(manager, move, false);
return -1L;
}
},
true,
new MoveMessageCallback()
{
@Override
public void call(final String message)
{
manager.getPlayerInterface().addTextToStatusPanel(message);
}
}
);
}
else
{
allowHumanBasedStepStart.set(model.expectsHumanInput());
if (moveThread != null && moveThread.isAlive())
moveThread.runnable.shouldTerminate = true;
moveThread = new RefereeStepThread(new RefereeStepRunnable()
{
@Override
public void run()
{
final double[] thinkTime = AIDetails.convertToThinkTimeArray(manager.aiSelected());
List<AI> agents = null;
if (!manager.settingsManager().agentsPaused())
{
agents = AIDetails.convertToAIList(manager.aiSelected());
}
// make sure any AIs are initialised
if (agents != null)
{
for (int p = 1; p <= context.game().players().count(); ++p)
{
if (agents.get(p) == null)
continue;
if (!agents.get(p).supportsGame(context.game()))
{
final AI oldAI = manager.aiSelected()[p].ai();
final AI newAI = AIUtils.defaultAiForGame(context.game());
final JSONObject json = new JSONObject()
.put("AI", new JSONObject()
.put("algorithm", newAI.friendlyName())
);
manager.aiSelected()[p] = new AIDetails(manager, json, p, "Ludii AI");
EventQueue.invokeLater(() ->
{
manager.getPlayerInterface().addTextToStatusPanel
(
oldAI.friendlyName() + " does not support this game. Switching to default AI for this game: "
+
newAI.friendlyName() + ".\n"
);
});
}
agents.get(p).initIfNeeded(context.game(), p);
}
}
final Trial startInstanceTrial = context.currentInstanceContext().trial();
model.startNewStep
(
context,
agents,
thinkTime,
-1, -1,
manager.settingsManager().minimumAgentThinkTime(),
false, // don't block
true, // force use of threads
false, // don't force use of no threads
new AgentMoveCallback()
{
@Override
public long call(final Move move)
{
preMoveApplication(manager, move);
return 0L;
}
},
new AgentMoveCallback()
{
@Override
public long call(final Move move)
{
postMoveApplication(manager, move, false);
return -1L;
}
},
true,
new MoveMessageCallback()
{
@Override
public void call(final String message)
{
manager.getPlayerInterface().addTextToStatusPanel(message);
}
}
);
while (!model.isReady() && !shouldTerminate)
{
manager.setLiveAIs(model.getLiveAIs());
allowHumanBasedStepStart.set(model.expectsHumanInput());
try
{
final List<AI> liveAIs = manager.liveAIs();
if (liveAIs != null && !liveAIs.isEmpty())
{
EventQueue.invokeAndWait(() ->
{
manager.getPlayerInterface().repaint();
});
}
Thread.sleep(AI_VIS_UPDATE_TIME);
}
catch (final InterruptedException | InvocationTargetException e)
{
e.printStackTrace();
}
}
if (shouldTerminate)
return;
EventQueue.invokeLater(() ->
{
manager.getPlayerInterface().repaint();
});
allowHumanBasedStepStart.set(false);
manager.setLiveAIs(null);
// If we transitioned to new instance, we need to pause
if (startInstanceTrial != context.currentInstanceContext().trial())
manager.settingsManager().setAgentsPaused(manager, true);
if (!manager.settingsManager().agentsPaused())
{
final List<AI> ais = model.getLastStepAIs();
EventQueue.invokeLater(() ->
{
for (int i = 0; i < ais.size(); ++i)
{
final AI ai = ais.get(i);
if (ai != null)
{
final String analysisReport = ai.generateAnalysisReport();
if (analysisReport != null)
manager.getPlayerInterface().addTextToAnalysisPanel(analysisReport + "\n");
}
}
});
if (!context().trial().over())
{
wantNextMoveCall.set(true);
nextMove(manager, false);
}
else
{
allowHumanBasedStepStart.set(true);
}
}
else
{
allowHumanBasedStepStart.set(true);
}
}
});
moveThread.setDaemon(true);
moveThread.start();
// Don't return until the model has at least started running (or maybe instantly completed)
while (!wantNextMoveCall.get() && moveThread != null && moveThread.isAlive() && (model.isReady() || !model.isRunning()))
{
// Don't return from call yet, keep calling thread occupied until
// model is at least properly running (or maybe already finished)
}
}
}
else
{
return false;
}
return true;
}
finally
{
if (!humanBasedStepStart && !context.model().isRunning())
{
allowHumanBasedStepStart.set(true);
}
}
}
//-------------------------------------------------------------------------
/**
* Callback to call prior to application of AI-chosen moves
*/
void preMoveApplication(final Manager manager, final Move move)
{
if (manager.settingsManager().showRepetitions())
{
final Context newContext = new Context(context);
newContext.trial().previousState().clear();
newContext.trial().previousStateWithinATurn().clear();
newContext.game().apply(newContext, move);
manager.settingsManager().setMovesAllowedWithRepetition(newContext.game().moves(newContext).moves());
}
}
//-------------------------------------------------------------------------
/**
* Handle miscellaneous stuff we need to do after applying a move
*/
public void postMoveApplication(final Manager manager, final Move move, final boolean savedMove)
{
// Store the hash of each state encountered.
if (manager.settingsManager().showRepetitions() && !manager.settingsManager().storedGameStatesForVisuals().contains(Long.valueOf(context.state().stateHash())))
manager.settingsManager().storedGameStatesForVisuals().add(Long.valueOf(context.state().stateHash()));
if (!savedMove)
{
manager.undoneMoves().clear();
if (manager.settingsNetwork().getActiveGameId() != 0)
{
String scoreString = "";
if (context.game().requiresScore())
for (int i = 1; i <= context.game().players().count(); i++)
scoreString += context.score(context.state().playerToAgent(i)) + ",";
final int moveNumber = context.currentInstanceContext().trial().numMoves() - context.currentInstanceContext().trial().numInitialPlacementMoves();
manager.databaseFunctionsPublic().sendMoveToDatabase(manager, move, context.state().mover(), scoreString, moveNumber);
manager.databaseFunctionsPublic().checkNetworkSwap(manager, move);
}
// Check if need to apply instant Pass move.
checkInstantPass(manager);
}
manager.getPlayerInterface().setTemporaryMessage("");
manager.getPlayerInterface().postMoveUpdates(move, savedMove);
}
//-------------------------------------------------------------------------
/**
* Checks if a pass move should be applied instantly, if its the only legal move and the game is stochastic.
*/
private void checkInstantPass(final Manager manager)
{
final Moves legal = context.game().moves(context);
final Move firstMove = legal.moves().get(0);
if
(
manager.aiSelected()[manager.moverToAgent()].ai() == null // Don't check instant pass if an AI is selected. Can potentially cause GUI threading issues.
&&
legal.moves().size() == 1 && firstMove.isPass() && firstMove.isForced()
&&
(!context.game().isStochasticGame() || manager.settingsManager().alwaysAutoPass())
&&
manager.settingsNetwork().getActiveGameId() == 0 // Instant pass can cause problems for remote games.
)
{
applyHumanMoveToGame(manager, firstMove);
}
}
//-------------------------------------------------------------------------
/**
* Attempts to interrupt any AI that is currently running, and returns only once there no longer is any AI thinking thread alive.
*/
public void interruptAI(final Manager manager)
{
context.model().interruptAIs();
manager.setLiveAIs(null);
allowHumanBasedStepStart.set(true);
}
//-------------------------------------------------------------------------
/**
* Runnable for per-step threads in Referee
*
* @author Dennis Soemers
*/
protected static abstract class RefereeStepRunnable implements Runnable
{
/** We can set this to true to indicate that we want to terminate, for example when loading a new game */
public boolean shouldTerminate = false;
}
/**
* Per-step thread for referee
*
* @author Dennis Soemers
*/
protected static class RefereeStepThread extends Thread
{
/** Our runnable */
public final RefereeStepRunnable runnable;
/**
* Constructor
* @param runnable
*/
public RefereeStepThread(final RefereeStepRunnable runnable)
{
super(runnable);
this.runnable = runnable;
}
}
//-------------------------------------------------------------------------
}
| 21,455 | 27.569907 | 161 |
java
|
Ludii
|
Ludii-master/Manager/src/manager/ai/AIDetails.java
|
package manager.ai;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;
import manager.Manager;
import other.AI;
import utils.AIFactory;
/**
* Object for storing all GUI-relevant details about an particular player/AI.
*
* @author Matthew.Stephenson
*/
public class AIDetails
{
/** AI JSONObject */
private JSONObject object;
/** AI for controlling this player (can be Human) */
private AI aI;
/** Thinking time for this AI */
private double thinkTime;
/** Name of this AI/player */
private String name;
/** Menu Name for this AI/player (used for the player panel) */
private String menuItemName;
//-------------------------------------------------------------------------
public AIDetails(final Manager manager, final JSONObject object, final int playerId, final String menuItemName)
{
this.object = object;
if (object != null)
{
final JSONObject aiObj = object.getJSONObject("AI");
final String algName = aiObj.getString("algorithm");
if (!algName.equalsIgnoreCase("Human"))
{
AI aiFromName = AIFactory.fromJson(object);
if (manager.isWebApp() && manager.ref().context() != null && aiFromName.usesFeatures(manager.ref().context().game()))
{
final JSONObject json = new JSONObject()
.put("AI", new JSONObject()
.put("algorithm", "UCT")
);
aiFromName = AIFactory.fromJson(json);
}
setAI(aiFromName);
}
}
else
{
this.object = new JSONObject().put
(
"AI", new JSONObject().put("algorithm", "Human")
);
}
try
{
name = manager.aiSelected()[playerId].name();
}
catch (final Exception e)
{
name = "Player " + playerId;
}
try
{
thinkTime = manager.aiSelected()[playerId].thinkTime();
}
catch (final Exception e)
{
thinkTime = 1.0;
}
this.menuItemName = menuItemName;
}
//-------------------------------------------------------------------------
public String name()
{
return name;
}
public void setName(final String name)
{
this.name = name;
}
public String menuItemName()
{
return menuItemName;
}
public void setMenuItemName(final String menuItemName)
{
this.menuItemName = menuItemName;
}
public JSONObject object()
{
return object;
}
public AI ai()
{
// AI might have been set to null during game compilation, in which case it needs to be recreated.
if (aI == null && object != null)
{
final JSONObject aiObj = object.getJSONObject("AI");
final String algName = aiObj.getString("algorithm");
if (!algName.equalsIgnoreCase("Human"))
{
setAI(AIFactory.fromJson(object));
}
}
return aI;
}
public double thinkTime()
{
return thinkTime;
}
public void setThinkTime(final double thinkTime)
{
this.thinkTime = thinkTime;
}
//-------------------------------------------------------------------------
public static AIDetails getCopyOf(final Manager manager, final AIDetails oldAIDetails, final int playerId)
{
if (oldAIDetails == null)
return new AIDetails(manager, null, playerId, "Human");
final AIDetails newAIDetails = new AIDetails(manager, oldAIDetails.object(), playerId, oldAIDetails.menuItemName);
newAIDetails.setName(oldAIDetails.name());
newAIDetails.setThinkTime(oldAIDetails.thinkTime());
newAIDetails.setName(oldAIDetails.name());
return newAIDetails;
}
//-------------------------------------------------------------------------
public static List<AI> convertToAIList(final AIDetails[] details)
{
final List<AI> aiList = new ArrayList<>();
for (final AIDetails detail : details)
aiList.add(detail.ai());
return aiList;
}
public static double[] convertToThinkTimeArray(final AIDetails[] details)
{
final double[] timeArray = new double[details.length];
for (int i = 0; i < details.length; i++)
timeArray[i] = details[i].thinkTime();
return timeArray;
}
//-------------------------------------------------------------------------
public boolean equals(final AIDetails aiDetails)
{
if (!aiDetails.object.equals(object))
return false;
if (!aiDetails.name.equals(name))
return false;
if (!aiDetails.menuItemName.equals(menuItemName))
return false;
return true;
}
//-------------------------------------------------------------------------
public void setAI(final AI aI)
{
this.aI = aI;
}
//-------------------------------------------------------------------------
}
| 4,485 | 21.318408 | 121 |
java
|
Ludii
|
Ludii-master/Manager/src/manager/ai/AIRegistry.java
|
package manager.ai;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.json.JSONObject;
import game.Game;
import other.AI;
import search.flat.FlatMonteCarlo;
import search.mcts.MCTS;
import search.minimax.AlphaBetaSearch;
import search.minimax.BRSPlus;
import utils.AIFactory;
import utils.AIFactory.AIConstructor;
import utils.RandomAI;
/**
* A registry of AIs that can be instantiated in the GUI of Ludii.
*
* @author Dennis Soemers, Eric.Piette
*/
public class AIRegistry
{
//-------------------------------------------------------------------------
/** Our registry */
protected static Map<String, AIRegistryEntry> registry = new HashMap<String, AIRegistryEntry>();
/** Rank to assign to next registered AI (used for sorting when we want a sorted list of AIs) */
protected static volatile int nextRank = 0;
static
{
// Static block to register our built-in AIs
registerAI("Human", -1, (game) -> {return false;}, null); // We have special handling for human in dropdown menus
registerAI("Ludii AI", -1, (game) -> {return true;}, null);
registerAI("Random", 1, (game) -> {return new RandomAI().supportsGame(game);}, null);
registerAI("Flat MC", 2, (game) -> {return new FlatMonteCarlo().supportsGame(game);}, null);
registerAI("UCT", 3, (game) -> {return MCTS.createUCT().supportsGame(game);}, null);
registerAI("UCT (Uncapped)", 4, (game) -> {return MCTS.createUCT().supportsGame(game);}, null);
registerAI("MC-GRAVE", 5, (game) -> {return AIFactory.createAI("MC-GRAVE").supportsGame(game);}, null);
registerAI("Progressive History", 6, (game) -> {return AIFactory.createAI("Progressive History").supportsGame(game);}, null);
registerAI("MAST", 7, (game) -> {return AIFactory.createAI("MAST").supportsGame(game);}, null);
registerAI("Biased MCTS", 8, (game) -> {return MCTS.createBiasedMCTS(0.0).supportsGame(game);}, null);
registerAI("MCTS (Biased Selection)", 9, (game) -> {return MCTS.createBiasedMCTS(1.0).supportsGame(game);}, null);
registerAI("Alpha-Beta", 10, (game) -> {return AlphaBetaSearch.createAlphaBeta().supportsGame(game);}, null);
registerAI("BRS+", 11, (game) -> {return new BRSPlus().supportsGame(game);}, null);
registerAI("MCTS (Hybrid Selection)", 12, (game) -> {return MCTS.createHybridMCTS().supportsGame(game);}, null);
registerAI("Bandit Tree Search", 13, (game) -> {return MCTS.createBanditTreeSearch().supportsGame(game);}, null);
registerAI("NST", 14, (game) -> {return AIFactory.createAI("NST").supportsGame(game);}, null);
registerAI("UCB1Tuned", 15, (game) -> {return AIFactory.createAI("UCB1Tuned").supportsGame(game);}, null);
registerAI("Progressive Bias", 16, (game) -> {return AIFactory.createAI("Progressive Bias").supportsGame(game);}, null);
registerAI("EPT", 17, (game) -> {return AIFactory.createAI("EPT").supportsGame(game);}, null);
registerAI("EPT-QB", 18, (game) -> {return AIFactory.createAI("EPT-QB").supportsGame(game);}, null);
registerAI("Score Bounded MCTS", 19, (game) -> {return AIFactory.createAI("Score Bounded MCTS").supportsGame(game);}, null);
registerAI("Heuristic Sampling", 20, (game) -> {return AIFactory.createAI("Heuristic Sampling").supportsGame(game);}, null);
registerAI("One-Ply (No Heuristic)", 21, (game) -> {return AIFactory.createAI("One-Ply (No Heuristic)").supportsGame(game);}, null);
//registerAI("Bob the Basic AI", 22, (game) -> {return true;}, null);
registerAI("UBFM", 23, (game) -> {return AIFactory.createAI("UBFM").supportsGame(game);}, null);
registerAI("Hybrid UBFM", 24, (game) -> {return AIFactory.createAI("Hybrid UBFM").supportsGame(game);}, null);
registerAI("Biased UBFM", 25, (game) -> {return AIFactory.createAI("Biased UBFM").supportsGame(game);}, null);
registerAI("Lazy UBFM", 26, (game) -> {return AIFactory.createAI("Lazy UBFM").supportsGame(game);}, null);
registerAI("From JAR", -1, (game) -> {return false;}, null); // We have special handling for From JAR in dropdown menus
}
//-------------------------------------------------------------------------
/**
* Registers a new AI. NOTE: this method does not provide a predicate to test
* whether or not any given game is supported, so we assume that ANY game is
* supported!
*
* @param label
* @param aiConstructor Functor to use for constructing AIs
* @return True if we successfully registered an AI, false if an AI with
* the same label was already registered.
*/
public static boolean registerAI(final String label, final AIConstructor aiConstructor)
{
return registerAI(label, -1, (game) -> {return true;}, aiConstructor);
}
/**
* Registers a new AI.
*
* @param label
* @param aiConstructor Functor to use for constructing AIs
* @param supportsGame Predicate to test whether or not any given game is supported.
* @return True if we successfully registered an AI, false if an AI with
* the same label was already registered.
*/
public static boolean registerAI
(
final String label, final AIConstructor aiConstructor, final SupportsGamePredicate supportsGame
)
{
return registerAI(label, -1, supportsGame, aiConstructor);
}
//-------------------------------------------------------------------------
/**
* @param game
* @return List of all agent names that are valid for given game
*/
public static List<String> generateValidAgentNames(final Game game)
{
final List<String> names = new ArrayList<String>();
for (final Entry<String, AIRegistryEntry> entry : registry.entrySet())
{
if (entry.getValue().supportsGame(game))
names.add(entry.getKey());
}
names.sort
(
new Comparator<String>()
{
@Override
public int compare(final String o1, final String o2)
{
return registry.get(o1).rank - registry.get(o2).rank;
}
}
);
return names;
}
/**
* Updates the given JSON object to properly handle registered third-party AIs
* @param json
*/
public static void processJson(final JSONObject json)
{
if (json == null || json.getJSONObject("AI") == null)
return;
final AIRegistryEntry entry = registry.get(json.getJSONObject("AI").getString("algorithm"));
if (entry != null)
{
final AIConstructor constructor = entry.aiConstructor();
if (constructor != null)
json.put("constructor", constructor);
}
}
//-------------------------------------------------------------------------
/**
* Registers a new AI
* @param label
* @param dbID
* @param supportsGame
* @param aiConstructor
* @return True if we successfully registered an AI, false if an AI with
* the same label was already registered.
*/
private static boolean registerAI
(
final String label, final int dbID,
final SupportsGamePredicate supportsGame, final AIConstructor aiConstructor
)
{
if (registry.containsKey(label))
return false;
registry.put(label, new AIRegistryEntry(label, dbID, supportsGame, aiConstructor));
return true;
}
//-------------------------------------------------------------------------
/**
* @param agentName The name of the agent.
* @return The AI object from its name.
*/
public static AI fromRegistry
(
final String agentName
)
{
final JSONObject json = new JSONObject();
final JSONObject aiJson = new JSONObject();
aiJson.put("algorithm", agentName);
json.put("AI", aiJson);
AIRegistry.processJson(json);
return AIFactory.fromJson(json);
}
//-------------------------------------------------------------------------
/**
* Interface for a predicate that tests whether or not an AI supports a given game.
*
* @author Dennis Soemers
*/
public static interface SupportsGamePredicate
{
/**
* @param game
* @return True if and only if the given game is supported.
*/
public boolean supportsGame(final Game game);
}
//-------------------------------------------------------------------------
/**
* An entry in the AI registry
*
* @author Dennis Soemers
*/
public static class AIRegistryEntry
{
/** Label of the entry */
private final String label;
/** Database ID of the AI (only built-in Ludii agents can have a database ID >= 0) */
private final int dbID;
/** Predicate to test whether or not we support a given game */
private final SupportsGamePredicate supportsGame;
/** Functor to construct AIs. If null, we'll use the AI factory to construct based on just name */
private final AIConstructor aiConstructor;
/** Used for sorting when we want sorted lists (in order of registration) */
protected final int rank;
/**
* Constructor.
*
* NOTE: intentionally protected. We want third-party users to go through the static
* registerAI() method.
*
* @param label
* @param dbID
* @param supportsGame
*/
protected AIRegistryEntry
(
final String label, final int dbID,
final SupportsGamePredicate supportsGame, final AIConstructor aiConstructor
)
{
this.label = label;
this.dbID = dbID;
this.supportsGame = supportsGame;
this.aiConstructor = aiConstructor;
this.rank = nextRank++;
}
/**
* @return The AI's label
*/
public String label()
{
return label;
}
/**
* @return Functor to use to construct AIs. If this returns null, should instead
* construct AIs just from name.
*/
public AIConstructor aiConstructor()
{
return aiConstructor;
}
/**
* @return The AI's database ID (only >= 0 for Ludii built-in AIs)
*/
public int dbID()
{
return dbID;
}
/**
* @param game
* @return True if and only if we support the given game
*/
public boolean supportsGame(final Game game)
{
return supportsGame.supportsGame(game);
}
}
//-------------------------------------------------------------------------
}
| 9,892 | 32.422297 | 134 |
java
|
Ludii
|
Ludii-master/Manager/src/manager/ai/AIUtil.java
|
package manager.ai;
import java.awt.EventQueue;
import org.json.JSONObject;
import manager.Manager;
import other.AI;
import other.context.Context;
import other.model.SimultaneousMove;
import utils.AIUtils;
/**
* Functions for handling AI agents.
*
* @author Matthew.Stephenson
*/
public class AIUtil
{
/**
* Cycles all players backwards by one.
*/
public static void cycleAgents(final Manager manager)
{
manager.settingsManager().setAgentsPaused(manager, true);
final AIDetails player1Details = AIDetails.getCopyOf(manager, manager.aiSelected()[1], 1);
for (int i = 2; i <= manager.ref().context().game().players().count(); i++)
manager.aiSelected()[i-1] = AIDetails.getCopyOf(manager, manager.aiSelected()[i], i);
manager.aiSelected()[manager.ref().context().game().players().count()] = player1Details;
manager.settingsNetwork().backupAiPlayers(manager);
}
//-------------------------------------------------------------------------
/**
* Update the selected AI agents for the given player numbers.
*/
public static void updateSelectedAI(final Manager manager, final JSONObject inJSON, final int playerNum, final String aiMenuName)
{
String menuName = aiMenuName;
JSONObject json = inJSON;
final JSONObject aiObj = json.getJSONObject("AI");
final String algName = aiObj.getString("algorithm");
if (algName.equals("Human"))
{
// First close previous AI if it exists
if (manager.aiSelected()[playerNum].ai() != null)
manager.aiSelected()[playerNum].ai().closeAI();
manager.aiSelected()[playerNum] = new AIDetails(manager, null, playerNum, "Human");
return;
}
else if (algName.equals("From JAR"))
{
if (!aiObj.has("JAR File") || !aiObj.has("Class Name"))
{
json = manager.getPlayerInterface().getNameFromJar();
if (json == null)
return;
menuName = "From JAR";
}
}
else if (algName.equals("From JSON"))
{
if (!aiObj.has("JSON File") || !aiObj.has("Class Name"))
{
json = manager.getPlayerInterface().getNameFromJson();
if (json == null)
return;
menuName = "From JSON";
}
}
else if (algName.equals("From AI.DEF"))
{
if (!aiObj.has("AI.DEF File") || !aiObj.has("Class Name"))
{
json = manager.getPlayerInterface().getNameFromAiDef();
if (json == null)
return;
menuName = "From AI.DEF";
}
}
else
{
AIRegistry.processJson(json);
}
// First close previous AI if it exists
if (manager.aiSelected()[playerNum].ai() != null)
manager.aiSelected()[playerNum].ai().closeAI();
manager.aiSelected()[playerNum] = new AIDetails(manager, json, playerNum, menuName);
manager.settingsNetwork().backupAiPlayers(manager);
pauseAgentsIfNeeded(manager);
return;
}
//-------------------------------------------------------------------------
/**
* Pauses all agents if required.
* Should be called any time the game is restarted/loaded, or an AI is selected.
*/
public static void pauseAgentsIfNeeded(final Manager manager)
{
if (manager.settingsNetwork().getActiveGameId() != 0 && !manager.settingsNetwork().getOnlineAIAllowed())
manager.settingsManager().setAgentsPaused(manager, true);
else if (manager.aiSelected()[manager.moverToAgent()].ai() != null)
manager.settingsManager().setAgentsPaused(manager, true);
else if (manager.ref().context().model() instanceof SimultaneousMove)
manager.settingsManager().setAgentsPaused(manager, true);
else if (manager.ref().context().game().players().count() == 0)
manager.settingsManager().setAgentsPaused(manager, true);
else
manager.settingsManager().setAgentsPaused(manager, false);
}
//-------------------------------------------------------------------------
/**
* Checks if any of the currently selected AI are not supported by the current game.
* @param context
*/
public static void checkAISupported(final Manager manager, final Context context)
{
// Make sure all AIs are initialised.
for (int p = 1; p < manager.aiSelected().length; ++p)
{
if (manager.aiSelected()[p].ai() == null)
continue;
if (!manager.aiSelected()[p].ai().supportsGame(context.game()))
{
final AI oldAI = manager.aiSelected()[p].ai();
final AI newAI = AIUtils.defaultAiForGame(context.game());
final JSONObject json = new JSONObject()
.put("AI", new JSONObject()
.put("algorithm", newAI.friendlyName())
);
manager.aiSelected()[p] = new AIDetails(manager, json, p, "Ludii AI");
EventQueue.invokeLater(() ->
{
manager.getPlayerInterface().addTextToStatusPanel(oldAI.friendlyName() + " does not support this game. Switching to default AI for this game: " + newAI.friendlyName() + ".\n");
});
}
if (p <= context.game().players().count())
manager.aiSelected()[p].ai().initIfNeeded(context.game(), p);
}
manager.settingsNetwork().backupAiPlayers(manager);
}
//-------------------------------------------------------------------------
/**
* @param manager
* @return If any of the games players are being controlled by an AI.
*/
public static boolean anyAIPlayer(final Manager manager)
{
for (int i = 1; i <= manager.ref().context().game().players().count(); i++)
if (manager.aiSelected()[i].ai() != null)
return true;
return false;
}
//-------------------------------------------------------------------------
}
| 5,404 | 28.697802 | 181 |
java
|
Ludii
|
Ludii-master/Manager/src/manager/network/DatabaseFunctionsPublic.java
|
package manager.network;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.rng.core.RandomProviderDefaultState;
import manager.Manager;
import other.context.Context;
import other.move.Move;
import other.trial.Trial;
/**
* Public class for calling database functions on the Ludii Server.
* Fake function calls. Database functionality is not available in the source code to prevent server spamming.
*
* @author Matthew.Stephenson and Dennis Soemers
*/
@SuppressWarnings("static-method")
public class DatabaseFunctionsPublic
{
//-------------------------------------------------------------------------
/** Class loader used to load private network code if available (not included in public source code repo) */
private static URLClassLoader privateNetworkCodeClassLoader = null;
// Static block to initialise classloader
static
{
final File networkPrivateBin = new File("../../LudiiPrivate/NetworkPrivate/bin");
if (networkPrivateBin.exists())
{
try
{
privateNetworkCodeClassLoader = new URLClassLoader(new URL[]{networkPrivateBin.toURI().toURL()});
}
catch (final MalformedURLException e)
{
// If this fails, that's fine, just means we don't have private code available
}
}
}
//-------------------------------------------------------------------------
/**
* @return Constructs a wrapper around the database functions.
*/
public static DatabaseFunctionsPublic construct()
{
// See if we can find private code first
final ClassLoader classLoader =
privateNetworkCodeClassLoader != null ? privateNetworkCodeClassLoader : DatabaseFunctionsPublic.class.getClassLoader();
try
{
final Class<?> privateClass = Class.forName("manager.network.privateFiles.DatabaseFunctionsPrivate", true, classLoader);
if (privateClass != null)
{
// Found private network code, use its zero-args constructor
return (DatabaseFunctionsPublic) privateClass.getConstructor().newInstance();
}
}
catch (final Exception e)
{
// Nothing to do
}
// Failed to load the private class, so we're probably working just with public source code
return new DatabaseFunctionsPublic();
}
//-------------------------------------------------------------------------
// Analysis
/**
* Gets all valid trials from the database for the provided parameters.
*/
public ArrayList<String> getTrialsFromDatabase(final String gameName, final List<String> gameOptions, final String agentName, final double thinkingTime, final int maxTurns, final int gameHash)
{
return new ArrayList<>();
}
/**
* Stores a trail in the database.
*/
public void storeTrialInDatabase(final String gameName, final List<String> gameOptions, final String agentName, final double thinkingTime, final int maxTurns, final int gameHash, final Trial trial, final RandomProviderDefaultState RNG)
{
// Do nothing.
}
/**
* Stores a website trail in the database.
*/
public void storeWebTrialInDatabase(final String gameName, final String rulesetName, final List<String> gameOptions, final int gameId, final int rulesetId, final boolean[] agents, final String username, final int gameHash, final Trial trial, final RandomProviderDefaultState RNG)
{
// Do nothing.
}
//-------------------------------------------------------------------------
// Remote
/**
* Begins repeating network actions that must be continuously performed while online.
*/
public void repeatNetworkActions(final Manager manager)
{
// Do nothing.
}
/**
* Provides an md5 encrypted hash string of a given password.
*/
public String md5(final String passwordToHash)
{
return "";
}
/**
* Refresh login flag on server, and make sure secret number up to date.
*/
public void refreshLogin(final Manager manager)
{
// Do nothing.
}
/**
* Sets the remaining time for each player.
*/
public void checkRemainingTime(final Manager manager)
{
// Do nothing.
}
/**
* Get a String representation of the remaining time for all players.
*/
public String getRemainingTime(final Manager manager)
{
return "";
}
/**
* Get a String representation of all (offline or online) players.
*/
public String GetAllPlayers()
{
return "";
}
/**
* Get a String representation of all tournaments that we have joined.
*/
public String findJoinedTournaments(final Manager manager)
{
return "";
}
/**
* Update the incoming messages chat with any new private messages.
*/
public void updateIncomingMessages(final Manager manager)
{
// Do nothing.
}
/**
* Update the last time the server was contacted.
*/
public void updateLastServerTime(final Manager manager)
{
// Do nothing.
}
/**
* Get a String representation of all private games that we have not previously joined.
*/
public String findJoinableGames(final Manager manager)
{
return "";
}
/**
* Get a String representation of all games that we have previously joined.
*/
public String findJoinedGames(final Manager manager)
{
return "";
}
/**
* Get a String representation of all games that we can spectate.
*/
public String findOtherGames(final Manager manager)
{
return "";
}
/**
* Get a String representation of all private tournaments that we have not previously joined.
*/
public String findJoinableTournaments(final Manager manager)
{
return "";
}
/**
* Get a String representation of all tournaments that we have previously joined.
*/
public String findHostedTournaments(final Manager manager)
{
return "";
}
/**
* Sends a message to the group chat for the current game.
*/
public void sendGameChatMessage(final Manager manager, final String s)
{
// Do nothing.
}
/**
* Sends a specified move to the database.
*/
public void sendMoveToDatabase(final Manager manager, final Move m, final int nextMover, final String score, final int moveNumber)
{
// Do nothing.
}
/**
* Sends the database a message to say that the game is finished
*/
public void sendGameOverDatabase(final Manager manager)
{
// Do nothing.
}
/**
* Sends the database a message to say that you have forfeit the game.
*/
public void sendForfeitToDatabase(final Manager manager)
{
// Do nothing.
}
/**
* Sends the database a message to say that you have proposed a draw.
*/
public void sendProposeDraw(final Manager manager)
{
// Do nothing.
}
/**
* Checks if each of the current game players are online or offline.
*/
public void checkOnlinePlayers(final Manager manager)
{
// Do nothing.
}
/**
* Checks if there are any outstanding moves in the database that need to be carried out.
*/
public void getMoveFromDatabase(final Manager manager)
{
// Do nothing.
}
/**
* Checks if there are any outstanding moves in the database that need to be carried out.
*/
public void checkStatesMatch(final Manager manager)
{
// Do nothing.
}
/**
* Checks if any players have forfeit or timed out.
*/
public void checkForfeitAndTimeoutAndDraw(final Manager manager)
{
// Do nothing.
}
/**
* Checks if any players have proposed a draw
*/
public void checkDrawProposed(final Manager manager)
{
// Do nothing.
}
/**
* Gets the username of each player in the game.
*/
public String[] getActiveGamePlayerNames(final Manager manager)
{
return new String[0];
}
/**
* Sends the database the current ranking of all played in the game.
*/
public void sendGameRankings(final Manager manager, final double[] rankingOriginal)
{
// Do nothing.
}
/**
* Converts an RandomProviderDefaultState object into a String representation.
*/
public String convertRNGToText(final RandomProviderDefaultState rngState)
{
return "";
}
/**
* Gets the initial RNG seed for the game from the database.
*/
public String getRNG(final Manager manager)
{
return "";
}
/**
* Gets leaderboard information from the database (leaderboard across all games is used).
*/
public String getLeaderboard()
{
return "";
}
/**
* Ping the server to check if we are still connected to it.
*/
public boolean pingServer(final String URLName)
{
return false;
}
/**
* Send result to database and update each player's statistics
*/
public void sendResultToDatabase(final Manager manager, final Context context)
{
// Do nothing.
}
/**
* Log out of the server.
*/
public void logout(final Manager manager)
{
// Do nothing.
}
/**
* Updates network player number if a swap action is made.
*/
public void checkNetworkSwap(final Manager manager, final Move move)
{
// Do nothing.
}
/**
* Location on server where remote scripts are stored.
*/
public String appFolderLocation()
{
return "";
}
/**
* Secret network number used for validating network actions.
*/
public double getSecretNetworkNumber(final Manager manager)
{
return 0.0;
}
}
| 9,056 | 22.282776 | 280 |
java
|
Ludii
|
Ludii-master/Manager/src/manager/network/SettingsNetwork.java
|
package manager.network;
import java.awt.Rectangle;
import java.util.Arrays;
import main.Constants;
import manager.Manager;
import manager.ai.AIDetails;
/**
* Network settings.
*
* @author Matthew.Stephenson
*/
public class SettingsNetwork
{
//-------------------------------------------------------------------------
// Database function parameters
/** Thread for handling repeated network actions. */
private Thread repeatNetworkActionsThread;
/**
* Number of refreshes where the local state doesn't match that stored in the DB.
* If true for too long, a move may have been lost.
*/
private int localStateMatchesDB = 0;
//-------------------------------------------------------------------------
// Network game parameters
/** Player number in a network game, 0 if not in a network game. */
private int networkPlayerNumber = 0;
/** Number of other connected players in the current network game. */
private int numberConnectedPlayers = 0;
/** ID for the network game being played, 0 if not in a network game. */
private int activeGameId = 0;
/** ID for the tournament being played, 0 if not in a network game. */
private int tournamentId = 0;
/** Secret player network number, used for verifying player identity. */
private int secretPlayerNetworkNumber = 0;
/** If AI agents are allowed for the current network game. */
private boolean onlineAIAllowed = false;
/** Last time the server was contacted. */
private int lastServerTime = -1;
//-------------------------------------------------------------------------
// Login settings
/** ID of the user, 0 if not logged in. */
private int loginId = 0;
/** Username of the user, "" if not logged in. */
private String loginUsername = "";
/** If the user wants their username to be remembered. */
private boolean rememberDetails = false;
//-------------------------------------------------------------------------
// Remote Dialog Settings
/** Index of the remote dialog tab currently selected. */
private int tabSelected = 0;
/** Position of the remote dialog. */
private Rectangle remoteDialogPosition;
/** Backup of the AIDetails array stored in PlayerApp, for when we do online games. */
private AIDetails[] onlineBackupAiPlayers = new AIDetails[Constants.MAX_PLAYERS+1];
/** Total time remaining for each player. */
private int[] playerTimeRemaining = new int[Constants.MAX_PLAYERS];
/** If we are currently loading a network game. */
private boolean loadingNetworkGame = false;
//-------------------------------------------------------------------------
// Network player parameters
/** The active players in the current Network game. */
private boolean[] activePlayers = new boolean[Constants.MAX_PLAYERS+1];
/** The players who are online in in the current Network game. */
private boolean[] onlinePlayers = new boolean[Constants.MAX_PLAYERS+1];
/** The players who have proposed a draw this move. */
private boolean[] drawProposedPlayers = new boolean[Constants.MAX_PLAYERS+1];
//-------------------------------------------------------------------------
// Other
/** If the network should be polled for moves less often, useful when slow Internet connection. */
private boolean longerNetworkPolling = false;
/** If the network should not be automatically refreshed, useful when slow Internet connection. */
private boolean noNetworkRefresh = false;
//-------------------------------------------------------------------------
/**
* Constructor.
*/
public SettingsNetwork()
{
resetNetworkPlayers();
}
//-------------------------------------------------------------------------
/**
* Keep a backup of the AI players.
*/
public void backupAiPlayers(final Manager manager)
{
if (activeGameId == 0)
for (int i = 0; i < manager.aiSelected().length; i++)
onlineBackupAiPlayers()[i] = AIDetails.getCopyOf(manager, manager.aiSelected()[i], i);
}
//-------------------------------------------------------------------------
/**
* Restore the AI players from the saved backup.
* Used if a player joins and then leaves an online game.
*/
public void restoreAiPlayers(final Manager manager)
{
for (int i = 0; i < onlineBackupAiPlayers().length; i++)
manager.aiSelected()[i] = AIDetails.getCopyOf(manager, onlineBackupAiPlayers()[i], i);
}
//-------------------------------------------------------------------------
/**
* Reset the network players, after a game is restarted.
*/
public void resetNetworkPlayers()
{
Arrays.fill(activePlayers(), true);
Arrays.fill(onlinePlayers(), false);
Arrays.fill(drawProposedPlayers(), false);
}
//-------------------------------------------------------------------------
public int getNetworkPlayerNumber()
{
return networkPlayerNumber;
}
public void setNetworkPlayerNumber(final int networkPlayerNumber)
{
this.networkPlayerNumber = networkPlayerNumber;
}
public int getNumberConnectedPlayers()
{
return numberConnectedPlayers;
}
public void setNumberConnectedPlayers(final int numberConnectedPlayers)
{
this.numberConnectedPlayers = numberConnectedPlayers;
}
public int getLoginId()
{
return loginId;
}
public void setLoginId(final int loginId)
{
this.loginId = loginId;
}
public String loginUsername()
{
return loginUsername;
}
public void setLoginUsername(final String loginUsername)
{
this.loginUsername = loginUsername;
}
public boolean rememberDetails()
{
return rememberDetails;
}
public void setRememberDetails(final boolean rememberDetails)
{
this.rememberDetails = rememberDetails;
}
public int getActiveGameId()
{
return activeGameId;
}
public void setActiveGameId(final int activeGameId)
{
this.activeGameId = activeGameId;
}
public int tabSelected()
{
return tabSelected;
}
public void setTabSelected(final int tabSelected)
{
this.tabSelected = tabSelected;
}
public Rectangle remoteDialogPosition()
{
return remoteDialogPosition;
}
public void setRemoteDialogPosition(final Rectangle remoteDialogPosition)
{
this.remoteDialogPosition = remoteDialogPosition;
}
public int getTournamentId()
{
return tournamentId;
}
public void setTournamentId(final int tournamentId)
{
this.tournamentId = tournamentId;
}
public void setSecretNetworkNumber(final int secretNetworkNumber)
{
setSecretPlayerNetworkNumber(secretNetworkNumber);
}
public boolean getOnlineAIAllowed()
{
return onlineAIAllowed;
}
public void setOnlineAIAllowed(final boolean onlineAIAllowed)
{
this.onlineAIAllowed = onlineAIAllowed;
}
public Thread repeatNetworkActionsThread()
{
return repeatNetworkActionsThread;
}
public void setRepeatNetworkActionsThread(final Thread repeatNetworkActionsThread)
{
this.repeatNetworkActionsThread = repeatNetworkActionsThread;
}
public int localStateMatchesDB()
{
return localStateMatchesDB;
}
public void setLocalStateMatchesDB(final int localStateMatchesDB)
{
this.localStateMatchesDB = localStateMatchesDB;
}
public AIDetails[] onlineBackupAiPlayers()
{
return onlineBackupAiPlayers;
}
public void setOnlineBackupAiPlayers(final AIDetails[] onlineBackupAiPlayers)
{
this.onlineBackupAiPlayers = onlineBackupAiPlayers;
}
public int[] playerTimeRemaining()
{
return playerTimeRemaining;
}
public void setPlayerTimeRemaining(final int[] playerTimeRemaining)
{
this.playerTimeRemaining = playerTimeRemaining;
}
public boolean loadingNetworkGame()
{
return loadingNetworkGame;
}
public void setLoadingNetworkGame(final boolean loadingNetworkGame)
{
this.loadingNetworkGame = loadingNetworkGame;
}
public boolean[] activePlayers()
{
return activePlayers;
}
public void setActivePlayers(final boolean[] activePlayers)
{
this.activePlayers = activePlayers;
}
public boolean[] onlinePlayers()
{
return onlinePlayers;
}
public void setOnlinePlayers(final boolean[] onlinePlayers)
{
this.onlinePlayers = onlinePlayers;
}
public boolean[] drawProposedPlayers()
{
return drawProposedPlayers;
}
public void setDrawProposedPlayers(final boolean[] drawProposedPlayers)
{
this.drawProposedPlayers = drawProposedPlayers;
}
public boolean longerNetworkPolling()
{
return longerNetworkPolling;
}
public void setLongerNetworkPolling(final boolean longer)
{
longerNetworkPolling = longer;
}
public boolean noNetworkRefresh()
{
return noNetworkRefresh;
}
public void setNoNetworkRefresh(final boolean no)
{
noNetworkRefresh = no;
}
public int lastServerTime()
{
return lastServerTime;
}
public void setLastServerTime(final int lastServerTime)
{
this.lastServerTime = lastServerTime;
}
public int secretPlayerNetworkNumber()
{
return secretPlayerNetworkNumber;
}
public void setSecretPlayerNetworkNumber(final int secretPlayerNetworkNumber)
{
this.secretPlayerNetworkNumber = secretPlayerNetworkNumber;
}
//-------------------------------------------------------------------------
}
| 9,098 | 23.007916 | 99 |
java
|
Ludii
|
Ludii-master/Manager/src/manager/network/local/LocalFunctions.java
|
package manager.network.local;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import game.rules.play.moves.Moves;
import manager.Manager;
import other.context.Context;
/**
* Local network functions that can be called by external agents using sockets.
* Messages are formatted as "XXXX ACTION EXTRA", where XXXX is the port number to return messages to, ACTION is the keyword for the desired task (see below), and EXTRA is any additional information.
* Example messages include:
* "5555 move 4" (make the 4th legal move)
* "5555 legal" (return all legal moves)
* "5555 player" (return the current mover)
*
* @author Matthew.Stephenson
*/
public class LocalFunctions
{
static ServerSocket serverSocket;
static Socket socket;
//-------------------------------------------------------------------------
/**
* Initialise the server socket and await messages.
*/
public static void initialiseServerSocket(final Manager manager, final int port)
{
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
serverSocket = new ServerSocket(port);
while (true)
{
// Establish connection.
socket = serverSocket.accept();
final DataInputStream dis = new DataInputStream(socket.getInputStream());
// Print any messages from socket.
final String message = dis.readUTF();
System.out.println("message= " + message);
// Reply string to respond to incoming messages.
String reply = "";
// Request about a move made.
if (message.length() >= 9 && message.substring(5, 9).equals("move"))
{
reply = "move failure";
final Context context = manager.ref().context();
final Moves legal = context.game().moves(context);
for (int i = 0; i < legal.moves().size(); i++)
{
if (i == Integer.parseInt(message.substring(10).trim()))
{
manager.ref().applyHumanMoveToGame(manager, context.game().moves(context).moves().get(i));
reply = "move success";
}
}
initialiseClientSocket(Integer.parseInt(message.substring(0,4)), reply);
}
// Request about legal moves.
else if (message.length() >= 10 && message.substring(5, 10).equals("legal"))
{
final Context context = manager.ref().context();
final Moves legal = context.game().moves(context);
for (int i = 0; i < legal.moves().size(); i++)
reply += i + " - " + legal.moves().get(i).getActionsWithConsequences(context) + "\n";
initialiseClientSocket(Integer.parseInt(message.substring(0,4)), "legal\n" + reply);
}
// Request about current mover.
else if (message.length() >= 11 && message.substring(5, 11).equals("player"))
{
reply = Integer.toString(manager.ref().context().state().mover());
initialiseClientSocket(Integer.parseInt(message.substring(0,4)), "player " + reply);
}
System.out.println("Reply= " + reply);
}
}
catch(final Exception e)
{
e.printStackTrace();
try
{
serverSocket.close();
socket.close();
}
catch (final IOException e1)
{
e1.printStackTrace();
}
}
}
}).start();
}
//-------------------------------------------------------------------------
/**
* Initialise the client socket when a message needs to be sent.
*/
public static void initialiseClientSocket(final int port, final String Message)
{
new Thread(new Runnable()
{
@Override
public void run()
{
try (final Socket clientSocket = new Socket("localhost",port))
{
try(final DataOutputStream dout = new DataOutputStream(clientSocket.getOutputStream()))
{
dout.writeUTF(Message);
dout.flush();
dout.close();
clientSocket.close();
}
catch(final Exception e)
{
e.printStackTrace();
}
}
catch(final Exception e)
{
e.printStackTrace();
}
}
}).start();
}
//-------------------------------------------------------------------------
}
| 4,236 | 28.020548 | 199 |
java
|
Ludii
|
Ludii-master/Manager/src/manager/network/local/RandomLocalAgent.java
|
package manager.network.local;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ThreadLocalRandom;
/**
* An example random agent that makes moves using the Ludii socket interface.
* Start a separate Ludii application, and select the Remote -> Initialise Server Socket menu option.
* Enter the same port number as specified below for the portNumberLudii variable.
* Now run this program.
* This agent will make a random move every time the turn number of the game being played equals the playerNumber variable below.
*
* @author Matthew.Stephenson
*/
public class RandomLocalAgent
{
// Change this based on your player number in the game.
static final int playerNumber = 2;
// Change this to the port number of the Ludii application.
static final int portNumberLudii = 4444;
// Change this to the port number used by the agent.
static final int portNumberAgent = 5555;
// Last recorded mover
static int currentPlayerNumber = 0;
// Last recorded legal moves
static String currentLegalMoves = "";
static ServerSocket serverSocket;
static Socket socket;
//-------------------------------------------------------------------------
/**
* Initialise the agent's own server socket, to receive incoming messages from the Ludii application.
* @param port
*/
public static void initialiseServerSocket(final int port)
{
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
serverSocket = new ServerSocket(port);
while (true)
{
// Establish connection.
socket = serverSocket.accept();
final DataInputStream dis = new DataInputStream(socket.getInputStream());
// Print any messages from socket.
final String message = dis.readUTF();
System.out.println("message= " + message);
// Request about legal moves.
if (message.substring(0,5).equals("legal"))
{
currentLegalMoves = message.substring(6);
}
// Request about current mover.
if (message.substring(0,6).equals("player"))
{
currentPlayerNumber = Integer.parseInt(message.substring(7));
}
}
}
catch(final Exception e)
{
e.printStackTrace();
try
{
serverSocket.close();
socket.close();
}
catch (final IOException e1)
{
e1.printStackTrace();
}
}
}
}).start();
}
//-------------------------------------------------------------------------
/**
* Sends the specified message to the specified port.
* @param port
* @param Message
*/
public static void initialiseClientSocket(final int port, final String Message)
{
try (final Socket clientSocket = new Socket("localhost",port))
{
try (final DataOutputStream dout = new DataOutputStream(clientSocket.getOutputStream()); )
{
dout.writeUTF(Message);
dout.flush();
dout.close();
clientSocket.close();
}
catch(final Exception e)
{
e.printStackTrace();
}
}
catch(final Exception e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Agent will continuously request the Ludii application for information, and make moves where appropriate.
* @param args
*/
public static void main(final String args[])
{
initialiseServerSocket(portNumberAgent);
// Update agent stored information (current mover, legal moves)
final Runnable runnableUpdateValues = new Runnable()
{
@Override
public void run()
{
while (true)
{
initialiseClientSocket(portNumberLudii, "" + portNumberAgent + " player");
initialiseClientSocket(portNumberLudii, "" + portNumberAgent + " legal");
try
{
Thread.sleep(10);
}
catch (final InterruptedException e)
{
// You probably logged out and the thread was interrupted.
}
}
}
};
final Thread repeatUpdateValuesThread = new Thread(runnableUpdateValues);
repeatUpdateValuesThread.start();
// If its the agent's turn, make a random move.
final long timeInterval = 100;
final Runnable runnableMakeMove = new Runnable()
{
@Override
public void run()
{
while (true)
{
if (playerNumber == currentPlayerNumber)
{
final String[] allLegalMoves = currentLegalMoves.split("\n");
final int randomNum = ThreadLocalRandom.current().nextInt(0, allLegalMoves.length);
initialiseClientSocket(portNumberLudii, "" + portNumberAgent + " move " + randomNum);
}
try
{
Thread.sleep(timeInterval);
}
catch (final InterruptedException e)
{
// You probably logged out and the thread was interrupted.
}
}
}
};
final Thread repeatMakeMoveThread = new Thread(runnableMakeMove);
repeatMakeMoveThread.start();
}
//-------------------------------------------------------------------------
}
| 5,052 | 25.73545 | 129 |
java
|
Ludii
|
Ludii-master/Manager/src/manager/utils/SettingsManager.java
|
package manager.utils;
import java.util.ArrayList;
import gnu.trove.map.hash.TObjectIntHashMap;
import main.Constants;
import main.collections.FastArrayList;
import main.options.UserSelections;
import manager.Manager;
import other.move.Move;
/**
* Settings used by the Manager Module.
*
* @author Matthew.Stephenson and cambolbro
*/
public final class SettingsManager
{
//-------------------------------------------------------------------------
// User settings
/** Visualize repetition moves */
private boolean showRepetitions = false;
/** Whether or not the agent(s) are paused. */
private boolean agentsPaused = true;
/** The time of a tick in simulation. */
private double tickLength = 0.1;
private boolean alwaysAutoPass = false;
private double minimumAgentThinkTime = 0.5;
//-------------------------------------------------------------------------
// Variables used for displaying repeated moves.
private ArrayList<Long> storedGameStatesForVisuals = new ArrayList<>();
private FastArrayList<Move> movesAllowedWithRepetition = new FastArrayList<>();
//-------------------------------------------------------------------------
// Variables used for multiple consequence selection.
/** List of possible consequence moves. */
private ArrayList<Move> possibleConsequenceMoves = new ArrayList<>();
//-------------------------------------------------------------------------
// Variables used for turn limits.
private TObjectIntHashMap<String> turnLimits = new TObjectIntHashMap<String>();
//-------------------------------------------------------------------------
/**
* User selections for options and rulesets within a game.
* When compiling a game, pass in a "dirty" copy of this object if you
* want the settings to be set to the game's defaults, otherwise the
* game will be compiled with the settings specified here.
*/
private final UserSelections userSelections = new UserSelections(new ArrayList<String>());
//-------------------------------------------------------------------------
// Getter and setters
public boolean showRepetitions()
{
return showRepetitions;
}
public void setShowRepetitions(final boolean show)
{
showRepetitions = show;
}
public double tickLength()
{
return tickLength;
}
public void setTickLength(final double length)
{
tickLength = length;
}
public ArrayList<Long> storedGameStatesForVisuals()
{
return storedGameStatesForVisuals;
}
public void setStoredGameStatesForVisuals(final ArrayList<Long> stored)
{
storedGameStatesForVisuals = stored;
}
public FastArrayList<Move> movesAllowedWithRepetition()
{
return movesAllowedWithRepetition;
}
public void setMovesAllowedWithRepetition(final FastArrayList<Move> moves)
{
movesAllowedWithRepetition = moves;
}
public ArrayList<Move> possibleConsequenceMoves()
{
return possibleConsequenceMoves;
}
public void setPossibleConsequenceMoves(final ArrayList<Move> possible)
{
possibleConsequenceMoves = possible;
}
public int turnLimit(final String gameName)
{
if (turnLimits.contains(gameName))
return turnLimits.get(gameName);
return Constants.DEFAULT_TURN_LIMIT;
}
public void setTurnLimit(final String gameName, final int turnLimit)
{
turnLimits.put(gameName, turnLimit);
}
public TObjectIntHashMap<String> turnLimits()
{
return turnLimits;
}
public void setTurnLimits(final TObjectIntHashMap<String> turnLimits)
{
this.turnLimits = turnLimits;
}
public boolean agentsPaused()
{
return agentsPaused;
}
public void setAgentsPaused(final Manager manager, final boolean paused)
{
agentsPaused = paused;
if (agentsPaused)
manager.ref().interruptAI(manager);
}
public UserSelections userSelections()
{
return userSelections;
}
public boolean alwaysAutoPass()
{
return alwaysAutoPass;
}
public void setAlwaysAutoPass(final boolean alwaysAutoPass)
{
this.alwaysAutoPass = alwaysAutoPass;
}
public double minimumAgentThinkTime()
{
return minimumAgentThinkTime;
}
public void setMinimumAgentThinkTime(double minimumAgentThinkTime)
{
this.minimumAgentThinkTime = minimumAgentThinkTime;
}
}
| 4,188 | 22.533708 | 91 |
java
|
Ludii
|
Ludii-master/Manager/src/manager/utils/game_logs/GameLogs.java
|
package manager.utils.game_logs;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.rng.core.RandomProviderDefaultState;
import game.Game;
import game.equipment.container.Container;
import other.state.State;
import other.state.container.ContainerState;
import other.trial.Trial;
/**
* A collection of one or more game trials which can be serialized and
* deserialized.
*
* @author Dennis Soemers
*/
public class GameLogs
{
/** */
private final String gameName;
/** */
private final Game game;
/** */
private final List<MatchRecord> matchRecords = new ArrayList<MatchRecord>();
//-------------------------------------------------------------------------
public GameLogs(final Game game)
{
gameName = game.name();
this.game = game;
}
//-------------------------------------------------------------------------
public void addMatchRecord(final MatchRecord matchRecord)
{
matchRecords.add(matchRecord);
}
public List<MatchRecord> matchRecords()
{
return matchRecords;
}
public Game game()
{
return game;
}
//-------------------------------------------------------------------------
public static GameLogs fromFile(final File file, final Game game)
{
GameLogs gameLogs = null;
try (ObjectInputStream reader = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(file))))
{
final String gameName = reader.readUTF();
//final Game game = PlayerCli.getGameInstance(gameName, nbRow, nbCol);
gameLogs = new GameLogs(game);
while (reader.available() > 0)
{
final int numRngStateBytes = reader.readInt();
final byte[] rngStateBytes = new byte[numRngStateBytes];
final int numBytesRead = reader.read(rngStateBytes);
if (numBytesRead != numRngStateBytes)
{
System.err.println
(
"Warning: GameLogs.fromFile() expected " + numRngStateBytes +
" bytes, but only read " + numBytesRead + " bytes!"
);
}
final RandomProviderDefaultState rngState = new RandomProviderDefaultState(rngStateBytes);
//System.out.println("loaded state = " + Arrays.toString(rngState.getState()));
final Trial trial = (Trial) reader.readObject();
final List<State> states = trial.auxilTrialData().stateHistory();
// fix reference to container for all ItemStates
if (states != null)
{
for (final State state : states)
{
final ContainerState[] itemStates = state.containerStates();
for (final ContainerState itemState : itemStates)
{
if (itemState != null)
{
final String containerName = itemState.nameFromFile();
for (final Container container : game.equipment().containers())
{
if (container != null && container.name().equals(containerName))
{
itemState.setContainer(container);
break;
}
}
}
}
}
}
gameLogs.addMatchRecord(new MatchRecord(trial, rngState, gameName));
}
}
catch (final IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
//System.out.println(gameLogs.matchRecords.get(0).trial.actions());
return gameLogs;
}
public String getGameName()
{
return gameName;
}
//-------------------------------------------------------------------------
}
| 3,513 | 23.068493 | 94 |
java
|
Ludii
|
Ludii-master/Manager/src/manager/utils/game_logs/MatchRecord.java
|
package manager.utils.game_logs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.rng.core.RandomProviderDefaultState;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.Status;
import main.Status.EndType;
import other.move.Move;
import other.trial.Trial;
/**
* A record of a single played Match (to be serialised/deserialised, typically as a collection
* in GameLogs)
*
* @author Dennis Soemers
*/
public class MatchRecord implements Serializable
{
/** */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** */
private final Trial trial;
/** */
private final RandomProviderDefaultState rngState;
//-------------------------------------------------------------------------
/**
* Constructor
* @param trial
* @param rngState
* @param loadedGameName
*/
public MatchRecord
(
final Trial trial,
final RandomProviderDefaultState rngState,
final String loadedGameName
)
{
this.trial = trial;
this.rngState = rngState;
}
//-------------------------------------------------------------------------
/**
* @return Reference to the current trial.
*/
public Trial trial()
{
return trial;
}
/**
* @return RNG state.
*/
public RandomProviderDefaultState rngState()
{
return rngState;
}
//-------------------------------------------------------------------------
/**
* Loads a MatchRecord from a text file
* @param file
* @param game
* @return The match record.
* @throws IOException
* @throws FileNotFoundException
*/
public static MatchRecord loadMatchRecordFromTextFile
(
final File file,
final Game game
) throws FileNotFoundException, IOException
{
try (final InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "UTF-8"))
{
return loadMatchRecordFromInputStream(reader, game);
}
}
/**
* Loads a MatchRecord from a text file
* @param inputStreamReader
* @param game
* @return The match record.
* @throws IOException
* @throws FileNotFoundException
*/
public static MatchRecord loadMatchRecordFromInputStream
(
final InputStreamReader inputStreamReader,
final Game game
) throws FileNotFoundException, IOException
{
try (final BufferedReader reader = new BufferedReader(inputStreamReader))
{
final String gameNameLine = reader.readLine();
final String loadedGameName = gameNameLine.substring("game=".length());
String nextLine = reader.readLine();
while (true)
{
if (nextLine == null)
break;
if (nextLine.startsWith("RNG internal state="))
break;
if (nextLine.startsWith("NEW LEGAL MOVES LIST"))
break;
if (nextLine.startsWith("winner="))
break;
if (nextLine.startsWith("rankings="))
break;
//if (!nextLine.startsWith("START GAME OPTIONS") && !nextLine.startsWith("END GAME OPTIONS"))
// Do nothing
nextLine = reader.readLine();
}
if (!nextLine.startsWith("RNG internal state="))
{
System.err.println("ERROR: MatchRecord::loadMatchRecordFromTextFile expected to read RNG internal state!");
return null;
}
final String rngInternalStateLine = nextLine;
final String[] byteStrings = rngInternalStateLine.substring("RNG internal state=".length()).split(Pattern.quote(","));
final byte[] bytes = new byte[byteStrings.length];
for (int i = 0; i < byteStrings.length; ++i)
bytes[i] = Byte.parseByte(byteStrings[i]);
final RandomProviderDefaultState rngState = new RandomProviderDefaultState(bytes);
final Trial trial = new Trial(game);
// now we expect to be reading played Moves
nextLine = reader.readLine();
while (true)
{
if (nextLine == null)
break;
if (!nextLine.startsWith("Move="))
break;
final Move move = new Move(nextLine.substring("Move=".length()));
trial.addMove(move);
nextLine = reader.readLine();
}
// now we expect to be reading sizes of histories of legal moves lists (if they were stored)
final TIntArrayList legalMovesHistorySizes = new TIntArrayList();
while (true)
{
if (nextLine == null)
break;
if (nextLine.startsWith("NEW LEGAL MOVES LIST"))
break;
if (nextLine.startsWith("winner="))
break;
if (nextLine.startsWith("rankings="))
break;
if (nextLine.startsWith("numInitialPlacementMoves="))
break;
if (nextLine.startsWith("LEGAL MOVES LIST SIZE = "))
legalMovesHistorySizes.add(Integer.parseInt(nextLine.substring("LEGAL MOVES LIST SIZE = ".length())));
nextLine = reader.readLine();
}
// now we expect to be reading sequences of legal moves (if they were stored)
final List<List<Move>> legalMovesHistory = new ArrayList<List<Move>>();
while (true)
{
if (nextLine == null)
break;
if (nextLine.startsWith("winner="))
break;
if (nextLine.startsWith("rankings="))
break;
if (nextLine.startsWith("numInitialPlacementMoves="))
break;
if (nextLine.equals("NEW LEGAL MOVES LIST"))
legalMovesHistory.add(new ArrayList<Move>());
else if (!nextLine.equals("END LEGAL MOVES LIST"))
legalMovesHistory.get(legalMovesHistory.size() - 1).add(new Move(nextLine));
nextLine = reader.readLine();
}
if (!legalMovesHistory.isEmpty())
{
trial.storeLegalMovesHistory();
trial.setLegalMovesHistory(legalMovesHistory);
}
if (!legalMovesHistorySizes.isEmpty())
{
trial.storeLegalMovesHistorySizes();
trial.setLegalMovesHistorySizes(legalMovesHistorySizes);
}
int winner = -99; // Not 100% sure that any of the nice constants are good enough, maybe used for losers in single-player games or something?
EndType endType = EndType.Unknown;
int numInitialPlacementMoves = 0;
if (nextLine != null && nextLine.startsWith("numInitialPlacementMoves="))
{
numInitialPlacementMoves = Integer.parseInt(nextLine.substring("numInitialPlacementMoves=".length()));
nextLine = reader.readLine();
}
if (nextLine != null && nextLine.startsWith("winner="))
{
winner = Integer.parseInt(nextLine.substring("winner=".length()));
nextLine = reader.readLine();
}
if (nextLine != null && nextLine.startsWith("endtype="))
{
endType = EndType.valueOf(nextLine.substring("endtype=".length()));
nextLine = reader.readLine();
}
trial.setNumInitialPlacementMoves(numInitialPlacementMoves);
if (winner > -99)
trial.setStatus(new Status(winner, endType));
if (nextLine != null && nextLine.startsWith("rankings="))
{
final String[] rankingStrings = nextLine.substring("rankings=".length()).split(Pattern.quote(","));
for (int i = 0; i < rankingStrings.length; ++i)
{
trial.ranking()[i] = Double.parseDouble(rankingStrings[i]);
}
}
return new MatchRecord(trial, rngState, loadedGameName);
}
}
//-------------------------------------------------------------------------
}
| 7,411 | 25.007018 | 144 |
java
|
Ludii
|
Ludii-master/Manager/src/tournament/Tournament.java
|
package tournament;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import game.Game;
import manager.Manager;
import manager.ai.AIUtil;
/**
* A Ludii Tournament
*
* @author Dennis Soemers and Matthew Stephenson and cambolbro
*/
public class Tournament
{
/** List of games we wish to play in tournament */
private final List<String> gamesToPlay;
/** List of agents to participate in tournament */
private final List<Object> agentsToPlay;
/** Results of tournament */
private final List<String[]> results;
private List<int[]> matchUps;
private int matchUpIndex;
private int[] matchUp;
//-------------------------------------------------------------------------
/**
* Constructor from JSON
* @param json
*/
public Tournament(final JSONObject json)
{
final JSONArray listGames = json.getJSONArray("GAMES");
gamesToPlay = new ArrayList<>(listGames.length());
System.out.println("Tournament games:");
for (final Object obj : listGames)
{
final String game = (String) obj;
gamesToPlay.add(game);
System.out.println(game);
}
final JSONArray listAgents = json.getJSONArray("AGENTS");
agentsToPlay = new ArrayList<>(listAgents.length());
System.out.println("Tournament agents:");
for (final Object obj : listAgents)
{
agentsToPlay.add(obj);
System.out.println(obj);
}
results = new ArrayList<>();
}
//-------------------------------------------------------------------------
/**
* Sets up the tournament for a (new) start
*/
public void setupTournament()
{
// reset the global tournament variables
results.clear();
final int totalNumberPlayers = agentsToPlay.size();
final List<int[]> matchUpsFlipped = generate(totalNumberPlayers, 2);
matchUps = generate(totalNumberPlayers, 2);
for (int j = 0; j < matchUps.size(); j++)
{
for (int i = 0; i < matchUps.get(j).length / 2; i++)
{
final int temp = matchUps.get(j)[i];
matchUps.get(j)[i] = matchUps.get(j)[matchUps.get(j).length - i - 1];
matchUps.get(j)[matchUps.get(j).length - i - 1] = temp;
}
}
matchUps.addAll(matchUpsFlipped);
matchUpIndex = 0;
}
/**
* Run the next game for the tournament
*/
public void startNextTournamentGame(final Manager manager)
{
if (gamesToPlay.size() > 0 && matchUps.size() > 0)
{
matchUp = matchUps.get(matchUpIndex);
for (int i = 0; i < matchUp.length; i++)
{
final Object agent = agentsToPlay.get(matchUp[i]);
final JSONObject json;
if (agent instanceof JSONObject)
json = (JSONObject) agent;
else
json = new JSONObject().put("AI", new JSONObject().put("algorithm", agent));
AIUtil.updateSelectedAI(manager, json, i + 1, json.getJSONObject("AI").getString("algorithm"));
}
final List<String> gameAndOptions = Arrays.asList(gamesToPlay.get(0).split("-"));
if (gameAndOptions.size() > 1)
{
System.out.println(gameAndOptions.get(1));
manager.getPlayerInterface().loadGameFromName(gameAndOptions.get(0).trim(), gameAndOptions.subList(1, gameAndOptions.size()), false);
}
else
{
manager.getPlayerInterface().loadGameFromName(gameAndOptions.get(0).trim(), new ArrayList<String>(), false);
}
matchUpIndex++;
if (matchUpIndex >= matchUps.size())
{
matchUpIndex = 0;
gamesToPlay.remove(0);
}
manager.settingsManager().setAgentsPaused(manager, false);
manager.ref().nextMove(manager, false);
}
else
{
// The tournament is over, show the results
System.out.println("FINAL RESULTS SHORT");
// String finalResultsToSend = "FINAL RESULTS SHORT";
for (int i = 0; i < results.size(); i++)
{
final String result = Arrays.toString(results.get(i));
System.out.println(result);
// finalResultsToSend += result;
}
System.out.println("\nFINAL RESULTS LONG");
// finalResultsToSend += "FINAL RESULTS LONG";
for (int i = 0; i < results.size(); i++)
{
final String gameData = "GAME(" + (i + 1) + ") " + results.get(i)[0];
System.out.println(gameData);
// finalResultsToSend += gameData;
try
{
for (int j = 0; j < results.get(i)[1].length(); j++)
{
final String result = "Player "
+ (Integer.parseInt(results.get(i)[1].split(",")[j].replace("[", "")
.replace("]", "").trim()) + 1)
+ " : " + results.get(i)[j + 2];
System.out.println(result);
// finalResultsToSend += result;
}
}
catch (final Exception e)
{
// just skip the players that don't have scores
}
}
}
}
/**
* Storse the results obtained in a single match
*
* @param game
* @param ranking
*/
public void storeResults(final Game game, final double[] ranking)
{
final String[] result = new String[10];
try
{
result[0] = game.name();
result[1] = Arrays.toString(matchUp);
result[2] = Double.toString(ranking[1]);
result[3] = Double.toString(ranking[2]);
result[4] = Double.toString(ranking[3]);
result[5] = Double.toString(ranking[4]);
result[6] = Double.toString(ranking[5]);
result[7] = Double.toString(ranking[6]);
result[8] = Double.toString(ranking[7]);
result[9] = Double.toString(ranking[8]);
}
catch (final Exception E)
{
// player number requested probably doesn't exist, carry on as normal
}
results.add(result);
}
/**
* Called when the tournament is being aborted / ended
*/
public void endTournament()
{
// Do nothing (for now)
}
//-------------------------------------------------------------------------
/**
* generates all nCr combinations (all round robin tournament combinations)
*/
private static List<int[]> generate(final int n, final int r)
{
final List<int[]> combinations = new ArrayList<>();
final int[] combination = new int[r];
// initialize with lowest lexicographic combination
for (int i = 0; i < r; i++)
{
combination[i] = i;
}
while (combination[r - 1] < n)
{
combinations.add(combination.clone());
// generate next combination in lexicographic order
int t = r - 1;
while (t != 0 && combination[t] == n - r + t)
{
t--;
}
combination[t]++;
for (int i = t + 1; i < r; i++)
{
combination[i] = combination[i - 1] + 1;
}
}
return combinations;
}
}
| 6,317 | 23.874016 | 137 |
java
|
Ludii
|
Ludii-master/Manager/src/tournament/TournamentUtil.java
|
package tournament;
import java.awt.EventQueue;
import manager.Manager;
import other.context.Context;
/**
* Ludii Tournament util functions
*
* @author Dennis Soemers and Matthew Stephenson
*/
public class TournamentUtil
{
/**
* If Tournament is running then need to save the results of this game.
*/
public static void saveTournamentResults(final Manager manager, final Context context)
{
if (manager.tournament() != null)
{
System.out.println("SAVING RESULTS");
manager.tournament().storeResults(context.game(), context.trial().ranking());
new java.util.Timer().schedule(
new java.util.TimerTask()
{
@Override
public void run()
{
EventQueue.invokeLater(() ->
{
System.out.println("LOADING NEXT GAME");
manager.tournament().startNextTournamentGame(manager);
});
}
},
5000L
);
}
}
//-------------------------------------------------------------------------
}
| 1,063 | 22.130435 | 87 |
java
|
Ludii
|
Ludii-master/Mining/src/agentPrediction/external/AgentPredictionExternal.java
|
package agentPrediction.external;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import game.Game;
import manager.ai.AIRegistry;
import metrics.Evaluation;
import other.concept.Concept;
import other.concept.ConceptComputationType;
import other.concept.ConceptDataType;
import utils.AIUtils;
import utils.concepts.ComputePlayoutConcepts;
/**
* Predict the best agent/heuristic using external Python models.
*
* Models are produced by the "generate_agent_heuristic_prediction_models()" function in the Sklearn "Main.py" file.
*
* @author Matthew.Stephenson
*/
public class AgentPredictionExternal
{
/**
* Predict the best agent/heuristic using external Python models.
* @param game
* @param modelFilePath
* @param classificationModel
* @param heuristics
* @param compilationOnly
*/
public static Map<String,Double> predictBestAgent(final Game game, final String modelFilePath, final boolean classificationModel, final boolean heuristics, final boolean compilationOnly)
{
final long startTime = System.currentTimeMillis();
if (!compilationOnly)
ComputePlayoutConcepts.updateGame(game, new Evaluation(), 10, -1, 1, "Random", true);
else
ComputePlayoutConcepts.updateGame(game, new Evaluation(), 0, -1, 1, "Random", true); // Still need to run this with zero trials to get compilation concepts
final double ms = (System.currentTimeMillis() - startTime);
System.out.println("Playouts computation done in " + ms + " ms.");
List<String> allModelNames = AIRegistry.generateValidAgentNames(game);
if (heuristics)
allModelNames = Arrays.asList(AIUtils.allHeuristicNames());
return AgentPredictionExternal.predictBestAgentName(game, allModelNames, modelFilePath, classificationModel, compilationOnly);
}
//-------------------------------------------------------------------------
/**
* @return Name of the best predicted agent from our pre-trained set of models.
*/
public static Map<String,Double> predictBestAgentName(final Game game, final List<String> allValidLabelNames, final String modelFilePath, final boolean classificationModel, final boolean compilationOnly)
{
final Map<String, Double> agentPredictions = new HashMap<>();
String sInput = null;
String sError = null;
try
{
final String conceptNameString = "RulesetName," + conceptNameString(compilationOnly);
final String conceptValueString = "UNUSED," + conceptValueString(game, compilationOnly);
// Classification prediction, just the agent name or probability for each.
if (classificationModel)
{
final String arg1 = modelFilePath;
final String arg2 = "Classification";
final String arg3 = conceptNameString;
final String arg4 = conceptValueString;
final Process p = Runtime.getRuntime().exec("python3 ../../LudiiPrivate/DataMiningScripts/Sklearn/External/GetBestPredictedAgent.py " + arg1 + " " + arg2 + " " + arg3 + " " + arg4);
// Read file output
final BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((sInput = stdInput.readLine()) != null)
{
System.out.println(sInput);
if (sInput.contains("PREDICTION"))
{
// Check if returning probabilities for each class.
try
{
final String[] classNamesAndProbas = sInput.split("=")[1].split("_:_");
final String[] classNames = classNamesAndProbas[0].split("_;_");
for (int i = 0; i < classNames.length; i++)
classNames[i] = classNames[i];
final String[] valueStrings = classNamesAndProbas[1].split("_;_");
final Double[] values = new Double[valueStrings.length];
for (int i = 0; i < valueStrings.length; i++)
values[i] = Double.valueOf(valueStrings[i]);
if (classNames.length != values.length)
System.out.println("ERROR! Class Names and Values should be the same length.");
for (int i = 0; i < classNames.length; i++)
{
agentPredictions.put(classNames[i], values[i]);
}
return agentPredictions;
}
catch (final Exception e)
{
e.printStackTrace();
}
}
}
// Read any errors.
final BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((sError = stdError.readLine()) != null)
{
System.out.println("Python Error\n");
System.out.println(sError);
}
}
// Regression prediction, get the predicted value for each valid agent.
else
{
// Record the predicted value for each agent.
for (final String agentName : allValidLabelNames)
{
final String arg1 = modelFilePath;
final String arg2 = agentName.replaceAll(" ", "_");
final String arg3 = conceptNameString;
final String arg4 = conceptValueString;
final Process p = Runtime.getRuntime().exec("python3 ../../LudiiPrivate/DataMiningScripts/Sklearn/External/GetBestPredictedAgent.py " + arg1 + " " + arg2 + " " + arg3 + " " + arg4);
// Read file output
final BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println("Predicting for " + agentName);
while ((sInput = stdInput.readLine()) != null)
{
System.out.println(sInput);
if (sInput.contains("PREDICTION"))
{
final Double predictedValue = Double.valueOf(sInput.split("=")[1]);
agentPredictions.put(agentName, predictedValue);
}
}
// Read any errors.
final BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((sError = stdError.readLine()) != null)
{
System.out.println("Python Error\n");
System.out.println(sError);
}
}
return agentPredictions;
}
}
catch (final IOException e)
{
e.printStackTrace();
}
return agentPredictions;
}
//-------------------------------------------------------------------------
public static Map<String, Map<String,Double>> predictPortfolioParameters(final Game game)
{
final Map<String, Map<String,Double>> portfolioParameterPredictions = new HashMap<>();
final String[] portfolioParameters = {"Heuristics", "Agents", "Selections", "Explorations", "Playouts", "Backpropagations"};
ComputePlayoutConcepts.updateGame(game, new Evaluation(), 0, -1, 1, "Random", true); // Still need to run this with zero trials to get compilation concepts
for (final String param : portfolioParameters)
{
final Map<String,Double> paramPredictions = new HashMap<>();
String sInput = null;
String sError = null;
try
{
final String conceptNameString = "RulesetName," + conceptNameString(true);
final String conceptValueString = "UNUSED," + conceptValueString(game, true);
final String arg1 = "RandomForestClassifier-Classification-" + param + "-Portfolio";
final String arg2 = "Classification";
final String arg3 = conceptNameString;
final String arg4 = conceptValueString;
final Process p = Runtime.getRuntime().exec("python3 ../../LudiiPrivate/DataMiningScripts/Sklearn/External/GetBestPredictedAgent.py " + arg1 + " " + arg2 + " " + arg3 + " " + arg4);
// Read file output
final BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((sInput = stdInput.readLine()) != null)
{
System.out.println(sInput);
if (sInput.contains("PREDICTION"))
{
// Check if returning probabilities for each class.
try
{
final String[] classNamesAndProbas = sInput.split("=")[1].split("_:_");
final String[] classNames = classNamesAndProbas[0].split("_;_");
for (int i = 0; i < classNames.length; i++)
classNames[i] = classNames[i];
final String[] valueStrings = classNamesAndProbas[1].split("_;_");
final Double[] values = new Double[valueStrings.length];
for (int i = 0; i < valueStrings.length; i++)
values[i] = Double.valueOf(valueStrings[i]);
if (classNames.length != values.length)
System.out.println("ERROR! Class Names and Values should be the same length.");
for (int i = 0; i < classNames.length; i++)
{
paramPredictions.put(classNames[i], values[i]);
}
continue;
}
catch (final Exception e)
{
e.printStackTrace();
}
}
}
// Read any errors.
final BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((sError = stdError.readLine()) != null)
{
System.out.println("Python Error\n");
System.out.println(sError);
}
}
catch (final IOException e)
{
e.printStackTrace();
}
portfolioParameterPredictions.put(param, paramPredictions);
}
return portfolioParameterPredictions;
}
//-------------------------------------------------------------------------
/**
* @return The concepts as a string with comma between them.
*/
public static String conceptNameString(final boolean compilationOnly)
{
final Concept[] concepts = compilationOnly ? Concept.values() : Concept.portfolioConcepts();
final StringBuffer sb = new StringBuffer();
for (final Concept concept: concepts)
if (!compilationOnly || concept.computationType().equals(ConceptComputationType.Compilation))
sb.append(concept.name()+",");
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* @param game The game compiled.
* @return The concepts as boolean values with comma between them.
*/
public static String conceptValueString(final Game game, final boolean compilationOnly)
{
final Concept[] concepts = compilationOnly ? Concept.values() : Concept.portfolioConcepts();
final StringBuffer sb = new StringBuffer();
for (final Concept concept: concepts)
if (!compilationOnly || concept.computationType().equals(ConceptComputationType.Compilation))
if (concept.dataType().equals(ConceptDataType.BooleanData))
sb.append((game.booleanConcepts().get(concept.id()) ? "1" : "0")).append(",");
else
sb.append((game.nonBooleanConcepts().get(Integer.valueOf(concept.id())))).append(",");
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* @param modelName should be the name of the model to use (same as from GUI), e.g. "BayesianRidge"
* @param useClassifier
* @param useHeuristics
* @param useCompilationOnly
*/
public static String getModelPath(final String modelName, final boolean useClassifier, final boolean useHeuristics, final boolean useCompilationOnly)
{
String modelFilePath = modelName;
if (useClassifier)
modelFilePath += "-Classification";
else
modelFilePath += "-Regression";
if (useHeuristics)
modelFilePath += "-Heuristics";
else
modelFilePath += "-Agents";
if (useCompilationOnly)
modelFilePath += "-True";
else
modelFilePath += "-False";
return modelFilePath;
}
//-------------------------------------------------------------------------
// public static void updateAgent()
// {
// if (!heuristics)
// {
// if (playerIndexToUpdate > 0)
// {
// final JSONObject json = new JSONObject().put("AI",
// new JSONObject()
// .put("algorithm", bestPredictedAgentName)
// );
//
// AIUtil.updateSelectedAI(manager, json, playerIndexToUpdate, bestPredictedAgentName);
// }
// }
// else
// {
// if (manager.aiSelected()[playerIndexToUpdate].ai() != null)
// {
// final Heuristics heuristic = AIUtils.convertStringtoHeuristic(bestPredictedAgentName);
// manager.aiSelected()[playerIndexToUpdate].ai().setHeuristics(heuristic);
// manager.aiSelected()[playerIndexToUpdate].ai().initAI(manager.ref().context().game(), playerIndexToUpdate);
// }
// }
// }
//-------------------------------------------------------------------------
}
| 13,513 | 38.171014 | 204 |
java
|
Ludii
|
Ludii-master/Mining/src/agentPrediction/external/MetricPredictionExternal.java
|
package agentPrediction.external;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import game.Game;
import metrics.Evaluation;
import utils.concepts.ComputePlayoutConcepts;
public class MetricPredictionExternal
{
/**
* Predict the values for each metric using external Python models.
* @param game
* @param modelFilePath
* @param compilationOnly
*/
public static Map<String,Double> predictMetrics(final Game game, final String modelFilePath, final boolean compilationOnly)
{
final long startTime = System.currentTimeMillis();
if (!compilationOnly)
ComputePlayoutConcepts.updateGame(game, new Evaluation(), 10, -1, 1, "Random", true);
else
ComputePlayoutConcepts.updateGame(game, new Evaluation(), 0, -1, 1, "Random", true); // Still need to run this with zero trials to get compilation concepts
final double ms = (System.currentTimeMillis() - startTime);
System.out.println("Playouts computation done in " + ms + " ms.");
final List<String> allMetricNames = new ArrayList<>();
final File folder = new File("../../LudiiPrivate/DataMiningScripts/Sklearn/res/trainedModels/" + modelFilePath);
final File[] listOfFiles = folder.listFiles();
for (final File file : listOfFiles)
allMetricNames.add(file.getName());
return AgentPredictionExternal.predictBestAgentName(game, allMetricNames, modelFilePath, false, compilationOnly);
}
//-------------------------------------------------------------------------
}
| 1,512 | 32.622222 | 158 |
java
|
Ludii
|
Ludii-master/Mining/src/agentPrediction/internal/AgentPredictionInternal.java
|
package agentPrediction.internal;
import java.util.ArrayList;
import java.util.List;
import agentPrediction.internal.models.BaseModel;
import gnu.trove.list.array.TIntArrayList;
import manager.Manager;
import other.concept.Concept;
public class AgentPredictionInternal
{
//-------------------------------------------------------------------------
/**
* Predicts the best AI, from a given prediction model.
*/
public static void predictAI(final Manager manager, final BaseModel predictionModel)
{
manager.getPlayerInterface().selectAnalysisTab();
final String[] agentStrings = {"AlphaBeta", "MC-GRAVE", "Random", "UCT"};
// Record all the concept Names and Values
final List<String> flags = new ArrayList<String>();
final TIntArrayList flagsValues = new TIntArrayList();
for (final Concept concept : Concept.values())
{
flags.add(concept.name());
flagsValues.add(concept.id());
}
// Calculate the predicted score for each agent.
final double[] agentPredictions = predictionModel.predictAI(manager, flags, flagsValues, agentStrings);
// Give best agent prediction.
double bestAgentScore = -999999999;
String bestAgentName = "None";
for (int agentIndex = 0; agentIndex < agentStrings.length; agentIndex++)
{
if (agentPredictions[agentIndex] > bestAgentScore)
{
bestAgentScore = agentPredictions[agentIndex];
bestAgentName = agentStrings[agentIndex];
}
manager.getPlayerInterface().addTextToAnalysisPanel("Predicted win-rate for " + agentStrings[agentIndex] + ": " + agentPredictions[agentIndex] + "\n");
}
manager.getPlayerInterface().addTextToAnalysisPanel("Best predicted agent is " + bestAgentName + "\n");
manager.getPlayerInterface().addTextToAnalysisPanel("//-------------------------------------------------------------------------\n");
}
//-------------------------------------------------------------------------
}
| 1,916 | 33.232143 | 154 |
java
|
Ludii
|
Ludii-master/Mining/src/agentPrediction/internal/models/BaseModel.java
|
package agentPrediction.internal.models;
import java.util.List;
import gnu.trove.list.array.TIntArrayList;
import manager.Manager;
public interface BaseModel
{
/** The name of the model used, must match up with the filepath to the stored model. */
String modelName();
/** Returns the predicted win-rate for each agent in agentStrings, based on the game concepts. */
double[] predictAI(final Manager manager, List<String> flags, TIntArrayList flagsValues, String[] agentStrings);
}
| 491 | 27.941176 | 113 |
java
|
Ludii
|
Ludii-master/Mining/src/agentPrediction/internal/models/LinearRegression.java
|
package agentPrediction.internal.models;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import gnu.trove.list.array.TIntArrayList;
import manager.Manager;
public class LinearRegression implements BaseModel
{
//-------------------------------------------------------------------------
@Override
public String modelName()
{
return "LinearRegression";
}
//-------------------------------------------------------------------------
@Override
public double[] predictAI(final Manager manager, final List<String> flags, final TIntArrayList flagsValues, final String[] agentStrings)
{
final double[] agentPredictions = {0.0, 0.0, 0.0, 0.0};
for (int agentIndex = 0; agentIndex < agentStrings.length; agentIndex++)
{
double predictedScore = 0;
// Open CSV, and record all the values.
final Map<String, Double> entries = new HashMap<String, Double>();
// Load the csv model file.
final String filePath = "/predictionModels/" + modelName() + "/" + agentStrings[agentIndex] + ".csv";
System.out.println(filePath);
final InputStream in = LinearRegression.class.getResourceAsStream(filePath);
if (in != null)
{
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")))
{
for (String line; (line = reader.readLine()) != null; /**/)
{
final String[] lineSplit = line.split(Pattern.quote(","));
if (lineSplit.length > 1)
entries.put(lineSplit[1], Double.valueOf(lineSplit[0]));
else
predictedScore = Double.valueOf(lineSplit[0]).doubleValue();
}
}
catch (final IOException e)
{
e.printStackTrace();
}
// Calculate the score for this agent.
for (final Map.Entry<String,Double> entry : entries.entrySet())
{
for (int i = 0; i < flags.size(); i++)
{
if (flags.get(i).equals(entry.getKey()))
{
final int flagIndex = flagsValues.get(i);
final int flagValue = manager.ref().context().game().booleanConcepts().get(flagIndex) ? 1 : 0;
predictedScore += entry.getValue().doubleValue() * flagValue;
break;
}
}
}
}
else
{
System.out.println("Failed to load agent prediction CSV for " + modelName() + ", " + agentStrings[agentIndex]);
}
agentPredictions[agentIndex] = predictedScore;
}
return agentPredictions;
}
//-------------------------------------------------------------------------
}
| 2,631 | 27.608696 | 138 |
java
|
Ludii
|
Ludii-master/Mining/src/cluster/ConceptAverageValue.java
|
package cluster;
import other.concept.Concept;
/**
* A concept associated with a value.
* Used to sort a list.
* @author Eric.Piette
*
*/
public class ConceptAverageValue
{
/**
* The concept.
*/
final Concept concept;
/**
* The value associated with the concept.
*/
final double value;
public ConceptAverageValue(
final Concept concept,
final double value
)
{
this.concept = concept;
this.value = value;
}
}
| 447 | 12.575758 | 42 |
java
|
Ludii
|
Ludii-master/Mining/src/cluster/ConceptsComparaisonClusters.java
|
package cluster;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.options.Ruleset;
import other.GameLoader;
import other.concept.Concept;
import other.concept.ConceptComputationType;
import other.concept.ConceptDataType;
import other.concept.ConceptType;
import utils.RulesetNames;
/**
* Generate the percentage of concepts from a list of rulesets.
* @author Eric.Piette
*
*/
public class ConceptsComparaisonClusters
{
final static String pathFile = "./res/cluster/input/clusters/";
final static String csv = ".csv";
final static String outputConcept = "ConceptsForCluster.csv";
/**
* Main method to call the reconstruction with command lines.
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
@SuppressWarnings("boxing")
public static void main(final String[] args) throws FileNotFoundException, IOException
{
final String[] clusters = {"Cluster1.1", "Cluster1.2", "Cluster1.3", "Cluster1.4", "Cluster1.5", "Cluster1.6",
"Cluster2.1", "Cluster2.2", "Cluster2.3", "Cluster2.4", "Cluster2.5", "Cluster2.6", "Cluster2.7", "Cluster2.8",
"Cluster3.1", "Cluster3.2", "Cluster3.3", "Cluster3.4", "Cluster3.5", "Cluster3.6",
"Cluster3.7", "Cluster3.8", "Cluster3.9", "Cluster3.10", "Cluster3.11", "Cluster3.12",
"Cluster4"};
// final String[] clusters = {"Cluster1.1", "Cluster1.2"};
final List<List<ConceptAverageValue>> results = new ArrayList<List<ConceptAverageValue>>();
// Get the list of the right concepts.
final List<Concept> concepts = new ArrayList<Concept>();
for(Concept concept: Concept.values())
{
if((concept.type().equals(ConceptType.Start) || concept.type().equals(ConceptType.End) || concept.type().equals(ConceptType.Play)
|| concept.type().equals(ConceptType.Meta)|| concept.type().equals(ConceptType.Container)|| concept.type().equals(ConceptType.Component))
&& (concept.computationType().equals(ConceptComputationType.Compilation))
)
{
concepts.add(concept);
}
}
try (final PrintWriter writer = new UnixPrintWriter(new File(outputConcept), "UTF-8"))
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add("");
for(String clusterName : clusters)
lineToWrite.add(clusterName);
writer.println(StringRoutines.join(",", lineToWrite));
int numConcepts = 0;
for(String clusterName : clusters)
{
// Get the list of ruleset names.
final List<String> rulesetNames = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(pathFile + clusterName + csv)))
{
String line = br.readLine();
while (line != null)
{
rulesetNames.add(line);
line = br.readLine();
}
}
// Conversion to Game object
final List<Game> rulesetsCompiled = new ArrayList<Game>();
final String[] gameNames = FileHandling.listGames();
for (int index = 0; index < gameNames.length; index++)
{
final String gameName = gameNames[index];
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("subgame"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction"))
continue;
final Game game = GameLoader.loadGameFromName(gameName);
final List<Ruleset> rulesetsInGame = game.description().rulesets();
// Get all the rulesets of the game if it has some.
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
if (!ruleset.optionSettings().isEmpty() && !ruleset.heading().contains("Incomplete"))
{
final Game gameRuleset = GameLoader.loadGameFromName(gameName, ruleset.heading());
final String rulesetName = RulesetNames.gameRulesetName(gameRuleset);
if(rulesetNames.contains(rulesetName))
rulesetsCompiled.add(gameRuleset);
}
}
}
else
{
final String rulesetName = RulesetNames.gameRulesetName(game);
if(rulesetNames.contains(rulesetName))
rulesetsCompiled.add(game);
}
}
System.out.println(clusterName);
System.out.println("Num compiled rulesets is " + rulesetsCompiled.size());
System.out.println("*****************************");
// for(Game gameRuleset: rulesetsCompiled)
// System.out.println(RulesetNames.gameRulesetName(gameRuleset));
final List<ConceptAverageValue> conceptAverageValues = new ArrayList<ConceptAverageValue>();
// Check boolean concepts
for(Concept concept: concepts)
{
if(concept.dataType().equals(ConceptDataType.BooleanData))
{
int count = 0;
for(Game gameRuleset: rulesetsCompiled)
if(gameRuleset.booleanConcepts().get(concept.id()))
count++;
final double average = ((double) count * 100) / rulesetsCompiled.size();
final ConceptAverageValue conceptAverageValue = new ConceptAverageValue(concept, average);
conceptAverageValues.add(conceptAverageValue);
}
}
// booleanConceptAverageValues.sort((c1, c2) -> { return (c2.value - c1.value) > 0 ? 1 : (c2.value - c1.value) < 0 ? -1 : 0;});
// Check numerical concepts
for(Concept concept: concepts)
{
if(concept.dataType().equals(ConceptDataType.IntegerData) || concept.dataType().equals(ConceptDataType.IntegerData))
{
int count = 0;
for(Game gameRuleset: rulesetsCompiled)
if(gameRuleset.nonBooleanConcepts().get(concept.id()) != null)
count += Double.parseDouble(gameRuleset.nonBooleanConcepts().get(concept.id()));
final double average = (double) count / (double) rulesetsCompiled.size();
final ConceptAverageValue conceptAverageValue = new ConceptAverageValue(concept, average);
conceptAverageValues.add(conceptAverageValue);
}
}
numConcepts = conceptAverageValues.size();
results.add(conceptAverageValues);
System.out.println(clusterName + " Average concepts computed");
// numericalConceptAverageValues.sort((c1, c2) -> { return (c2.value - c1.value) > 0 ? 1 : (c2.value - c1.value) < 0 ? -1 : 0;});
}
for(int i = 0; i < numConcepts; i++)
{
final List<String> lineToWriteConcept = new ArrayList<String>();
lineToWriteConcept.add(results.get(0).get(i).concept.name());
for(List<ConceptAverageValue> conceptAverage : results)
lineToWriteConcept.add(""+conceptAverage.get(i).value);
writer.println(StringRoutines.join(",", lineToWriteConcept));
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
System.out.println("Done.");
}
}
| 7,490 | 35.014423 | 142 |
java
|
Ludii
|
Ludii-master/Mining/src/cluster/ConceptsFromCluster.java
|
package cluster;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.FileHandling;
import main.options.Ruleset;
import other.GameLoader;
import other.concept.Concept;
import other.concept.ConceptDataType;
import other.concept.ConceptType;
import utils.RulesetNames;
/**
* Generate the percentage of concepts from a list of rulesets.
* @author Eric.Piette
*
*/
public class ConceptsFromCluster
{
final static String listRulesets = "./res/cluster/input/clusters/Cluster4.csv";
final static String nameCluster = "Cluster 4";
/**
* Main method to call the reconstruction with command lines.
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
@SuppressWarnings("boxing")
public static void main(final String[] args) throws FileNotFoundException, IOException
{
// Get the list of ruleset names.
final List<String> rulesetNames = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(listRulesets)))
{
String line = br.readLine();
while (line != null)
{
rulesetNames.add(line);
line = br.readLine();
}
}
// Conversion to Game object
final List<Game> rulesetsCompiled = new ArrayList<Game>();
final String[] gameNames = FileHandling.listGames();
for (int index = 0; index < gameNames.length; index++)
{
final String gameName = gameNames[index];
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("subgame"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction"))
continue;
final Game game = GameLoader.loadGameFromName(gameName);
final List<Ruleset> rulesetsInGame = game.description().rulesets();
// Get all the rulesets of the game if it has some.
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
if (!ruleset.optionSettings().isEmpty() && !ruleset.heading().contains("Incomplete"))
{
final Game gameRuleset = GameLoader.loadGameFromName(gameName, ruleset.heading());
final String rulesetName = RulesetNames.gameRulesetName(gameRuleset);
if(rulesetNames.contains(rulesetName))
rulesetsCompiled.add(gameRuleset);
}
}
}
else
{
final String rulesetName = RulesetNames.gameRulesetName(game);
if(rulesetNames.contains(rulesetName))
rulesetsCompiled.add(game);
}
}
System.out.println(nameCluster);
System.out.println("Num compiled rulesets is " + rulesetsCompiled.size());
System.out.println("*****************************");
// for(Game gameRuleset: rulesetsCompiled)
// System.out.println(RulesetNames.gameRulesetName(gameRuleset));
final List<Concept> concepts = new ArrayList<Concept>();
for(Concept concept: Concept.values())
{
if(concept.type().equals(ConceptType.Start) || concept.type().equals(ConceptType.End) || concept.type().equals(ConceptType.Play)
|| concept.type().equals(ConceptType.Meta)|| concept.type().equals(ConceptType.Container)|| concept.type().equals(ConceptType.Component)
)
{
concepts.add(concept);
}
}
System.out.println("\n\n***Boolean concepts in average***\n");
final List<ConceptAverageValue> booleanConceptAverageValues = new ArrayList<ConceptAverageValue>();
// Check boolean concepts
for(Concept concept: concepts)
{
if(concept.dataType().equals(ConceptDataType.BooleanData))
{
int count = 0;
for(Game gameRuleset: rulesetsCompiled)
if(gameRuleset.booleanConcepts().get(concept.id()))
count++;
final double average = ((double) count * 100) / rulesetsCompiled.size();
final ConceptAverageValue conceptAverageValue = new ConceptAverageValue(concept, average);
booleanConceptAverageValues.add(conceptAverageValue);
}
}
booleanConceptAverageValues.sort((c1, c2) -> { return (c2.value - c1.value) > 0 ? 1 : (c2.value - c1.value) < 0 ? -1 : 0;});
for(ConceptAverageValue concept : booleanConceptAverageValues)
System.out.println(concept.concept.name() + "," + concept.value);
System.out.println("\n\n***Numerical concepts in average***\n");
final List<ConceptAverageValue> numericalConceptAverageValues = new ArrayList<ConceptAverageValue>();
// Check numerical concepts
for(Concept concept: concepts)
{
if(concept.dataType().equals(ConceptDataType.IntegerData))
{
int count = 0;
for(Game gameRuleset: rulesetsCompiled)
if(gameRuleset.nonBooleanConcepts().get(concept.id()) != null)
count += Double.parseDouble(gameRuleset.nonBooleanConcepts().get(concept.id()));
final double average = (double) count / (double) rulesetsCompiled.size();
final ConceptAverageValue conceptAverageValue = new ConceptAverageValue(concept, average);
numericalConceptAverageValues.add(conceptAverageValue);
}
if(concept.dataType().equals(ConceptDataType.DoubleData))
{
double count = 0;
for(Game gameRuleset: rulesetsCompiled)
if(gameRuleset.nonBooleanConcepts().get(concept.id()) != null)
count += Double.parseDouble(gameRuleset.nonBooleanConcepts().get(concept.id()));
final double average = count / rulesetsCompiled.size();
final ConceptAverageValue conceptAverageValue = new ConceptAverageValue(concept, average);
numericalConceptAverageValues.add(conceptAverageValue);
}
}
numericalConceptAverageValues.sort((c1, c2) -> { return (c2.value - c1.value) > 0 ? 1 : (c2.value - c1.value) < 0 ? -1 : 0;});
for(ConceptAverageValue concept : numericalConceptAverageValues)
System.out.println(concept.concept.name() + "," + concept.value);
}
}
| 6,240 | 34.061798 | 141 |
java
|
Ludii
|
Ludii-master/Mining/src/cluster/GenerateClusters.java
|
package cluster;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Generate the clusters based on the coordinates obtained with Sklearn.
* @author Eric.Piette
*
*/
public class GenerateClusters
{
// Coordinates of the 4 main clusters
// final static int numClusters = 4;
// // Cluster 1 area
// final static int xMinCluster1 = -50;
// final static int xMaxCluster1 = 0;
// final static int yMinCluster1 = -40;
// final static int yMaxCluster1 = 20;
//
// // Cluster 2 area
// final static int xMinCluster2 = -30;
// final static int xMaxCluster2 = 10;
// final static int yMinCluster2 = 20;
// final static int yMaxCluster2 = 50;
//
// // Cluster 3 area
// final static int xMinCluster3 = 0;
// final static int xMaxCluster3 = 40;
// final static int yMinCluster3 = -30;
// final static int yMaxCluster3 = 20;
//
// // Cluster 4 area
// final static int xMinCluster4 = 40;
// final static int xMaxCluster4 = 70;
// final static int yMinCluster4 = -40;
// final static int yMaxCluster4 = 10;
// Coordinates of the 4 sub-clusters of Cluster 1
// final static String coordinatesPath = "./res/cluster/input/coordinatesCluster1.csv";
// final static int numClusters = 6;
//
// // Cluster 1.1 area
// final static int xMinCluster1 = -15;
// final static double xMaxCluster1 = -2.4;
// final static int yMinCluster1 = -15;
// final static int yMaxCluster1 = 0;
//
// // Cluster 1.2 area
// final static int xMinCluster2 = -1;
// final static double xMaxCluster2 = 7.5;
// final static int yMinCluster2 = -15;
// final static int yMaxCluster2 = -4;
//
// // Cluster 1.3 area
// final static double xMinCluster3 = -2.45;
// final static int xMaxCluster3 = 5;
// final static int yMinCluster3 = -3;
// final static double yMaxCluster3 = 5.44;
//
// // Cluster 1.4 area
// final static int xMinCluster4 = 3;
// final static int xMaxCluster4 = 17;
// final static int yMinCluster4 = 7;
// final static int yMaxCluster4 = 16;
//
// // Cluster 1.5 area
// final static double xMinCluster5 = -4.5;
// final static int xMaxCluster5 = 1;
// final static double yMinCluster5 = 3.6;
// final static int yMaxCluster5 = 9;
//
// // Cluster 1.6 area
// final static int xMinCluster6 = 11;
// final static double xMaxCluster6 = 12.25;
// final static int yMinCluster6 = 4;
// final static double yMaxCluster6 = 6.5;
// Coordinates of the 5 sub-clusters of Cluster 2
// final static String coordinatesPath = "./res/cluster/input/coordinatesCluster2.csv";
// final static int numClusters = 8;
//
// // Cluster 2.1 area
// final static int xMinCluster1 = -10;
// final static int xMaxCluster1 = -6;
// final static double yMinCluster1 = -7.5;
// final static double yMaxCluster1 = -3.6;
//
// // Cluster 2.2 area
// final static int xMinCluster2 = -14;
// final static int xMaxCluster2 = -8;
// final static double yMinCluster2 = -0.75;
// final static int yMaxCluster2 = 4;
//
// final static double secondxMinCluster2 = -8.2;
// final static double secondxMaxCluster2 = -6.8;
// final static double secondyMinCluster2 = 2.2;
// final static int secondyMaxCluster2 = 3;
//
// // Cluster 2.3 area
// final static double xMinCluster3 = -1.2;
// final static int xMaxCluster3 = 5;
// final static int yMinCluster3 = -7;
// final static double yMaxCluster3 = -2.8;
//
// final static double secondxMinCluster3 = 5.3;
// final static double secondxMaxCluster3 = 7;
// final static double secondyMinCluster3 = -2.75;
// final static int secondyMaxCluster3 = -1;
//
// // Cluster 2.4 area
// final static double xMinCluster4 = -5.8;
// final static double xMaxCluster4 = -0.94;
// final static int yMinCluster4 = 2;
// final static double yMaxCluster4 = 5.5;
//
// // Cluster 2.5 area
// final static double xMinCluster5 = -0.77;
// final static int xMaxCluster5 = 2;
// final static double yMinCluster5 = 1.75;
// final static double yMaxCluster5 = 4.5;
//
// // Cluster 2.6 area
// final static double xMinCluster6 = 4.25;
// final static int xMaxCluster6 = 6;
// final static double yMinCluster6 = 5.5;
// final static double yMaxCluster6 = 7.0;
//
// // Cluster 2.7 area
// final static double xMinCluster7 = 1;
// final static double xMaxCluster7 = 4.5;
// final static double yMinCluster7 = 0;
// final static double yMaxCluster7 = 1.25;
//
// // Cluster 2.8 area
// final static double xMinCluster8 = -1.7;
// final static double xMaxCluster8 = 0;
// final static double yMinCluster8 = -2.5;
// final static double yMaxCluster8 = 0.8;
// Coordinates of the 9 sub-clusters of Cluster 3
final static String coordinatesPath = "./res/cluster/input/coordinatesCluster3.csv";
final static int numClusters = 12;
// Cluster 3.1 area
final static int xMinCluster1 = -4;
final static double xMaxCluster1 = 3;
final static double yMinCluster1 = 10.8;
final static int yMaxCluster1 = 19;
// Cluster 3.2 area
final static double xMinCluster2 = 6.5;
final static int xMaxCluster2 = 12;
final static double yMinCluster2 = 5.4;
final static int yMaxCluster2 = 12;
// Cluster 3.3 area
final static double xMinCluster3 = 5.4;
final static int xMaxCluster3 = 13;
final static double yMinCluster3 = -2.3;
final static int yMaxCluster3 = 3;
// Cluster 3.4 area
final static double xMinCluster4 = 6.5;
final static double xMaxCluster4 = 11;
final static double yMinCluster4 = -7;
final static int yMaxCluster4 = -3;
// Cluster 3.5 area
final static double xMinCluster5 = 4.8;
final static double xMaxCluster5 = 8;
final static double yMinCluster5 = -10;
final static double yMaxCluster5 = -7.5;
// Cluster 3.6 area
final static double xMinCluster6 = -1.5;
final static double xMaxCluster6 = 5;
final static double yMinCluster6 = -13.4;
final static double yMaxCluster6 = -9.8;
final static double secondxMinCluster6 = -3.5;
final static double secondxMaxCluster6 = 3;
final static double secondyMinCluster6 = -11.58;
final static double secondyMaxCluster6 = -8.3;
final static double thirdxMinCluster6 = -1.6;
final static double thirdxMaxCluster6 = 2;
final static double thirdyMinCluster6 = -9.45;
final static double thirdyMaxCluster6 = -7.28;
// Cluster 3.7 area
final static double xMinCluster7 = -11.66;
final static double xMaxCluster7 = -5.22;
final static double yMinCluster7 = -6.30;
final static double yMaxCluster7 = 0.25;
final static double secondxMinCluster7 = -7.35;
final static double secondxMaxCluster7 = -4;
final static double secondyMinCluster7 = 1.0;
final static double secondyMaxCluster7 = 2.25;
// Cluster 3.8 area
final static double xMinCluster8 = -18;
final static double xMaxCluster8 = -11;
final static double yMinCluster8 = -2.3;
final static double yMaxCluster8 = 1.3;
// Cluster 3.9 area
final static double xMinCluster9 = -10.9;
final static double xMaxCluster9 = -6;
final static double yMinCluster9 = 4.4;
final static double yMaxCluster9 = 8.1;
// Cluster 3.10 area
final static double xMinCluster10 = -3;
final static double xMaxCluster10 = 0.8;
final static double yMinCluster10 = 1.31;
final static double yMaxCluster10 = 9;
// Cluster 3.11 area
final static double xMinCluster11 = 1.43;
final static double xMaxCluster11 = 6;
final static double yMinCluster11 = 6;
final static double yMaxCluster11 = 10;
// Cluster 3.12 area
final static double xMinCluster12 = -5.2;
final static double xMaxCluster12 = -0.55;
final static double yMinCluster12 = -5.45;
final static double yMaxCluster12 = -0.9;
final static String gamePath = "./res/cluster/input/Games.csv";
/**
* Main method to call the reconstruction with command lines.
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
@SuppressWarnings("unchecked")
public static void main(final String[] args) throws FileNotFoundException, IOException
{
// init game names list
final List<String> gameNames = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(gamePath)))
{
String line = br.readLine();
while (line != null)
{
gameNames.add(line.substring(1, line.length()-1)); // we remove the quotes.
line = br.readLine();
}
}
// init the clusters results;
final List<String>[] clusters = new ArrayList[numClusters];
for(int i = 0; i < numClusters; i++)
clusters[i] = new ArrayList<String>();
// Read the CSV line by line.
final List<String> coordinates = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(coordinatesPath)))
{
String line = br.readLine();
while (line != null)
{
coordinates.add(line);
line = br.readLine();
}
}
for(int i = 0; i < coordinates.size(); i++)
{
String[] gameAndCoordinates = coordinates.get(i).split(";");
final String gameName = gameAndCoordinates[0];
final double x = Double.parseDouble(gameAndCoordinates[1]);
final double y = Double.parseDouble(gameAndCoordinates[2]);
if(x >= xMinCluster1 && x <= xMaxCluster1 && y >= yMinCluster1 && y <= yMaxCluster1)
clusters[0].add(gameName);
else if(x >= xMinCluster2 && x <= xMaxCluster2 && y >= yMinCluster2 && y <= yMaxCluster2)
clusters[1].add(gameName);
else if(x >= xMinCluster3 && x <= xMaxCluster3 && y >= yMinCluster3 && y <= yMaxCluster3)
clusters[2].add(gameName);
else if(x >= xMinCluster4 && x <= xMaxCluster4 && y >= yMinCluster4 && y <= yMaxCluster4)
clusters[3].add(gameName);
else if(x >= xMinCluster5 && x <= xMaxCluster5 && y >= yMinCluster5 && y <= yMaxCluster5)
clusters[4].add(gameName);
else if(x >= xMinCluster6 && x <= xMaxCluster6 && y >= yMinCluster6 && y <= yMaxCluster6)
clusters[5].add(gameName);
else if(x >= secondxMinCluster6 && x <= secondxMaxCluster6 && y >= secondyMinCluster6 && y <= secondyMaxCluster6)
clusters[5].add(gameName);
else if(x >= thirdxMinCluster6 && x <= thirdxMaxCluster6 && y >= thirdyMinCluster6 && y <= thirdyMaxCluster6)
clusters[5].add(gameName);
else if(x >= xMinCluster7 && x <= xMaxCluster7 && y >= yMinCluster7 && y <= yMaxCluster7)
clusters[6].add(gameName);
else if(x >= secondxMinCluster7 && x <= secondxMaxCluster7 && y >= secondyMinCluster7 && y <= secondyMaxCluster7)
clusters[6].add(gameName);
else if(x >= xMinCluster8 && x <= xMaxCluster8 && y >= yMinCluster8 && y <= yMaxCluster8)
clusters[7].add(gameName);
else if(x >= xMinCluster9 && x <= xMaxCluster9 && y >= yMinCluster9 && y <= yMaxCluster9)
clusters[8].add(gameName);
else if(x >= xMinCluster10 && x <= xMaxCluster10 && y >= yMinCluster10 && y <= yMaxCluster10)
clusters[9].add(gameName);
else if(x >= xMinCluster11 && x <= xMaxCluster11 && y >= yMinCluster11 && y <= yMaxCluster11)
clusters[10].add(gameName);
else if(x >= xMinCluster12 && x <= xMaxCluster12 && y >= yMinCluster12 && y <= yMaxCluster12)
clusters[11].add(gameName);
else
System.err.println(gameName + " does not go to any cluster");
}
for(int i = 0; i < numClusters; i++)
{
System.out.println("****************** Cluster " + (i + 1) + " **************************");
for(int j = 0; j < clusters[i].size(); j++)
System.out.println(clusters[i].get(j));
System.out.println("*****Size = " + clusters[i].size());
System.out.println();
}
final String SQLRequest = "SELECT DISTINCT GameRulesets.Id AS GameRulesetsId, GameRulesets.Name AS GameRulesetsName, Games.Id AS GamesId, Games.Name AS GamesName FROM GameRulesets, Games, RulesetConcepts WHERE Games.Id = GameRulesets.GameId AND RulesetConcepts.RulesetId = GameRulesets.Id AND (GameRulesets.Type = 1 OR GameRulesets.Type = 3) AND Games.DLPGame = 1 AND (";
String SQLRequestCluster1 = SQLRequest;
String SQLRequestCluster2 = SQLRequest;
String SQLRequestCluster3 = SQLRequest;
String SQLRequestCluster4 = SQLRequest;
// Request for Cluster 1.
for(int i = 0; i < clusters[0].size() - 1; i++)
{
String gameName = clusters[0].get(i);
//System.out.println("test for " + fullGameName);
boolean found = false;
while(!found)
{
String gameNameWithUnderscore = gameName.substring(0, gameName.lastIndexOf('_'));
gameName = gameNameWithUnderscore.replace('_', ' ');
//System.out.println("Test: " + possibleGameName);
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster1 += "Games.Name = \\\"" + gameName + "\\\" OR ";
break;
}
}
gameName = gameNameWithUnderscore;
if(!gameName.contains("_")) // If this is reached, the game name is never found.
{
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster1 += "Games.Name = \\\"" + gameName + "\\\" OR ";
break;
}
}
if(!found)
{
System.err.println(clusters[0].get(i) + " is never found in the list of game names.");
System.exit(1);
}
}
}
}
String gameName = clusters[0].get(clusters[0].size()-1);
//System.out.println("test for " + fullGameName);
boolean found = false;
while(!found)
{
String gameNameWithUnderscore = gameName.substring(0, gameName.lastIndexOf('_'));
gameName = gameNameWithUnderscore.replace('_', ' ');
//System.out.println("Test: " + possibleGameName);
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster1 += "Games.Name = \\\"" + gameName + "\\\")";
break;
}
}
if(!found)
{
gameName = gameNameWithUnderscore;
if(!gameName.contains("_")) // If this is reached, the game name is never found.
{
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster1 += "Games.Name = \\\"" + gameName + "\\\")";
break;
}
}
if(!found)
{
System.err.println(clusters[0].get(clusters[0].size()-1) + " is never found in the list of game names.");
System.exit(1);
}
}
}
}
// Request for Cluster 2.
for(int i = 0; i < clusters[1].size() - 1; i++)
{
gameName = clusters[1].get(i);
//System.out.println("test for " + fullGameName);
found = false;
while(!found)
{
String gameNameWithUnderscore = gameName.substring(0, gameName.lastIndexOf('_'));
gameName = gameNameWithUnderscore.replace('_', ' ');
//System.out.println("Test: " + possibleGameName);
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster2 += "Games.Name = \\\"" + gameName + "\\\" OR ";
break;
}
}
gameName = gameNameWithUnderscore;
if(!gameName.contains("_")) // If this is reached, the game name is never found.
{
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster2 += "Games.Name = \\\"" + gameName + "\\\" OR ";
break;
}
}
if(!found)
{
System.err.println(clusters[1].get(i) + " is never found in the list of game names.");
System.exit(1);
}
}
}
}
gameName = clusters[1].get(clusters[1].size()-1);
//System.out.println("test for " + fullGameName);
found = false;
while(!found)
{
String gameNameWithUnderscore = gameName.substring(0, gameName.lastIndexOf('_'));
gameName = gameNameWithUnderscore.replace('_', ' ');
//System.out.println("Test: " + possibleGameName);
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster2 += "Games.Name = \\\"" + gameName + "\\\")";
break;
}
}
if(!found)
{
gameName = gameNameWithUnderscore;
if(!gameName.contains("_")) // If this is reached, the game name is never found.
{
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster2 += "Games.Name = \\\"" + gameName + "\\\")";
break;
}
}
if(!found)
{
System.err.println(clusters[1].get(clusters[1].size()-1) + " is never found in the list of game names.");
System.exit(1);
}
}
}
}
// Request for Cluster 3.
for(int i = 0; i < clusters[2].size() - 1; i++)
{
gameName = clusters[2].get(i);
//System.out.println("test for " + fullGameName);
found = false;
while(!found)
{
String gameNameWithUnderscore = gameName.substring(0, gameName.lastIndexOf('_'));
gameName = gameNameWithUnderscore.replace('_', ' ');
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster3 += "Games.Name = \\\"" + gameName + "\\\" OR ";
break;
}
}
gameName = gameNameWithUnderscore;
if(!gameName.contains("_")) // If this is reached, the game name is never found.
{
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster3 += "Games.Name = \\\"" + gameName + "\\\" OR ";
break;
}
}
if(!found)
{
System.err.println(clusters[2].get(i) + " is never found in the list of game names.");
System.exit(1);
}
}
}
}
gameName = clusters[2].get(clusters[2].size()-1);
//System.out.println("test for " + fullGameName);
found = false;
while(!found)
{
String gameNameWithUnderscore = gameName.substring(0, gameName.lastIndexOf('_'));
gameName = gameNameWithUnderscore.replace('_', ' ');
//System.out.println("Test: " + possibleGameName);
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster3 += "Games.Name = \\\"" + gameName + "\\\")";
break;
}
}
if(!found)
{
gameName = gameNameWithUnderscore;
if(!gameName.contains("_")) // If this is reached, the game name is never found.
{
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster3 += "Games.Name = \\\"" + gameName + "\\\")";
break;
}
}
if(!found)
{
System.err.println(clusters[2].get(clusters[2].size()-1) + " is never found in the list of game names.");
System.exit(1);
}
}
}
}
// Request for Cluster 4.
for(int i = 0; i < clusters[3].size() - 1; i++)
{
gameName = clusters[3].get(i);
//System.out.println("test for " + fullGameName);
found = false;
while(!found)
{
String gameNameWithUnderscore = gameName.substring(0, gameName.lastIndexOf('_'));
gameName = gameNameWithUnderscore.replace('_', ' ');
//System.out.println("Test: " + possibleGameName);
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster4 += "Games.Name = \\\"" + gameName + "\\\" OR ";
break;
}
}
gameName = gameNameWithUnderscore;
if(!gameName.contains("_")) // If this is reached, the game name is never found.
{
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster4 += "Games.Name = \\\"" + gameName + "\\\" OR ";
break;
}
}
if(!found)
{
System.err.println(clusters[3].get(i) + " is never found in the list of game names.");
System.exit(1);
}
}
}
}
gameName = clusters[3].get(clusters[3].size()-1);
//System.out.println("test for " + fullGameName);
found = false;
while(!found)
{
String gameNameWithUnderscore = gameName.substring(0, gameName.lastIndexOf('_'));
gameName = gameNameWithUnderscore.replace('_', ' ');
//System.out.println("Test: " + possibleGameName);
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster4 += "Games.Name = \\\"" + gameName + "\\\")";
break;
}
}
if(!found)
{
gameName = gameNameWithUnderscore;
if(!gameName.contains("_")) // If this is reached, the game name is never found.
{
for(int j = 0; j < gameNames.size(); j++)
{
if(gameNames.get(j).replace("'","").replace("(","").replace(")","").equals(gameName))
{
found = true;
gameName = gameNames.get(j);
SQLRequestCluster4 += "Games.Name = \\\"" + gameName + "\\\")";
break;
}
}
if(!found)
{
System.err.println(clusters[3].get(clusters[3].size()-1) + " is never found in the list of game names.");
System.exit(1);
}
}
}
}
System.out.println(SQLRequestCluster1);
System.out.println("********************");
System.out.println(SQLRequestCluster2);
System.out.println("********************");
System.out.println(SQLRequestCluster3);
System.out.println("********************");
System.out.println(SQLRequestCluster4);
}
}
| 22,835 | 31.254237 | 373 |
java
|
Ludii
|
Ludii-master/Mining/src/contextualiser/ContextualSimilarity.java
|
package contextualiser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import game.Game;
import utils.DBGameInfo;
public class ContextualSimilarity
{
//-------------------------------------------------------------------------
public static final String rulesetIdsFilePath = "../Mining/res/concepts/input/GameRulesets.csv";
public static final String rulesetContextualiserFilePath = "../Mining/res/recons/input/contextualiser_1000/similarity_";
public static final String rulesetGeographicDistanceFilePath = "../Mining/res/recons/input/rulesetGeographicalDistances.csv";
public static final String rulesetYearDistanceFilePath = "../Mining/res/recons/input/rulesetYearDistances.csv";
//-------------------------------------------------------------------------
/**
* @param game Game to compare similarity against.
* @param conceptSimilarity true if using concept similarity, otherwise using cultural similarity.
* @return Map of game/ruleset names to similarity values.
*/
public static final Map<String, Double> getRulesetSimilarities(final Game game, final boolean conceptSimilarity)
{
// Get all ruleset ids from DB
final String name = DBGameInfo.getUniqueName(game);
final Map<String, Integer> rulesetIds = DBGameInfo.getRulesetIds(rulesetIdsFilePath);
final int rulesetId = rulesetIds.get(name).intValue();
final Map<Integer, Double> rulesetSimilaritiesIds = new HashMap<>(); // Map of ruleset ids to similarity
final Map<String, Double> rulesetSimilaritiesNames = new HashMap<>(); // Map of game/ruleset names to similarity
final String fileName = rulesetContextualiserFilePath + rulesetId + ".csv";
try (BufferedReader br = new BufferedReader(new FileReader(fileName)))
{
br.readLine(); // Skip first line of column headers.
String line;
while ((line = br.readLine()) != null)
{
final String[] values = line.split(",");
double similarity = -1.0;
if (conceptSimilarity)
similarity = Double.valueOf(values[2]).doubleValue();
else
similarity = Double.valueOf(values[1]).doubleValue();
rulesetSimilaritiesIds.put(Integer.valueOf(values[0]), Double.valueOf(similarity));
if (!rulesetIds.containsValue(Integer.valueOf(values[0])))
System.out.println("ERROR, two rulesets with the same name. ruleset id: " + Integer.valueOf(values[0]));
// Convert ruleset ids to corresponding names.
for (final Map.Entry<String, Integer> entry : rulesetIds.entrySet())
if (entry.getValue().equals(Integer.valueOf(values[0])))
rulesetSimilaritiesNames.put(entry.getKey(), Double.valueOf(similarity));
}
}
catch (final Exception e)
{
System.out.println("Could not find similarity file, ruleset probably has no evidence.");
e.printStackTrace();
}
return rulesetSimilaritiesNames;
}
//-------------------------------------------------------------------------
/**
* @param game Game to compare geographic similarity against.
* @return Map of game/ruleset names to similarity values.
*/
public static final Map<String, Double> getRulesetGeographicSimilarities(final Game game)
{
// Get all ruleset ids from DB
final String name = DBGameInfo.getUniqueName(game);
final Map<String, Integer> rulesetIds = DBGameInfo.getRulesetIds(rulesetIdsFilePath);
final int rulesetId = rulesetIds.get(name).intValue();
final Map<Integer, Double> rulesetSimilaritiesIds = new HashMap<>(); // Map of ruleset ids to similarity
final Map<String, Double> rulesetSimilaritiesNames = new HashMap<>(); // Map of game/ruleset names to similarity
try (BufferedReader br = new BufferedReader(new FileReader(rulesetGeographicDistanceFilePath)))
{
br.readLine(); // Skip first line of column headers.
String line;
while ((line = br.readLine()) != null)
{
final String[] values = line.split(",");
if (Integer.valueOf(values[0]).intValue() != rulesetId)
continue;
final double similarity = Math.max((20000 - Double.valueOf(values[2]).doubleValue()) / 20000, 0); // 20000km is the maximum possible distance
rulesetSimilaritiesIds.put(Integer.valueOf(values[1]), Double.valueOf(similarity));
if (!rulesetIds.containsValue(Integer.valueOf(values[0])))
System.out.println("ERROR, two rulesets with the same name. ruleset id: " + Integer.valueOf(values[0]));
// Convert ruleset ids to corresponding names.
for (final Map.Entry<String, Integer> entry : rulesetIds.entrySet())
if (entry.getValue().equals(Integer.valueOf(values[1])))
rulesetSimilaritiesNames.put(entry.getKey(), Double.valueOf(similarity));
}
}
catch (final Exception e)
{
System.out.println("Could not find similarity file, ruleset probably has no evidence.");
e.printStackTrace();
}
return rulesetSimilaritiesNames;
}
//-------------------------------------------------------------------------
/**
* @param game Game to compare year similarity against.
* @return Map of game/ruleset names to similarity values.
*/
public static final Map<String, Double> getRulesetYearSimilarities(final Game game)
{
// Get all ruleset ids from DB
final String name = DBGameInfo.getUniqueName(game);
final Map<String, Integer> rulesetIds = DBGameInfo.getRulesetIds(rulesetIdsFilePath);
final int rulesetId = rulesetIds.get(name).intValue();
final Map<Integer, Double> rulesetSimilaritiesIds = new HashMap<>(); // Map of ruleset ids to similarity
final Map<String, Double> rulesetSimilaritiesNames = new HashMap<>(); // Map of game/ruleset names to similarity
try (BufferedReader br = new BufferedReader(new FileReader(rulesetYearDistanceFilePath)))
{
br.readLine(); // Skip first line of column headers.
String line;
while ((line = br.readLine()) != null)
{
final String[] values = line.split(",");
if (Integer.valueOf(values[0]).intValue() != rulesetId)
continue;
final double similarity = Math.max((5520 - Double.valueOf(values[2]).doubleValue()) / 5520, 0); // 5520 years is the maximum possible distance
rulesetSimilaritiesIds.put(Integer.valueOf(values[1]), Double.valueOf(similarity));
if (!rulesetIds.containsValue(Integer.valueOf(values[0])))
System.out.println("ERROR, two rulesets with the same name. ruleset id: " + Integer.valueOf(values[0]));
// Convert ruleset ids to corresponding names.
for (final Map.Entry<String, Integer> entry : rulesetIds.entrySet())
if (entry.getValue().equals(Integer.valueOf(values[1])))
rulesetSimilaritiesNames.put(entry.getKey(), Double.valueOf(similarity));
}
}
catch (final Exception e)
{
System.out.println("Could not find similarity file, ruleset probably has no evidence.");
e.printStackTrace();
}
return rulesetSimilaritiesNames;
}
//-------------------------------------------------------------------------
}
| 7,271 | 41.27907 | 152 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/CompareAllDistanceMetrics.java
|
package gameDistance;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import gameDistance.datasets.treeEdit.LudemeDataset;
import gameDistance.metrics.DistanceMetric;
import gameDistance.metrics.bagOfWords.Overlap;
import gameDistance.utils.DistanceUtils;
import main.DatabaseInformation;
import other.GameLoader;
/**
* Compares all distance metrics for a given set of games.
*
* Download the "TrialsRandom.zip" file from the Ludii Server.
* Copy "TrialsRandom.zip" into "Ludii/Trials/", and extract the zip to a "TrialsRandom" folder (just right click and select "Extract Here"). Making the fullPath "Ludii/Trials/TrialsRandom/".
* Run CompareAllDistanceMetrics.java
* Output for each game/ruleset is stored in Ludii/Mining/res/gameDistance/
* "byGame" folder stores the distance from a specific ruleset to all other games for all metrics.
* "byMetric" folder stores the distance between all ruleset pairs for a specific metric.
*
* Make sure to set the "overrideStoredVocabularies" variable to true if any trials or games have changed.
*
* @author matthew.stephenson
*/
public class CompareAllDistanceMetrics
{
/** Set this variable to true, if the stored vocabularies should be overwritten on the next comparison. */
final static boolean overrideStoredVocabularies = true;
//---------------------------------------------------------------------
final static String outputPath = "res/gameDistance/";
final static Dataset ludemeDataset = new LudemeDataset();
// final static Dataset compilationConceptDataset = new CompilationConceptDataset();
// final static Dataset moveConceptDataset = new MoveConceptDataset();
// final static Dataset importConceptDataset = new ImportConceptDataset();
static Map<String, Double> fullLudemeVocabulary;
// static Map<String, Double> fullCompilationConceptVocabulary;
// static Map<String, Double> fullMoveConceptVocabulary;
// static Map<String, Double> fullImportConceptDataset;
//---------------------------------------------------------------------
public static void main(final String[] args)
{
calculateVocabularies();
// Use this code to compare specific games.
// final List<String[]> gamesAndRulesetsToCompare = getSpecificGamesToCompare();
// recordAllComparisonDistances(gamesAndRulesetsToCompare.get(0), gamesAndRulesetsToCompare.get(1));
// Use this code to compare all games.
final List<String[]> gamesAndRulesetsToCompare = GameLoader.allAnalysisGameRulesetNames();
final List<String> allGameNames = new ArrayList<>();
final List<String> allRulesetNames = new ArrayList<>();
for (final String[] allGamesToComare : gamesAndRulesetsToCompare)
{
allGameNames.add(allGamesToComare[0]);
allRulesetNames.add(allGamesToComare[1]);
}
recordAllComparisonDistances(allGameNames.toArray(new String[0]), allRulesetNames.toArray(new String[0]));
}
//---------------------------------------------------------------------
/**
* Record distances for each game/ruleset comparison.
*/
private static void recordAllComparisonDistances(final String[] gamesToCompare, final String[] rulesetsToCompare)
{
// [Game, {Game, {DistanceMetric, Value}}]
final List<Map<String, Map<String, Double>>> allGameDistances = new ArrayList<>();
for (int i = 0; i < gamesToCompare.length; i++)
{
final Map<String, Map<String, Double>> gameDistances = new HashMap<>();
for (int j = 0; j < gamesToCompare.length; j++)
{
gameDistances.put
(
gamesToCompare[j] + "_" + rulesetsToCompare[j],
compareTwoGames(GameLoader.loadGameFromName(gamesToCompare[i], rulesetsToCompare[i]), GameLoader.loadGameFromName(gamesToCompare[j], rulesetsToCompare[j]))
);
}
allGameDistances.add(gameDistances);
}
storeByGameResults(gamesToCompare, rulesetsToCompare, allGameDistances);
storeByMetricResults(gamesToCompare, rulesetsToCompare, allGameDistances);
}
//---------------------------------------------------------------------
/**
* Stores the distance results in a set of .csv files, with each file representing a single game and its distance to all other games.
* @param gamesToCompare
* @param rulesetsToCompare
* @param allGameDistances
*/
@SuppressWarnings("unchecked")
private static void storeByGameResults(final String[] gamesToCompare, final String[] rulesetsToCompare, final List<Map<String, Map<String, Double>>> allGameDistances)
{
for (int i = 0; i < gamesToCompare.length; i++)
{
// Create output file.
final File outputFile = new File(outputPath + "output/byGame/" +
gamesToCompare[i].split("\\/")[gamesToCompare[i].split("\\/").length-1] + "_" +
rulesetsToCompare[i].split("\\/")[rulesetsToCompare[i].split("\\/").length-1] + ".csv");
try
{
outputFile.createNewFile();
}
catch (final IOException e1)
{
e1.printStackTrace();
}
// Store distances in output file.
try (final FileWriter myWriter = new FileWriter(outputFile))
{
// Write the top row of the csv
String topRow = "GameName,Id";
final List<String> distanceNames = new ArrayList<>(((Map<String, Double>) allGameDistances.get(i).values().toArray()[0]).keySet());
for (final String distance : distanceNames)
topRow += "," + distance;
myWriter.write(topRow + "\n");
// Store all distances for this ruleset.
for (final Map.Entry<String, Map<String, Double>> gameEntry : allGameDistances.get(i).entrySet())
{
final String gameName = gameEntry.getKey();
// Get corresponding ruleset Id.
final String[] nameArray = gameName.split("_")[0].split("/");
final String formattedGameName = nameArray[nameArray.length-1].substring(0,nameArray[nameArray.length-1].length()-4);
String formattedRulesetName = "";
if (gameName.split("_").length > 1)
formattedRulesetName = gameName.split("_")[1];
final int rulesetId = DatabaseInformation.getRulesetId(formattedGameName, formattedRulesetName);
final List<String> row = new ArrayList<>(distanceNames);
for (final Map.Entry<String, Double> distanceEntry : gameEntry.getValue().entrySet())
{
final String distanceMetric = distanceEntry.getKey();
final Double distaneValue = distanceEntry.getValue();
row.set(row.indexOf(distanceMetric), String.valueOf(distaneValue));
}
myWriter.write(gameName + "," + rulesetId + "," + String.join(",", row) + "\n");
}
myWriter.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
//---------------------------------------------------------------------
/**
* Stores the distance results in a set of .csv files, with each file representing a single distance metric for all game-distance pairs.
* @param gamesToCompare
* @param rulesetsToCompare
* @param allGameDistances
*/
@SuppressWarnings("unchecked")
private static void storeByMetricResults(final String[] gamesToCompare, final String[] rulesetsToCompare, final List<Map<String, Map<String, Double>>> allGameDistances)
{
final List<String> distanceNames = new ArrayList<>(((Map<String, Double>) allGameDistances.get(0).values().toArray()[0]).keySet());
for (int i = 0; i < distanceNames.size(); i++)
{
// Create output file.
final File outputFile = new File(outputPath + "output/byMetric/" + distanceNames.get(i) + ".csv");
try
{
outputFile.createNewFile();
}
catch (final IOException e1)
{
e1.printStackTrace();
}
// Store distances in output file.
try (final FileWriter myWriter = new FileWriter(outputFile))
{
final List<String> allRulesetIds = new ArrayList<>();
// Write the top row of the file
String topRow = "Id";
for (int j = 0; j < gamesToCompare.length; j++)
{
final String gameName = gamesToCompare[j] + "_" + rulesetsToCompare[j];
// Get corresponding ruleset Id.
final String[] nameArray = gameName.split("_")[0].split("/");
final String formattedGameName = nameArray[nameArray.length-1].substring(0,nameArray[nameArray.length-1].length()-4);
String formattedRulesetName = "";
if (gameName.split("_").length > 1)
formattedRulesetName = gameName.split("_")[1];
final int rulesetId = DatabaseInformation.getRulesetId(formattedGameName, formattedRulesetName);
allRulesetIds.add(String.valueOf(rulesetId));
topRow += "," + rulesetId;
}
myWriter.write(topRow + "\n");
for (int j = 0; j < gamesToCompare.length; j++)
{
String row = allRulesetIds.get(j);
final Map<String, Map<String, Double>> distanceMapAllGames = allGameDistances.get(j);
for (int k = 0; k < gamesToCompare.length; k++)
{
final Map<String, Double> distanceMap = distanceMapAllGames.get(gamesToCompare[k] + "_" + rulesetsToCompare[k]);
row += "," + distanceMap.get(distanceNames.get(i));
}
myWriter.write(row + "\n");
}
myWriter.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
//---------------------------------------------------------------------
/**
* Calculate dataset vocabularies for TFIDF measures.
*/
private static void calculateVocabularies()
{
fullLudemeVocabulary = DistanceUtils.fullVocabulary(ludemeDataset, "ludemeDataset", overrideStoredVocabularies);
System.out.println("ludemeVocabulary recorded");
// fullCompilationConceptVocabulary = DistanceUtils.fullVocabulary(compilationConceptDataset, "compilationConceptDataset", overrideStoredVocabularies);
// System.out.println("compilationConceptDataset recorded");
//
// fullMoveConceptVocabulary = DistanceUtils.fullVocabulary(moveConceptDataset, "moveConceptDataset", overrideStoredVocabularies);
// System.out.println("moveConceptVocabulary recorded");
//
// fullImportConceptDataset = DistanceUtils.fullVocabulary(importConceptDataset, "importConceptDataset", overrideStoredVocabularies);
// System.out.println("importConceptVocabulary recorded");
}
//---------------------------------------------------------------------
/**
* Compares gameA and gameB across all distance measures
* @param gameA
* @param gameB
* @return Map of distance metric names and values.
*/
public static Map<String, Double> compareTwoGames(final Game gameA, final Game gameB)
{
final Map<String, Double> allDistances = new HashMap<>();
//ludemeDataset.getTree(gameA);
System.out.println("\n" + gameA.name() + " v.s. " + gameB.name());
// //---------------------------------------------------------------------
// // Store the default vocabularies for each dataset.
//
final Map<String, Double> defaultLudemeVocabulary = DistanceUtils.defaultVocabulary(ludemeDataset, gameA, gameB);
// final Map<String, Double> defaultLudemeNGramVocabulary = DistanceUtils.defaultVocabulary(new NGramDataset(ludemeDataset, DistanceUtils.nGramLength), gameA, gameB);
//
// final Map<String, Double> defaultCompilationConceptVocabulary = DistanceUtils.defaultVocabulary(compilationConceptDataset, gameA, gameB);
//
// final Map<String, Double> defaultMoveConceptVocabulary = DistanceUtils.defaultVocabulary(moveConceptDataset, gameA, gameB);
// final Map<String, Double> defaultMoveConceptNGramVocabulary = DistanceUtils.defaultVocabulary(new NGramDataset(moveConceptDataset, DistanceUtils.nGramLength), gameA, gameB);
//
// //---------------------------------------------------------------------
// // Overlap
//
final DistanceMetric overlapDistanceMetric = new Overlap();
allDistances.put("overlap_ludeme", Double.valueOf(overlapDistanceMetric.distance(ludemeDataset, defaultLudemeVocabulary, gameA, gameB)));
//
// //---------------------------------------------------------------------
// // JensenShannonDivergence
//
// final DistanceMetric jensenShannonDivergenceMetric = new JensenShannonDivergence();
//
// allDistances.put("JSD_ludeme", jensenShannonDivergenceMetric.distance(ludemeDataset, defaultLudemeVocabulary, gameA, gameB));
// allDistances.put("JSD_compilationConcept", jensenShannonDivergenceMetric.distance(compilationConceptDataset, defaultCompilationConceptVocabulary, gameA, gameB));
// allDistances.put("JSD_moveConcept", jensenShannonDivergenceMetric.distance(moveConceptDataset, defaultMoveConceptVocabulary, gameA, gameB));
//
// allDistances.put("JSD_ludeme_ngram", jensenShannonDivergenceMetric.distance(new NGramDataset(ludemeDataset, DistanceUtils.nGramLength), defaultLudemeNGramVocabulary, gameA, gameB));
// allDistances.put("JSD_moveCooncept_ngram", jensenShannonDivergenceMetric.distance(new NGramDataset(moveConceptDataset, DistanceUtils.nGramLength), defaultMoveConceptNGramVocabulary, gameA, gameB));
//
// allDistances.put("JSD_ludeme_TFIDF", jensenShannonDivergenceMetric.distance(ludemeDataset, fullLudemeVocabulary, gameA, gameB));
// allDistances.put("JSD_compilationConcept_TFIDF", jensenShannonDivergenceMetric.distance(compilationConceptDataset, fullCompilationConceptVocabulary, gameA, gameB));
// allDistances.put("JSD_moveConcept_TFIDF", jensenShannonDivergenceMetric.distance(moveConceptDataset, fullMoveConceptVocabulary, gameA, gameB));
//
// //---------------------------------------------------------------------
// // Cosine
//
// final DistanceMetric cosineMetric = new Cosine();
//
// allDistances.put("Cosine_ludeme", cosineMetric.distance(ludemeDataset, defaultLudemeVocabulary, gameA, gameB));
// allDistances.put("Cosine_compilationConcept", cosineMetric.distance(compilationConceptDataset, defaultCompilationConceptVocabulary, gameA, gameB));
// allDistances.put("Cosine_moveConcept", cosineMetric.distance(moveConceptDataset, defaultMoveConceptVocabulary, gameA, gameB));
//
// allDistances.put("Cosine_ludeme_ngram", cosineMetric.distance(new NGramDataset(ludemeDataset, DistanceUtils.nGramLength), defaultLudemeNGramVocabulary, gameA, gameB));
// allDistances.put("Cosine_moveCooncept_ngram", cosineMetric.distance(new NGramDataset(moveConceptDataset, DistanceUtils.nGramLength), defaultMoveConceptNGramVocabulary, gameA, gameB));
//
// allDistances.put("Cosine_ludeme_TFIDF", cosineMetric.distance(ludemeDataset, fullLudemeVocabulary, gameA, gameB));
// allDistances.put("Cosine_compilationConcept_TFIDF", cosineMetric.distance(compilationConceptDataset, fullCompilationConceptVocabulary, gameA, gameB));
// allDistances.put("Cosine_moveConcept_TFIDF", cosineMetric.distance(moveConceptDataset, fullMoveConceptVocabulary, gameA, gameB));
//
// //---------------------------------------------------------------------
// // Jaccard
//
// final DistanceMetric jaccardMetric = new Jaccard();
//
// allDistances.put("Jaccard_ludeme", jaccardMetric.distance(ludemeDataset, defaultLudemeVocabulary, gameA, gameB));
// allDistances.put("Jaccard_compilationConcept", jaccardMetric.distance(compilationConceptDataset, defaultCompilationConceptVocabulary, gameA, gameB));
// allDistances.put("Jaccard_moveConcept", jaccardMetric.distance(moveConceptDataset, defaultMoveConceptVocabulary, gameA, gameB));
//
// allDistances.put("Jaccard_ludeme_ngram", jaccardMetric.distance(new NGramDataset(ludemeDataset, DistanceUtils.nGramLength), defaultLudemeNGramVocabulary, gameA, gameB));
// allDistances.put("Jaccard_moveCooncept_ngram", jaccardMetric.distance(new NGramDataset(moveConceptDataset, DistanceUtils.nGramLength), defaultMoveConceptNGramVocabulary, gameA, gameB));
//
// allDistances.put("Jaccard_ludeme_TFIDF", jaccardMetric.distance(ludemeDataset, fullLudemeVocabulary, gameA, gameB));
// allDistances.put("Jaccard_compilationConcept_TFIDF", jaccardMetric.distance(compilationConceptDataset, fullCompilationConceptVocabulary, gameA, gameB));
// allDistances.put("Jaccard_moveConcept_TFIDF", jaccardMetric.distance(moveConceptDataset, fullMoveConceptVocabulary, gameA, gameB));
//
// //---------------------------------------------------------------------
// // Levenshtein
//
// final DistanceMetric levenshteinMetric = new Levenshtein();
//
// allDistances.put("Levenshtein_ludeme", levenshteinMetric.distance(ludemeDataset, null, gameA, gameB));
// allDistances.put("Levenshtein_moveConcept", levenshteinMetric.distance(moveConceptDataset, null, gameA, gameB));
//
// //---------------------------------------------------------------------
// // Local Alignment
//
// final DistanceMetric localAlignmentMetric = new LocalAlignment();
//
// allDistances.put("LocalAlignment_ludeme", localAlignmentMetric.distance(ludemeDataset, null, gameA, gameB));
// allDistances.put("LocalAlignment_moveConcept", localAlignmentMetric.distance(moveConceptDataset, null, gameA, gameB));
//
// //---------------------------------------------------------------------
// // Repeated Local Alignment
//
// final DistanceMetric repeatedLocalAlignmentMetric = new RepeatedLocalAlignment();
//
// allDistances.put("RepeatedLocalAlignment_ludeme", repeatedLocalAlignmentMetric.distance(ludemeDataset, null, gameA, gameB));
// allDistances.put("RepeatedLocalAlignment_moveConcept", repeatedLocalAlignmentMetric.distance(moveConceptDataset, null, gameA, gameB));
//
// //---------------------------------------------------------------------
// // Global Alignment
//
// final DistanceMetric globalAlignmentMetric = new GlobalAlignment();
//
// allDistances.put("GlobalAlignment_ludeme", globalAlignmentMetric.distance(ludemeDataset, null, gameA, gameB));
// allDistances.put("GlobalAlignment_moveConcept", globalAlignmentMetric.distance(moveConceptDataset, null, gameA, gameB));
//
// //---------------------------------------------------------------------
// // Zhang Shasha
//
// final DistanceMetric zhangShashaMetric = new ZhangShasha();
//
// allDistances.put("ZhangShasha_ludeme", zhangShashaMetric.distance(ludemeDataset, defaultLudemeVocabulary, gameA, gameB));
//
// //---------------------------------------------------------------------
// // Apted
//
// final DistanceMetric aptedMetric = new Apted();
//
// allDistances.put("Apted_ludeme", aptedMetric.distance(ludemeDataset, defaultLudemeVocabulary, gameA, gameB));
//---------------------------------------------------------------------
return allDistances;
}
//---------------------------------------------------------------------
}
| 18,644 | 45.037037 | 201 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/datasets/Dataset.java
|
package gameDistance.datasets;
import java.util.List;
import java.util.Map;
import game.Game;
import utils.data_structures.support.zhang_shasha.Tree;
/**
* Interface for game dataset classes.
*
* @author Matthew.Stephenson
*/
public interface Dataset
{
/**
* @return dataset in a bag of words format <FeatureName, FeatureValue>
*/
Map<String, Double> getBagOfWords(Game game);
/**
* @return dataset in a sequence format.
*/
List<String> getSequence(Game game);
/**
* @return dataset in a tree format.
*/
Tree getTree(Game game);
}
| 562 | 17.16129 | 72 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/datasets/DatasetUtils.java
|
package gameDistance.datasets;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import game.Game;
import manager.utils.game_logs.MatchRecord;
import other.trial.Trial;
/**
* Game dataset utility functions.
*
* @author matthew.stephenson
*/
public class DatasetUtils
{
//-------------------------------------------------------------------------
/**
* TODO currently the loaded trial doesn't consider rulesetStrings
*/
public static List<Trial> getSavedTrials(final Game game)
{
final List<Trial> gameTrials = new ArrayList<>();
final String folderTrials = "/../Trials/TrialsRandom/";
final File currentFolder = new File(".");
final File folder = new File(currentFolder.getAbsolutePath() + folderTrials);
final String gameName = game.name();
final String rulesetName = game.getRuleset() == null ? "" : game.getRuleset().heading();
String trialFolderPath = folder + "/" + gameName;
if(!rulesetName.isEmpty())
trialFolderPath += File.separator + rulesetName.replace("/", "_");
final File trialFolder = new File(trialFolderPath);
if(!trialFolder.exists())
System.out.println("DO NOT FOUND IT - Path is " + trialFolder);
for(final File trialFile : trialFolder.listFiles())
{
MatchRecord loadedRecord;
try
{
loadedRecord = MatchRecord.loadMatchRecordFromTextFile(trialFile, game);
final Trial loadedTrial = loadedRecord.trial();
gameTrials.add(new Trial(loadedTrial));
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
return gameTrials;
}
//-------------------------------------------------------------------------
}
| 1,792 | 24.614286 | 90 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/datasets/bagOfWords/AIResultDataset.java
|
package gameDistance.datasets.bagOfWords;
import java.util.List;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import utils.data_structures.support.zhang_shasha.Tree;
/**
* Dataset containing performance results of different AI.
* - BagOfWords
*
* @author matthew.stephenson
*/
public class AIResultDataset implements Dataset
{
@Override
public Map<String, Double> getBagOfWords(final Game game)
{
return null;
}
/**
* Not Supported
*/
@Override
public List<String> getSequence(final Game game)
{
return null;
}
/**
* Not Supported
*/
@Override
public Tree getTree(final Game game)
{
return null;
}
}
| 676 | 14.386364 | 59 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/datasets/bagOfWords/CompilationConceptDataset.java
|
package gameDistance.datasets.bagOfWords;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import other.concept.Concept;
import other.concept.ConceptComputationType;
import other.concept.ConceptDataType;
import utils.data_structures.support.zhang_shasha.Tree;
/**
* Dataset containing compilation concepts.
* - BagOfWords
*
* @author matthew.stephenson
*/
public class CompilationConceptDataset implements Dataset
{
@Override
public Map<String, Double> getBagOfWords(final Game game)
{
final Map<String, Double> featureMap = new HashMap<>();
for (int i = 0; i < Concept.values().length; i++)
{
final Concept concept = Concept.values()[i];
if(concept.computationType().equals(ConceptComputationType.Compilation))
{
if (concept.dataType().equals(ConceptDataType.BooleanData))
{
if (game.booleanConcepts().get(concept.id()))
featureMap.put(concept.name(), Double.valueOf(1.0));
else
featureMap.put(concept.name(), Double.valueOf(0.0));
}
else if (concept.dataType().equals(ConceptDataType.DoubleData) || concept.dataType().equals(ConceptDataType.IntegerData))
{
featureMap.put(concept.name(), Double.valueOf(game.nonBooleanConcepts().get(Integer.valueOf(concept.id()))));
}
else
{
System.out.println("ERROR, the following concept has an invalid type " + concept.toString());
}
}
}
return featureMap;
}
/**
* Not Supported
*/
@Override
public List<String> getSequence(final Game game)
{
return null;
}
/**
* Not Supported
*/
@Override
public Tree getTree(final Game game)
{
return null;
}
}
| 1,707 | 22.39726 | 125 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/datasets/bagOfWords/ImportConceptDataset.java
|
package gameDistance.datasets.bagOfWords;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import utils.data_structures.support.zhang_shasha.Tree;
/**
* Dataset containing compilation concepts.
* - BagOfWords
*
* @author matthew.stephenson
*/
public class ImportConceptDataset implements Dataset
{
@Override
public Map<String, Double> getBagOfWords(final Game game)
{
final Map<String, Double> featureMap = new HashMap<>();
// Load files from a specific directory instead.
final String filePath = "../../LudiiPrivate/DataMiningScripts/Sklearn/res/Input/rulesetConceptsUCT.csv";
List<String> topRow = new ArrayList<>();
final List<List<String>> records = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath)))
{
String line = br.readLine();
topRow = Arrays.asList(line.split(","));
while ((line = br.readLine()) != null)
{
final String[] values = line.split(",");
records.add(Arrays.asList(values));
}
}
catch (final Exception e)
{
e.printStackTrace();
}
final String gameName = game.name().replaceAll("',()", "").replace(" ", "_");
String rulesetName = "Default";
if (game.getRuleset() != null)
rulesetName = game.getRuleset().heading().replaceAll("',()", "").replace(" ", "_");
final String formattedRulesetName = gameName + "_" + rulesetName;
// find the record that matches the ruleset name:
for (final List<String> record : records)
{
if (record.get(0).equals(formattedRulesetName))
{
for (int i = 1; i < topRow.size(); i++)
{
System.out.println(i);
System.out.println(topRow.get(i));
System.out.println(Double.valueOf(record.get(i)));
featureMap.put(topRow.get(i), Double.valueOf(record.get(i)));
}
break;
}
}
System.out.println("Failed to find match for " + formattedRulesetName);
return featureMap;
}
/**
* Not Supported
*/
@Override
public List<String> getSequence(final Game game)
{
return null;
}
/**
* Not Supported
*/
@Override
public Tree getTree(final Game game)
{
return null;
}
}
| 2,336 | 23.34375 | 106 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/datasets/bagOfWords/NGramDataset.java
|
package gameDistance.datasets.bagOfWords;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import utils.data_structures.support.zhang_shasha.Tree;
/**
* Converts a Sequence-possible dataset into a BagOfWords equivalent based on NGram sets.
* - BagOfWords
*
* @author matthew.stephenson
*/
public class NGramDataset implements Dataset
{
//---------------------------------------------------------------------
Dataset originalDataset;
int nGramLength;
//---------------------------------------------------------------------
/**
* Make sure to call this constructor with a dataset that provides a sequence output format.
* @param originalDataset
* @param nGramLength
*/
public NGramDataset(final Dataset originalDataset, final int nGramLength)
{
this.originalDataset = originalDataset;
this.nGramLength = nGramLength;
}
//---------------------------------------------------------------------
@Override
public Map<String, Double> getBagOfWords(final Game game)
{
return convertSequenceToNGram(originalDataset.getSequence(game), nGramLength);
}
/**
* Not Supported
*/
@Override
public List<String> getSequence(final Game game)
{
return null;
}
/**
* Not Supported
*/
@Override
public Tree getTree(final Game game)
{
return null;
}
//---------------------------------------------------------------------
/**
* Converts from a sequence dataset output to an NGrams bagOfWords output.
*/
public static Map<String, Double> convertSequenceToNGram(final List<String> sequence, final int n)
{
final Map<String, Double> featureMap = new HashMap<>();
final List<List<String>> allNGrams = new ArrayList<>();
for (int i = 0; i < sequence.size()-n; i++)
allNGrams.add(sequence.subList(i, i+n));
final List<String> allNGramStrings = new ArrayList<>();
for (int i = 0; i < allNGrams.size(); i++)
allNGramStrings.add(String.join("_", allNGrams.get(i)));
for (final String nGramString : allNGramStrings)
{
if (featureMap.containsKey(nGramString))
featureMap.put(nGramString, Double.valueOf(featureMap.get(nGramString).doubleValue()+1.0));
else
featureMap.put(nGramString, Double.valueOf(1.0));
}
return featureMap;
}
//---------------------------------------------------------------------
}
| 2,417 | 24.1875 | 99 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/datasets/sequence/MoveConceptDataset.java
|
package gameDistance.datasets.sequence;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import gameDistance.datasets.DatasetUtils;
import gnu.trove.list.array.TIntArrayList;
import other.concept.Concept;
import other.context.Context;
import other.trial.Trial;
import utils.data_structures.support.zhang_shasha.Tree;
/**
* Dataset containing move concepts from trials.
* - BagOfWords
* - Sequence
*
* @author matthew.stephenson
*/
public class MoveConceptDataset implements Dataset
{
//-------------------------------------------------------------------------
@Override
public Map<String, Double> getBagOfWords(final Game game)
{
final Map<String, Double> featureMap = new HashMap<>();
final List<Trial> gameTrials = DatasetUtils.getSavedTrials(game);
for (int i = 0; i < gameTrials.size(); ++i)
{
final Trial trial = gameTrials.get(i);
final Trial newTrial = new Trial(game);
final Context context = new Context(game, newTrial);
game.start(context);
final TIntArrayList gameMoveConceptSet = new TIntArrayList();
for(int j = 0; j < Concept.values().length; j++)
gameMoveConceptSet.add(0);
for(int o = newTrial.numInitialPlacementMoves(); o < trial.numMoves(); o++)
{
final TIntArrayList moveConceptSet = trial.getMove(o).moveConceptsValue(context);
for(int j = 0; j < Concept.values().length; j++)
gameMoveConceptSet.set(j, gameMoveConceptSet.get(j) + moveConceptSet.get(j));
game.apply(context, trial.getMove(o));
}
for(int j = 0; j < gameMoveConceptSet.size(); j++)
featureMap.put(Concept.values()[j].name(), Double.valueOf(gameMoveConceptSet.get(j)));
}
return featureMap;
}
//-------------------------------------------------------------------------
@Override
public List<String> getSequence(final Game game)
{
final List<String> moveConceptSequence = new ArrayList<>();
final List<Trial> gameTrials = DatasetUtils.getSavedTrials(game);
// For now, just take the first trial. gameTrials.size()
for (int i = 0; i < 1; ++i)
{
final Trial trial = gameTrials.get(i);
final Trial newTrial = new Trial(game);
final Context context = new Context(game, newTrial);
game.start(context);
final ArrayList<TIntArrayList> moveConceptSet = new ArrayList<>();
for(int o = newTrial.numInitialPlacementMoves(); o < trial.numMoves(); o++)
{
moveConceptSet.add(trial.getMove(o).moveConceptsValue(context));
game.apply(context, trial.getMove(o));
}
for (int j = 0; j < moveConceptSet.size(); j++)
moveConceptSequence.add(moveConceptSet.get(j).toString());
}
return moveConceptSequence;
}
//-------------------------------------------------------------------------
/**
* Not Supported
*/
@Override
public Tree getTree(final Game game)
{
return null;
}
//-------------------------------------------------------------------------
}
| 3,031 | 27.336449 | 90 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/datasets/sequence/StateConceptDataset.java
|
package gameDistance.datasets.sequence;
import java.util.List;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import utils.data_structures.support.zhang_shasha.Tree;
/**
* Dataset containing state concepts from trials.
* - BagOfWords
* - Sequence
*
* @author matthew.stephenson
*/
public class StateConceptDataset implements Dataset
{
@Override
public Map<String, Double> getBagOfWords(final Game game)
{
return null;
}
@Override
public List<String> getSequence(final Game game)
{
return null;
}
/**
* Not Supported
*/
@Override
public Tree getTree(final Game game)
{
return null;
}
}
| 656 | 14.642857 | 59 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/datasets/treeEdit/LudemeDataset.java
|
package gameDistance.datasets.treeEdit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import game.Game;
import gameDistance.datasets.Dataset;
import ludemeplexDetection.GetLudemeInfo;
import main.grammar.Call;
import main.grammar.LudemeInfo;
import utils.data_structures.support.zhang_shasha.Tree;
/**
* Dataset containing ludemes used for each game's description.
* - BagOfWords
* - Sequence
* - Tree
*
* @author matthew.stephenson
*/
public class LudemeDataset implements Dataset
{
//-------------------------------------------------------------------------
@Override
public Map<String, Double> getBagOfWords(final Game game)
{
final List<LudemeInfo> allLudemes = GetLudemeInfo.getLudemeInfo();
// Initialise all values to zero
final Map<String, Double> featureMap = new HashMap<>();
for (final LudemeInfo ludeme :allLudemes)
featureMap.put(ludeme.symbol().name(), Double.valueOf(0.0));
final Call callTree = game.description().callTree();
final Set<LudemeInfo> gameLudemes = callTree.analysisFormat(0, allLudemes).keySet();
for (final LudemeInfo ludeme : gameLudemes)
featureMap.put(ludeme.symbol().name(), Double.valueOf(featureMap.get(ludeme.symbol().name()).doubleValue()+1.0));
return featureMap;
}
//-------------------------------------------------------------------------
@Override
public List<String> getSequence(final Game game)
{
final List<LudemeInfo> allLudemes = GetLudemeInfo.getLudemeInfo();
final Call callTree = game.description().callTree();
final Set<LudemeInfo> gameLudemes = callTree.analysisFormat(0, allLudemes).keySet();
final List<String> ludemeSequence = new ArrayList<>();
for (final LudemeInfo ludeme : gameLudemes)
ludemeSequence.add(ludeme.symbol().name());
return ludemeSequence;
}
//-------------------------------------------------------------------------
@Override
public Tree getTree(final Game game)
{
final List<LudemeInfo> allLudemes = GetLudemeInfo.getLudemeInfo();
final Call callTree = game.description().callTree();
final String gameLudemes = callTree.preorderFormat(0, allLudemes);
final Tree ludemeTree = new Tree(gameLudemes);
return ludemeTree;
}
//-------------------------------------------------------------------------
}
| 2,356 | 28.835443 | 116 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/metrics/DistanceMetric.java
|
package gameDistance.metrics;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
/**
* Interface for distance metric classes.
*
* @author Matthew.Stephenson
*/
public interface DistanceMetric
{
/**
* @return Estimated distance between two games.
*/
double distance(final Dataset dataset, final Map<String, Double> vocabulary, final Game gameA, final Game gameB);
}
| 407 | 18.428571 | 114 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/metrics/bagOfWords/Cosine.java
|
package gameDistance.metrics.bagOfWords;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import gameDistance.metrics.DistanceMetric;
import gameDistance.utils.DistanceUtils;
import main.Constants;
//-----------------------------------------------------------------------------
/**
* https://en.wikipedia.org/wiki/Cosine_similarity
*
* @author Matthew.Stephenson, Markus
*/
public class Cosine implements DistanceMetric
{
@Override
public double distance(final Dataset dataset, final Map<String, Double> vocabulary, final Game gameA, final Game gameB)
{
final Map<String, Double> datasetA = DistanceUtils.getGameDataset(dataset, gameA);
final Map<String, Double> datasetB = DistanceUtils.getGameDataset(dataset, gameB);
double nominator = 0.0;
double denominatorA = 0.0;
double denominatorB = 0.0;
for (final String word : vocabulary.keySet())
{
double frqA = 0.0;
double frqB = 0.0;
if (datasetA.containsKey(word))
frqA = datasetA.get(word).doubleValue() * vocabulary.get(word).doubleValue();
if (datasetB.containsKey(word))
frqB = datasetB.get(word).doubleValue() * vocabulary.get(word).doubleValue();
nominator+=frqA*frqB;
denominatorA+=frqA*frqA;
denominatorB+=frqB*frqB;
}
final double denominator = Math.sqrt(denominatorA)*Math.sqrt(denominatorB);
final double finalVal = 1-(nominator/denominator);
// Handle floating point imprecision
if (finalVal < Constants.EPSILON)
return 0;
return finalVal;
}
}
| 1,525 | 26.25 | 120 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/metrics/bagOfWords/Jaccard.java
|
package gameDistance.metrics.bagOfWords;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import gameDistance.metrics.DistanceMetric;
import gameDistance.utils.DistanceUtils;
//-----------------------------------------------------------------------------
/**
* https://en.wikipedia.org/wiki/Jaccard_index
*
* @author Matthew.Stephenson, Markus
*/
public class Jaccard implements DistanceMetric
{
@Override
public double distance(final Dataset dataset, final Map<String, Double> vocabulary, final Game gameA, final Game gameB)
{
final Map<String, Double> datasetA = DistanceUtils.getGameDataset(dataset, gameA);
final Map<String, Double> datasetB = DistanceUtils.getGameDataset(dataset, gameB);
double nominator = 0.0;
double denominator = 0.0;
for (final String word : vocabulary.keySet())
{
double frqA = 0.0;
double frqB = 0.0;
if (datasetA.containsKey(word))
frqA = datasetA.get(word).doubleValue() * vocabulary.get(word).doubleValue();
if (datasetB.containsKey(word))
frqB = datasetB.get(word).doubleValue() * vocabulary.get(word).doubleValue();
nominator += Math.min(frqA,frqB);
denominator += Math.max(frqA, frqB);
}
final double finalVal = 1-(nominator/denominator);
return finalVal;
}
}
| 1,297 | 26.041667 | 120 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/metrics/bagOfWords/JensenShannonDivergence.java
|
package gameDistance.metrics.bagOfWords;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import gameDistance.metrics.DistanceMetric;
import gameDistance.utils.DistanceUtils;
//-----------------------------------------------------------------------------
/**
* https://en.wikipedia.org/wiki/Jensen%E2%80%93Shannon_divergence
*
* @author Matthew.Stephenson, Sofia, Markus
*/
public class JensenShannonDivergence implements DistanceMetric
{
@Override
public double distance(final Dataset dataset, final Map<String, Double> vocabulary, final Game gameA, final Game gameB)
{
final Map<String, Double> datasetA = DistanceUtils.getGameDataset(dataset, gameA);
final Map<String, Double> datasetB = DistanceUtils.getGameDataset(dataset, gameB);
double klDiv1 = 0.0;
double klDiv2 = 0.0;
for (final String word : vocabulary.keySet())
{
double valA = 0.0;
double valB = 0.0;
if (datasetA.containsKey(word))
valA = datasetA.get(word).doubleValue() * vocabulary.get(word).doubleValue();
if (datasetB.containsKey(word))
valB = datasetB.get(word).doubleValue() * vocabulary.get(word).doubleValue();
final double avg = (valA + valB) / 2.0;
assert (avg != 0.0);
if (valA != 0.0)
klDiv1 += valA * Math.log(valA / avg);
if (valB != 0.0)
klDiv2 += valB * Math.log(valB / avg);
}
final double jensonsShannonDivergence = (klDiv1 + klDiv2) / 2.0 / Math.log(2);
return jensonsShannonDivergence;
}
}
| 1,494 | 25.696429 | 120 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.