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/ViewController/src/view/component/custom/DieStyle.java
|
package view.component.custom;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.equipment.component.Component;
import other.context.Context;
/**
* Implementation of die component style.
*
* @author matthew.stephenson
*/
public class DieStyle extends PieceStyle
{
public DieStyle(final Bridge bridge, final Component component)
{
super(bridge, component);
setDefaultDiceDesign();
}
//----------------------------------------------------------------------------
/**
* Sets the name of the dice component based on the number of faces it has.
*/
protected void setDefaultDiceDesign()
{
if (component.getNumFaces() == 6 || component.getNumFaces() == 10 || component.getNumFaces() == 12)
component.setNameWithoutNumber("square");
else if (component.getNumFaces() == 4)
component.setNameWithoutNumber("rectangle");
else if (component.getNumFaces() == 2)
component.setNameWithoutNumber("paddle");
else
component.setNameWithoutNumber("triangle");
}
//----------------------------------------------------------------------------
@Override
protected SVGGraphics2D getSVGImageFromFilePath(final SVGGraphics2D g2d, final Context context, final int imageSize, final String filePath,
final int containerIndex, final int localState, final int value, final int hiddenValue, final int rotation, final boolean secondary)
{
final SVGGraphics2D diceImage = super.getSVGImageFromFilePath(g2d, context, imageSize, filePath, containerIndex, localState, value, hiddenValue, rotation, secondary);
final Point diceCenter = new Point(diceImage.getWidth()/2, diceImage.getHeight()/2);
final int diceValue = component.getFaces()[localState];
if (context.game().metadata().graphics().pieceForeground(context, component.owner(), component.name(), containerIndex, localState, value).size() == 0)
drawPips(context, diceCenter.x, diceCenter.y, diceValue, imageSize, diceImage);
return diceImage;
}
//----------------------------------------------------------------------------
/**
* Draws pips (or number if too many) on the dice.
*/
public void drawPips(final Context context, final int positionX, final int positionY, final int pipValue, final int imageSize, final Graphics2D g2d)
{
final int maxDieValueForPips = 6;
double pipSpacingMultiplier = 0.8;
double pipSizeFraction = 0.15;
Point2D pipTranslation = new Point2D.Double(0, 0);
if (svgName.toLowerCase().equals("triangle"))
{
pipSpacingMultiplier = 0.4;
pipSizeFraction = 0.1;
pipTranslation = new Point2D.Double(0, 0.15);
}
if (svgName.toLowerCase().equals("rectangle"))
{
pipSpacingMultiplier = 0.4;
pipSizeFraction = 0.1;
}
// draw pips on dice if 6 or less pips, unless metadata says otherwise.
if (pipValue <= maxDieValueForPips && !context.game().metadata().graphics().noDicePips())
{
final double pipSize = (int) (imageSize * pipSizeFraction);
final int dw = (int) (imageSize * pipSpacingMultiplier / 2 - pipSize);
final int dh = (int) (imageSize * pipSpacingMultiplier / 2 - pipSize);
final int dx = (int) (positionX + (imageSize * pipTranslation.getX()));
final int dy = (int) (positionY + (imageSize * pipTranslation.getY()));
final ArrayList<Point> pipPositions = new ArrayList<>();
switch (pipValue)
{
case 1:
pipPositions.add(new Point(dx, dy));
break;
case 2:
pipPositions.add(new Point(dx + dw, dy + dh));
pipPositions.add(new Point(dx - dw, dy - dw));
break;
case 3:
pipPositions.add(new Point(dx, dy));
pipPositions.add(new Point(dx + dw, dy + dh));
pipPositions.add(new Point(dx - dw, dy - dw));
break;
case 4:
pipPositions.add(new Point(dx + dw, dy + dh));
pipPositions.add(new Point(dx - dw, dy - dw));
pipPositions.add(new Point(dx - dw, dy + dh));
pipPositions.add(new Point(dx + dw, dy - dw));
break;
case 5:
pipPositions.add(new Point(dx + dw, dy + dh));
pipPositions.add(new Point(dx - dw, dy - dw));
pipPositions.add(new Point(dx - dw, dy + dh));
pipPositions.add(new Point(dx + dw, dy - dw));
pipPositions.add(new Point(dx, dy));
break;
case 6:
pipPositions.add(new Point(dx + dw, dy + dh));
pipPositions.add(new Point(dx - dw, dy - dw));
pipPositions.add(new Point(dx - dw, dy + dh));
pipPositions.add(new Point(dx + dw, dy - dw));
pipPositions.add(new Point(dx, dy + dh));
pipPositions.add(new Point(dx, dy - dw));
break;
}
for (int numPips = 0; numPips < pipPositions.size(); numPips++)
{
final int pipX = pipPositions.get(numPips).x;
final int pipY = pipPositions.get(numPips).y;
g2d.setColor(Color.BLACK);
g2d.fillOval(pipX - (int) pipSize / 2, pipY - (int) pipSize / 2, (int) pipSize, (int) pipSize);
}
}
// if more than 6 pips, draw the number on the dice instead.
else
{
final Font valueFont = new Font("Arial", Font.BOLD, imageSize / 3);
g2d.setColor(Color.BLACK);
g2d.setFont(valueFont);
final Rectangle2D rect = valueFont.getStringBounds(Integer.toString(pipValue), g2d.getFontRenderContext());
try
{
if (svgName.toLowerCase().equals("triangle"))
{
g2d.drawString(Integer.toString(pipValue), (int) (positionX - rect.getWidth() / 2),
(int) (positionY + rect.getHeight() / 1.5));
}
else
{
g2d.drawString(Integer.toString(pipValue), (int) (positionX - rect.getWidth() / 2),
(int) (positionY + rect.getHeight() / 2));
}
}
catch (final Exception e)
{
// carry on
}
}
}
}
| 5,766 | 31.954286 | 168 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/component/custom/ExtendedShogiStyle.java
|
package view.component.custom;
import java.awt.Color;
import java.awt.Font;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.equipment.component.Component;
import graphics.ImageUtil;
import other.context.Context;
import view.component.custom.types.ShogiType;
/**
* Implementation of extended Shogi piece style
* Used for games where the Shogi characters are drawn on top of blank SVGs (e.g. Taikyoku Shogi)
*
* @author matthew.stephenson
*/
public class ExtendedShogiStyle extends PieceStyle
{
public ExtendedShogiStyle(final Bridge bridge, final Component component)
{
super(bridge, component);
}
//----------------------------------------------------------------------------
@Override
protected SVGGraphics2D getSVGImageFromFilePath(final SVGGraphics2D g2dOriginal, final Context context, final int imageSize, final String filePath,
final int containerIndex, final int localState, final int value, final int hiddenValue, final int rotation, final boolean secondary)
{
final String outlinePath = ImageUtil.getImageFullPath("shogi_blank");
final SVGGraphics2D g2d = super.getSVGImageFromFilePath(g2dOriginal, context, imageSize, outlinePath, containerIndex, localState, value, hiddenValue, rotation, secondary);
final int g2dSize = g2d.getWidth();
// Temporarily rotate graphics object so that the drawn text is also rotated correctly.
final AffineTransform originalTransform = g2d.getTransform();
g2d.rotate(Math.toRadians(rotation), g2dSize/2, g2dSize/2);
for (int i = 0; i < ShogiType.values().length; i++)
{
if
(
ShogiType.values()[i].englishName().equals(svgName)
||
ShogiType.values()[i].kanji().equals(svgName)
||
ShogiType.values()[i].romaji().toLowerCase().equals(svgName.toLowerCase())
||
ShogiType.values()[i].name().toLowerCase().equals(svgName.toLowerCase())
)
{
final Font valueFont = new Font("Arial", Font.PLAIN, g2dSize/4);
g2d.setColor(Color.BLACK);
g2d.setFont(valueFont);
if (ShogiType.values()[i].kanji().length() == 1)
{
final Rectangle2D rect = valueFont.getStringBounds(Character.toString(ShogiType.values()[i].kanji().charAt(0)), g2d.getFontRenderContext());
g2d.drawString( Character.toString(ShogiType.values()[i].kanji().charAt(0)), (int)(g2dSize/2 - rect.getWidth()/2) , (int)(g2dSize/2 + rect.getHeight()/2));
break;
}
else if (ShogiType.values()[i].kanji().length() == 2)
{
Rectangle2D rect = valueFont.getStringBounds(Character.toString(ShogiType.values()[i].kanji().charAt(0)), g2d.getFontRenderContext());
g2d.drawString( Character.toString(ShogiType.values()[i].kanji().charAt(0)), (int)(g2dSize/2 - rect.getWidth()/2) , g2dSize/2);
rect = valueFont.getStringBounds(Character.toString(ShogiType.values()[i].kanji().charAt(1)), g2d.getFontRenderContext());
g2d.drawString( Character.toString(ShogiType.values()[i].kanji().charAt(1)), (int)(g2dSize/2 - rect.getWidth()/2) , (int)(g2dSize/2 + rect.getHeight()));
break;
}
else if (ShogiType.values()[i].kanji().length() == 3)
{
Rectangle2D rect = valueFont.getStringBounds(Character.toString(ShogiType.values()[i].kanji().charAt(0)), g2d.getFontRenderContext());
g2d.drawString( Character.toString(ShogiType.values()[i].kanji().charAt(0)), (int)(g2dSize/2 - rect.getWidth()/2) , (int) (g2dSize/2 - rect.getHeight()/4));
rect = valueFont.getStringBounds(Character.toString(ShogiType.values()[i].kanji().charAt(1)), g2d.getFontRenderContext());
g2d.drawString( Character.toString(ShogiType.values()[i].kanji().charAt(1)), (int)(g2dSize/2 - rect.getWidth()/2) , (int)(g2dSize/2 + rect.getHeight()/2));
rect = valueFont.getStringBounds(Character.toString(ShogiType.values()[i].kanji().charAt(2)), g2d.getFontRenderContext());
g2d.drawString( Character.toString(ShogiType.values()[i].kanji().charAt(2)), (int)(g2dSize/2 - rect.getWidth()/2) , (int)(g2dSize/2 + rect.getHeight()*1.3));
break;
}
}
}
g2d.setTransform(originalTransform);
return g2d;
}
//----------------------------------------------------------------------------
}
| 4,256 | 41.57 | 173 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/component/custom/ExtendedXiangqiStyle.java
|
package view.component.custom;
import java.awt.Color;
import java.awt.Font;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.equipment.component.Component;
import graphics.ImageUtil;
import other.context.Context;
import view.component.custom.types.XiangqiType;
/**
* Implementation of extended Xiangqi piece style
* Used for games where the Xiangqi characters are drawn on top of blank SVGs (e.g. Qi Guo Xiangxi)
*
* @author matthew.stephenson
*/
public class ExtendedXiangqiStyle extends PieceStyle
{
public ExtendedXiangqiStyle(final Bridge bridge, final Component component)
{
super(bridge, component);
}
//----------------------------------------------------------------------------
@Override
protected SVGGraphics2D getSVGImageFromFilePath(final SVGGraphics2D g2dOriginal, final Context context, final int imageSize, final String filePath,
final int containerIndex, final int localState, final int value, final int hiddenValue, final int rotation, final boolean secondary)
{
final String outlinePath = ImageUtil.getImageFullPath("disc");
SVGGraphics2D g2d = super.getSVGImageFromFilePath(g2dOriginal, context, imageSize, outlinePath, containerIndex, localState, value, hiddenValue, rotation, secondary);
final int g2dSize = g2d.getWidth();
Font valueFont = null;
// Temporarily rotate graphics object so that the drawn text is also rotated correctly.
final AffineTransform originalTransform = g2d.getTransform();
g2d.rotate(Math.toRadians(rotation), g2dSize/2, g2dSize/2);
for (int i = 0; i < XiangqiType.values().length; i++)
{
if
(
XiangqiType.values()[i].englishName().equals(svgName)
||
XiangqiType.values()[i].kanji().equals(svgName)
||
XiangqiType.values()[i].romaji().toLowerCase().equals(svgName.toLowerCase())
||
XiangqiType.values()[i].name().toLowerCase().equals(svgName.toLowerCase())
)
{
if (XiangqiType.values()[i].kanji().length() == 1)
{
valueFont = new Font("Arial", Font.PLAIN, g2dSize/2);
g2d.setColor(Color.BLACK);
g2d.setFont(valueFont);
final Rectangle2D rect = valueFont.getStringBounds(Character.toString(XiangqiType.values()[i].kanji().charAt(0)), g2d.getFontRenderContext());
g2d.drawString( Character.toString(XiangqiType.values()[i].kanji().charAt(0)), (int)(g2dSize/2 - rect.getWidth()/2) , (int)(g2dSize/2 + rect.getHeight()/3));
break;
}
else if (XiangqiType.values()[i].kanji().length() == 2)
{
valueFont = new Font("Arial", Font.PLAIN, g2dSize/3);
g2d.setColor(Color.BLACK);
g2d.setFont(valueFont);
Rectangle2D rect = valueFont.getStringBounds(Character.toString(XiangqiType.values()[i].kanji().charAt(0)), g2d.getFontRenderContext());
g2d.drawString( Character.toString(XiangqiType.values()[i].kanji().charAt(0)), (int)(g2dSize/2 - rect.getWidth()/2) , g2dSize/2);
rect = valueFont.getStringBounds(Character.toString(XiangqiType.values()[i].kanji().charAt(1)), g2d.getFontRenderContext());
g2d.drawString( Character.toString(XiangqiType.values()[i].kanji().charAt(1)), (int)(g2dSize/2 - rect.getWidth()/2) , (int)(g2dSize/2 + rect.getHeight()/1.5));
break;
}
}
}
g2d.setTransform(originalTransform);
// Couldn't find the name you were after, try and find an SVG instead (used to force western style).
if (valueFont == null)
g2d = super.getSVGImageFromFilePath(g2dOriginal, context, (int)(imageSize/1.5), filePath, containerIndex, localState, value, hiddenValue, rotation, secondary);
return g2d;
}
//----------------------------------------------------------------------------
}
| 3,759 | 38.166667 | 167 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/component/custom/NativeAmericanDiceStyle.java
|
package view.component.custom;
import java.awt.Color;
import java.awt.Rectangle;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.equipment.component.Component;
import other.context.Context;
import view.component.custom.types.NativeAmericanDiceType;
/**
* Implementation of the Native American Dice style
* Used for games which use special styles for dice, mostly native american games (e.g. Kints)
*
* @author matthew.stephenson
*/
public class NativeAmericanDiceStyle extends DieStyle
{
public NativeAmericanDiceStyle(final Bridge bridge, final Component component)
{
super(bridge, component);
setDefaultDiceDesign();
}
//----------------------------------------------------------------------------
@Override
protected SVGGraphics2D getSVGImageFromFilePath(final SVGGraphics2D g2d, final Context context, final int imageSize, final String filePath,
final int containerIndex, final int localState, final int value, final int hiddenValue, final int rotation, final boolean secondary)
{
// Rectangle that defines the position and size of the rectangle background.
final Rectangle rect = new Rectangle(0, imageSize/5, imageSize - imageSize/7, imageSize - imageSize/3 - imageSize/5);
g2d.drawRect(rect.x, rect.y, rect.width, rect.height);
NativeAmericanDiceType nativeAmericanDiceType = null;
for (int i = 0; i < NativeAmericanDiceType.values().length; i++)
if (NativeAmericanDiceType.values()[i].englishName().equals(svgName) || NativeAmericanDiceType.values()[i].name().toLowerCase().equals(svgName.toLowerCase()))
nativeAmericanDiceType = NativeAmericanDiceType.values()[i];
if (nativeAmericanDiceType == null)
return g2d;
switch(nativeAmericanDiceType)
{
case Patol1:
if (localState == 0)
break;
else if (localState == 1)
{
g2d.drawLine(rect.x + rect.width/2, rect.y, rect.x, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width/2, rect.y + rect.height);
break;
}
break;
case Patol2:
if (localState == 0)
break;
else if (localState == 1)
{
g2d.drawLine(rect.x, rect.y, rect.width, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/2, rect.y, rect.x, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width/2, rect.y + rect.height);
break;
}
break;
case Notched:
if (localState == 0)
break;
else if (localState == 1)
{
g2d.drawLine(rect.x + rect.width/5, rect.y, rect.x + rect.width/5, rect.y + rect.height/5);
g2d.drawLine(rect.x + rect.width/5 * 2, rect.y, rect.x + rect.width/5 * 2, rect.y + rect.height/5);
g2d.drawLine(rect.x + rect.width/5 * 3, rect.y, rect.x + rect.width/5 * 3, rect.y + rect.height/5);
g2d.drawLine(rect.x + rect.width/5 * 3, rect.y + rect.height, rect.x + rect.width/5 * 3, rect.y + rect.height - rect.height/5);
g2d.drawLine(rect.x + rect.width/5 * 4, rect.y + rect.height, rect.x + rect.width/5 * 4, rect.y + rect.height - rect.height/5);
break;
}
break;
case SetDilth:
if (localState == 0)
break;
else if (localState == 1)
{
g2d.drawLine(rect.x + rect.width/2, rect.y, rect.x + rect.width/3, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/2 + rect.width/6, rect.y, rect.x + rect.width/2, rect.y + rect.height);
break;
}
break;
case Nebakuthana1:
if (localState == 0)
break;
else if (localState == 1)
{
g2d.setColor(Color.RED);
g2d.drawPolygon(new int[] {rect.x + rect.width/10, rect.x + rect.width/5 + rect.width/10, rect.x + rect.width/5}, new int[] {rect.y, rect.y, rect.y + rect.height/5}, 3);
g2d.drawPolygon(new int[] {rect.x + rect.width - rect.width/10, rect.x + rect.width - rect.width/5 - rect.width/10, rect.x + rect.width - rect.width/5}, new int[] {rect.y, rect.y, rect.y + rect.height/5}, 3);
g2d.drawPolygon(new int[] {rect.x + rect.width/10, rect.x + rect.width/5 + rect.width/10, rect.x + rect.width/5}, new int[] {rect.y + rect.height, rect.y + rect.height, rect.y + rect.height - rect.height/5}, 3);
g2d.drawPolygon(new int[] {rect.x + rect.width - rect.width/10, rect.x + rect.width - rect.width/5 - rect.width/10, rect.x + rect.width - rect.width/5}, new int[] {rect.y + rect.height, rect.y + rect.height, rect.y + rect.height - rect.height/5}, 3);
break;
}
break;
case Nebakuthana2:
if (localState == 0)
break;
else if (localState == 1)
{
g2d.setColor(Color.RED);
g2d.drawLine(rect.x, rect.y + rect.height/2, rect.x + rect.width, rect.y + rect.height/2);
g2d.drawLine(rect.x + rect.width/3, rect.y, rect.x + rect.width/3*2, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/3, rect.y + rect.height, rect.x + rect.width/3*2, rect.y);
break;
}
break;
case Nebakuthana3:
if (localState == 0)
break;
else if (localState == 1)
{
g2d.setColor(Color.RED);
g2d.drawLine(rect.x + rect.width/2, rect.y + rect.height/2, rect.x + rect.width/2, rect.y + rect.height/2);
g2d.drawPolygon(new int[] {rect.x + rect.width/2, rect.x + rect.width/3, rect.x + rect.width/2, rect.x + rect.width/3*2}, new int[] {rect.y + rect.height/10, rect.y + rect.height/2, rect.y + rect.height - rect.height/10, rect.y + rect.height/2}, 4);
break;
}
break;
case Nebakuthana4:
if (localState == 0)
{
g2d.drawLine(rect.x + rect.width/8, rect.y, rect.x + rect.width/8, rect.y + rect.height/5);
g2d.drawLine(rect.x + rect.width/8 * 2, rect.y, rect.x + rect.width/8 * 2, rect.y + rect.height/5);
g2d.drawLine(rect.x + rect.width/2, rect.y, rect.x + rect.width/2 , rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/8 * 6, rect.y + rect.height, rect.x + rect.width/8 * 6, rect.y + rect.height - rect.height/5);
g2d.drawLine(rect.x + rect.width/8 * 7, rect.y + rect.height, rect.x + rect.width/8 * 7, rect.y + rect.height - rect.height/5);
break;
}
else if (localState == 1)
{
g2d.setColor(Color.GREEN);
g2d.drawLine(rect.x + rect.width/2, rect.y + rect.height/2, rect.x + rect.width/4, rect.y + rect.height/2);
g2d.drawLine(rect.x + rect.width/2, rect.y + rect.height/2, rect.x + rect.width/2 + rect.width/4, rect.y + rect.height/2);
g2d.drawLine(rect.x + rect.width/2, rect.y + rect.height/2, rect.x + rect.width/2, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/2, rect.y + rect.height/2, rect.x + rect.width/2, rect.y);
g2d.drawLine(rect.x + rect.width/2, rect.y + rect.height/2, rect.x + rect.width/4, rect.y);
g2d.drawLine(rect.x + rect.width/2, rect.y + rect.height/2, rect.x + rect.width/2 + rect.width/4, rect.y);
g2d.drawLine(rect.x + rect.width/2, rect.y + rect.height/2, rect.x + rect.width/2 + rect.width/4, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/2, rect.y + rect.height/2, rect.x + rect.width/4, rect.y + rect.height);
break;
}
break;
case Kints1:
if (localState == 0)
break;
else if (localState == 1)
{
g2d.drawLine(rect.x , rect.y, rect.x + rect.width/6, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/3 , rect.y, rect.x + rect.width/6, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/3, rect.y, rect.x + rect.width/2, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/3*2, rect.y, rect.x + rect.width/2, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/3*2, rect.y, rect.x + rect.width/6*5, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width/6*5, rect.y + rect.height);
break;
}
break;
case Kints2:
if (localState == 0)
break;
else if (localState == 1)
{
g2d.drawLine(rect.x + rect.width/2 - rect.width/6, rect.y, rect.x + rect.width/2 - rect.width/6, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/2 - rect.width/3, rect.y, rect.x + rect.width/2 - rect.width/3, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/2 + rect.width/6, rect.y, rect.x + rect.width/2 + rect.width/6, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/2 + rect.width/3, rect.y, rect.x + rect.width/2 + rect.width/3, rect.y + rect.height);
break;
}
break;
case Kints3:
if (localState == 0)
break;
else if (localState == 1)
{
g2d.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width/6, rect.y);
g2d.drawLine(rect.x + rect.width/3, rect.y + rect.height, rect.x + rect.width/6, rect.y);
g2d.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width - rect.width/6, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width - rect.width/3, rect.y, rect.x + rect.width - rect.width/6, rect.y + rect.height);
break;
}
break;
case Kints4:
if (localState == 0)
break;
else if (localState == 1)
{
g2d.drawLine(rect.x + rect.width/3, rect.y, rect.x + rect.width/3*2, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/3, rect.y + rect.height, rect.x + rect.width/3*2, rect.y);
break;
}
break;
case Kolica1:
if (localState == 1)
break;
else if (localState == 0)
{
g2d.drawPolygon(new int[] {rect.x + rect.width/10, rect.x + rect.width/5 + rect.width/10, rect.x + rect.width/5}, new int[] {rect.y, rect.y, rect.y + rect.height/5}, 3);
g2d.drawPolygon(new int[] {rect.x + rect.width - rect.width/10, rect.x + rect.width - rect.width/5 - rect.width/10, rect.x + rect.width - rect.width/5}, new int[] {rect.y, rect.y, rect.y + rect.height/5}, 3);
g2d.drawPolygon(new int[] {rect.x + rect.width/10, rect.x + rect.width/5 + rect.width/10, rect.x + rect.width/5}, new int[] {rect.y + rect.height, rect.y + rect.height, rect.y + rect.height - rect.height/5}, 3);
g2d.drawPolygon(new int[] {rect.x + rect.width - rect.width/10, rect.x + rect.width - rect.width/5 - rect.width/10, rect.x + rect.width - rect.width/5}, new int[] {rect.y + rect.height, rect.y + rect.height, rect.y + rect.height - rect.height/5}, 3);
break;
}
break;
case Kolica2:
if (localState == 1)
break;
else if (localState == 0)
{
g2d.drawLine(rect.x, rect.y + rect.height/2, rect.x + rect.width, rect.y + rect.height/2);
g2d.drawLine(rect.x + rect.width/3, rect.y, rect.x + rect.width/3*2, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/3, rect.y + rect.height, rect.x + rect.width/3*2, rect.y);
break;
}
break;
case Kolica3:
if (localState == 0)
break;
else if (localState == 1)
{
g2d.drawLine(rect.x + rect.width/2, rect.y, rect.x + rect.width/3, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/2 + rect.width/6, rect.y, rect.x + rect.width/2, rect.y + rect.height);
break;
}
break;
case Kolica4:
if (localState == 0)
break;
else if (localState == 1)
{
g2d.drawLine(rect.x + rect.width/2, rect.y, rect.x + rect.width/3, rect.y + rect.height);
g2d.drawLine(rect.x + rect.width/2 + rect.width/6, rect.y, rect.x + rect.width/2, rect.y + rect.height);
break;
}
break;
default:
break;
}
return g2d;
}
//----------------------------------------------------------------------------
}
| 11,153 | 43.261905 | 254 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/component/custom/PieceStyle.java
|
package view.component.custom;
import java.awt.Font;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.util.Arrays;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.equipment.component.Component;
import graphics.ImageConstants;
import graphics.ImageProcessing;
import graphics.svg.SVGtoImage;
import metadata.graphics.util.ValueDisplayInfo;
import metadata.graphics.util.ValueLocationType;
import other.context.Context;
import util.StringUtil;
import view.component.BaseComponentStyle;
/**
* Implementation of regular piece style, no additional code from the base component style.
*
* @author matthew.stephenson
*/
public class PieceStyle extends BaseComponentStyle
{
public PieceStyle(final Bridge bridge, final Component component)
{
super(bridge, component);
}
public PieceStyle(final Bridge bridge, final Component component, final boolean drawStringVisuals)
{
super(bridge, component);
this.drawStringVisuals = drawStringVisuals;
}
//----------------------------------------------------------------------------
@Override
protected SVGGraphics2D getSVGImageFromFilePath(final SVGGraphics2D g2dOriginal, final Context context, final int imageSize, final String filePath,
final int containerIndex, final int localState, final int value, final int hiddenValue, final int rotation, final boolean secondary)
{
SVGGraphics2D g2d = g2dOriginal;
final int scaledImageSizeX = (int) (imageSize * scaleX);
final int scaledImageSizeY = (int) (imageSize * scaleY);
final int scaledGraphicsSize = (int) (imageSize * scale(context, containerIndex, localState, value));
g2d = getBackground(g2d, context, containerIndex, localState, value, imageSize);
if (filePath != null)
{
if (Arrays.asList(ImageConstants.customImageKeywords).contains(filePath))
{
int posnX = (imageSize - scaledImageSizeX)/2;
int posnY = (imageSize - scaledImageSizeX)/2;
// TODO not sure exactly why this needs to be done for scale > 1.0
if (posnX < 0)
posnX = 0;
if (posnY < 0)
posnY = 0;
if (filePath.equalsIgnoreCase("ball") || filePath.equalsIgnoreCase("seed"))
{
if (scaledImageSizeX > 1)
ImageProcessing.ballImage(g2d, posnX, posnY, scaledImageSizeX / 2, fillColour);
}
else if (filePath.equalsIgnoreCase("marker"))
{
if (scaledImageSizeX > 1)
ImageProcessing.markerImage(g2d, posnX, posnY, scaledImageSizeX / 2, fillColour);
}
else if (filePath.equalsIgnoreCase("ring"))
{
if (scaledImageSizeX > 1)
ImageProcessing.ringImage(g2d, posnX, posnY, scaledImageSizeX, fillColour);
}
else if (filePath.equalsIgnoreCase("chocolate"))
{
if (scaledImageSizeX > 1)
ImageProcessing.chocolateImage(g2d, scaledImageSizeX, 4, fillColour);
}
}
else
{
int offsetDistance = 0;
if (scaledImageSizeX < imageSize)
offsetDistance = (imageSize-scaledImageSizeX)/2;
if (showValue.isOffsetImage() || showLocalState.isOffsetImage())
{
SVGtoImage.loadFromFilePath
(
g2d, filePath,
new Rectangle(offsetDistance, offsetDistance + (int)(scaledGraphicsSize * 0.15), scaledImageSizeX, scaledImageSizeY),
edgeColour, fillColour, rotation
);
}
else
{
SVGtoImage.loadFromFilePath
(
g2d, filePath, new Rectangle(offsetDistance, offsetDistance, scaledImageSizeX, scaledImageSizeY),
edgeColour, fillColour, rotation
);
}
}
}
else
{
final Font valueFont = new Font("Arial", Font.BOLD, (int) (scaledGraphicsSize * 0.7));
g2d.setColor(fillColour);
g2d.setFont(valueFont);
StringUtil.drawStringAtPoint(g2d, svgName, null, new Point(g2d.getWidth()/2,g2d.getHeight()/2), true);
}
g2d = getForeground(g2d, context, containerIndex, localState, value, imageSize);
// Draw local state or value on piece
g2d = displayNumberOnPiece(g2d, localState, scaledGraphicsSize, showLocalState);
g2d = displayNumberOnPiece(g2d, value, scaledGraphicsSize, showValue);
return g2d;
}
//----------------------------------------------------------------------------
/**
* Draws the local state or value on the piece if specified in metadata
*/
private SVGGraphics2D displayNumberOnPiece(final SVGGraphics2D g2d, final int value, final int scaledGraphicsSizeOriginal, final ValueDisplayInfo displayInfo)
{
final int scaledGraphicsSize = (int) (scaledGraphicsSizeOriginal * displayInfo.scale());
final ValueLocationType valueLocation = displayInfo.getLocationType();
final boolean valueOutline = displayInfo.isValueOutline();
final int offsetX = (int) (displayInfo.offsetX() * scaledGraphicsSize);
final int offsetY = (int) (displayInfo.offsetY() * scaledGraphicsSize);
if (value < 0)
return g2d;
final String printvalue = Integer.toString(value);
// Draw the state/value of the piece in its top left corner.
if (valueLocation == ValueLocationType.CornerLeft)
{
final Font valueFontCorner = new Font("Arial", Font.BOLD, scaledGraphicsSize/4);
g2d.setColor(secondaryColour);
g2d.setFont(valueFontCorner);
final Rectangle2D rect = g2d.getFont().getStringBounds(printvalue, g2d.getFontRenderContext());
if (valueOutline)
StringUtil.drawStringAtPoint(g2d, printvalue, null, new Point((int) (scaledGraphicsSize * 0.1 + rect.getWidth()/2) + offsetX, (int) (rect.getHeight()/2) + offsetY), true);
else
g2d.drawString(printvalue, (int)(scaledGraphicsSizeOriginal * 0.1) + offsetX, (int) (rect.getHeight()) + offsetY);
}
else if (valueLocation == ValueLocationType.CornerRight)
{
final Font valueFontCorner = new Font("Arial", Font.BOLD, scaledGraphicsSize/4);
g2d.setColor(secondaryColour);
g2d.setFont(valueFontCorner);
final Rectangle2D rect = g2d.getFont().getStringBounds(printvalue, g2d.getFontRenderContext());
if (valueOutline)
StringUtil.drawStringAtPoint(g2d, printvalue, null, new Point((int) (scaledGraphicsSize * 0.9 - rect.getWidth()/2) + offsetX, (int) (rect.getHeight()/2) + offsetY), true);
else
g2d.drawString(printvalue, (int)(scaledGraphicsSizeOriginal * 0.1) + offsetX, (int) (rect.getHeight()) + offsetY);
}
// Draw the state/value of the piece above it.
else if (valueLocation == ValueLocationType.Top)
{
final Font valueFontCorner = new Font("Arial", Font.BOLD, scaledGraphicsSize/4);
g2d.setColor(secondaryColour);
g2d.setFont(valueFontCorner);
final Rectangle2D rect = g2d.getFont().getStringBounds(printvalue, g2d.getFontRenderContext());
if (valueOutline)
StringUtil.drawStringAtPoint(g2d, printvalue, null, new Point((int) (scaledGraphicsSize * 0.5) + offsetX, (int) (rect.getHeight()/1.5) + offsetY), true);
else
g2d.drawString(printvalue, (int)(scaledGraphicsSizeOriginal * 0.5 - rect.getWidth()/2 - 1) + offsetX, (int) (rect.getHeight()) + offsetY);
}
// Draw the state/value of the piece on top of it.
else if (valueLocation == ValueLocationType.Middle)
{
final Font valueFontMiddle = new Font("Arial", Font.BOLD, scaledGraphicsSize/2);
g2d.setColor(secondaryColour);
g2d.setFont(valueFontMiddle);
final Rectangle2D rect = g2d.getFont().getStringBounds(printvalue, g2d.getFontRenderContext());
if (valueOutline)
StringUtil.drawStringAtPoint(g2d, printvalue, null, new Point((int) (scaledGraphicsSize * 0.5) + offsetX, (int) (scaledGraphicsSize * 0.5) + offsetY), true);
else
g2d.drawString(printvalue, (int) (scaledGraphicsSizeOriginal * 0.5 - rect.getWidth()/2 - 1) + offsetX, (int) (scaledGraphicsSizeOriginal * 0.5 + rect.getHeight()/3 - 1) + offsetY);
}
return g2d;
}
//----------------------------------------------------------------------------
}
| 7,807 | 36.902913 | 184 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/component/custom/large/DominoStyle.java
|
package view.component.custom.large;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.equipment.component.Component;
import game.equipment.container.board.Board;
import gnu.trove.list.array.TIntArrayList;
import other.context.Context;
import util.HiddenUtil;
/**
* Implementation of domino component style.
*
* @author matthew.stephenson
*/
public class DominoStyle extends LargePieceStyle
{
public DominoStyle(final Bridge bridge, final Component component)
{
super(bridge, component);
}
//----------------------------------------------------------------------------
@Override
protected SVGGraphics2D drawLargePieceVisuals(final SVGGraphics2D g2dOriginal, final TIntArrayList cellLocations, final int imageSize,
final int imageX, final int imageY, final int state, final int value, final Context context, final boolean secondary,
final int hiddenValue, final int rotation, final Board boardForLargePiece, final int containerIndex)
{
final SVGGraphics2D g2d = super.drawLargePieceVisuals(g2dOriginal, cellLocations, imageSize, imageX, imageY, state, value,
context, secondary, hiddenValue, rotation, boardForLargePiece, containerIndex);
Point2D currentPoint = new Point2D.Double();
double minCellLocationX = 99999;
double maxCellLocationX = -99999;
double minCellLocationY = 99999;
double maxCellLocationY = -99999;
for (int i = 0; i < cellLocations.size(); i++)
{
currentPoint = boardForLargePiece.topology().cells().get(cellLocations.get(i)).centroid();
if (currentPoint.getX() < minCellLocationX)
{
minCellLocationX = currentPoint.getX();
}
if (currentPoint.getX() > maxCellLocationX)
{
maxCellLocationX = currentPoint.getX();
}
if (currentPoint.getY() < minCellLocationY)
{
minCellLocationY = currentPoint.getY();
}
if (currentPoint.getY() > maxCellLocationY)
{
maxCellLocationY = currentPoint.getY();
}
}
maxCellLocationX -= minCellLocationX;
minCellLocationX -= minCellLocationX;
maxCellLocationY -= minCellLocationY;
minCellLocationY -= minCellLocationY;
final int strokeWidth = imageSize/5;
maxCellLocationX = maxCellLocationX + imageSize;
maxCellLocationY = maxCellLocationY + imageSize;
g2d.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
final GeneralPath path = new GeneralPath();
// domino outline
path.moveTo(minCellLocationX + strokeWidth/2, minCellLocationY + strokeWidth/2);
path.lineTo(minCellLocationX + strokeWidth/2, maxCellLocationY - strokeWidth/2);
path.lineTo(maxCellLocationX - strokeWidth/2, maxCellLocationY - strokeWidth/2);
path.lineTo(maxCellLocationX - strokeWidth/2, minCellLocationY + strokeWidth/2);
path.lineTo(minCellLocationX + strokeWidth/2, minCellLocationY + strokeWidth/2);
path.closePath();
final double xDistance = maxCellLocationX-minCellLocationX;
final double yDistance = maxCellLocationY-minCellLocationY;
// domino center line
if (xDistance > yDistance)
{
path.moveTo(minCellLocationX + (xDistance)/2, minCellLocationY);
path.lineTo(minCellLocationX + (xDistance)/2, maxCellLocationY);
}
else
{
path.moveTo(minCellLocationX, minCellLocationY + (yDistance)/2);
path.lineTo(maxCellLocationX, minCellLocationY + (yDistance)/2);
}
g2d.setColor(Color.BLACK);
g2d.draw(path);
final Point2D.Double[] dominoSides = {new Point2D.Double(minCellLocationX + imageSize, minCellLocationY + imageSize), new Point2D.Double(maxCellLocationX - imageSize, maxCellLocationY - imageSize)};
final int[] dominoValues = {0, 0};
if (state < 2)
{
dominoValues[0] = component.getValue();
dominoValues[1] = component.getValue2();
}
else
{
dominoValues[1] = component.getValue();
dominoValues[0] = component.getValue2();
}
for (int i = 0; i < dominoSides.length; i++)
{
if (!HiddenUtil.intToBitSet(hiddenValue).get(HiddenUtil.hiddenWhatIndex))
{
drawPips((int) dominoSides[i].x, (int) dominoSides[i].y, dominoValues[i], imageSize*2, g2d);
}
else
{
// If the what of the dominoe is hidden, draw a question mark.
final Font valueFont = new Font("Arial", Font.BOLD, (imageSize));
g2d.setFont(valueFont);
final Rectangle2D rect = valueFont.getStringBounds("?", g2d.getFontRenderContext());
g2d.drawString("?", (int)(dominoSides[i].x - rect.getWidth()/2) , (int)(dominoSides[i].y + rect.getHeight()/3));
}
}
return g2d;
}
//----------------------------------------------------------------------------
/**
* Draws pips (or number if too many) on the domino.
*/
private static void drawPips(final int positionX, final int positionY, final int pipValue, final int imageSize, final Graphics2D g2d)
{
final int maxDominoValueForPips = 9;
final double pipSpacingMultiplier = 0.8;
final double pipSizeFraction = 0.15;
final Point2D pipTranslation = new Point2D.Double(0, 0);
if (pipValue <= maxDominoValueForPips)
{
final double pipSize = (int) (imageSize * pipSizeFraction);
final int dw = (int) (imageSize * pipSpacingMultiplier / 2 - pipSize);
final int dh = (int) (imageSize * pipSpacingMultiplier / 2 - pipSize);
final int dx = (int) (positionX + (imageSize * pipTranslation.getX()));
final int dy = (int) (positionY + (imageSize * pipTranslation.getY()));
final ArrayList<Point> pipPositions = new ArrayList<>();
switch (pipValue)
{
case 1:
pipPositions.add(new Point(dx, dy));
break;
case 2:
pipPositions.add(new Point(dx + dw, dy + dh));
pipPositions.add(new Point(dx - dw, dy - dw));
break;
case 3:
pipPositions.add(new Point(dx, dy));
pipPositions.add(new Point(dx + dw, dy + dh));
pipPositions.add(new Point(dx - dw, dy - dw));
break;
case 4:
pipPositions.add(new Point(dx + dw, dy + dh));
pipPositions.add(new Point(dx - dw, dy - dw));
pipPositions.add(new Point(dx - dw, dy + dh));
pipPositions.add(new Point(dx + dw, dy - dw));
break;
case 5:
pipPositions.add(new Point(dx + dw, dy + dh));
pipPositions.add(new Point(dx - dw, dy - dw));
pipPositions.add(new Point(dx - dw, dy + dh));
pipPositions.add(new Point(dx + dw, dy - dw));
pipPositions.add(new Point(dx, dy));
break;
case 6:
pipPositions.add(new Point(dx + dw, dy + dh));
pipPositions.add(new Point(dx - dw, dy - dw));
pipPositions.add(new Point(dx - dw, dy + dh));
pipPositions.add(new Point(dx + dw, dy - dw));
pipPositions.add(new Point(dx, dy + dh));
pipPositions.add(new Point(dx, dy - dw));
break;
case 7:
pipPositions.add(new Point(dx + dw, dy + dh));
pipPositions.add(new Point(dx - dw, dy - dw));
pipPositions.add(new Point(dx - dw, dy + dh));
pipPositions.add(new Point(dx + dw, dy - dw));
pipPositions.add(new Point(dx, dy + dh));
pipPositions.add(new Point(dx, dy - dw));
pipPositions.add(new Point(dx, dy));
break;
case 8:
pipPositions.add(new Point(dx + dw, dy + dh));
pipPositions.add(new Point(dx - dw, dy - dw));
pipPositions.add(new Point(dx - dw, dy + dh));
pipPositions.add(new Point(dx + dw, dy - dw));
pipPositions.add(new Point(dx, dy + dh));
pipPositions.add(new Point(dx, dy - dw));
pipPositions.add(new Point(dx + dw, dy));
pipPositions.add(new Point(dx - dw, dy));
break;
case 9:
pipPositions.add(new Point(dx + dw, dy + dh));
pipPositions.add(new Point(dx - dw, dy - dw));
pipPositions.add(new Point(dx - dw, dy + dh));
pipPositions.add(new Point(dx + dw, dy - dw));
pipPositions.add(new Point(dx, dy + dh));
pipPositions.add(new Point(dx, dy - dw));
pipPositions.add(new Point(dx + dw, dy));
pipPositions.add(new Point(dx - dw, dy));
pipPositions.add(new Point(dx, dy));
break;
}
for (int numPips = 0; numPips < pipPositions.size(); numPips++)
{
final int pipX = pipPositions.get(numPips).x;
final int pipY = pipPositions.get(numPips).y;
g2d.setColor(Color.BLACK);
g2d.fillOval(pipX - (int) pipSize / 2, pipY - (int) pipSize / 2, (int) pipSize, (int) pipSize);
}
}
else
{
final Font valueFont = new Font("Arial", Font.BOLD, imageSize / 2);
g2d.setColor(Color.BLACK);
g2d.setFont(valueFont);
final Rectangle2D rect = valueFont.getStringBounds(Integer.toString(pipValue), g2d.getFontRenderContext());
try
{
g2d.drawString(Integer.toString(pipValue), (int) (positionX - rect.getWidth() / 2),
(int) (positionY + rect.getHeight() / 2));
}
catch (final Exception e)
{
// carry on
}
}
}
//----------------------------------------------------------------------------
}
| 8,963 | 33.08365 | 200 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/component/custom/large/LargePieceStyle.java
|
package view.component.custom.large;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import bridge.ViewControllerFactory;
import game.equipment.component.Component;
import game.equipment.container.board.Board;
import game.functions.dim.DimConstant;
import game.functions.graph.generators.basis.hex.HexagonOnHex;
import game.functions.graph.generators.basis.square.RectangleOnSquare;
import game.functions.graph.generators.basis.tri.TriangleOnTri;
import game.types.board.SiteType;
import gnu.trove.list.array.TIntArrayList;
import graphics.svg.SVGtoImage;
import other.context.Context;
import other.topology.Cell;
import view.container.ContainerStyle;
/**
* Implementation of large piece component style.
*
* @author matthew.stephenson
*/
public class LargePieceStyle extends TileStyle
{
/** In case of large Piece, here is the size. */
protected Point size;
/** In case of large Piece, here is the origin of the piece. */
private final ArrayList<Point> origin = new ArrayList<>();
/** List of offsets used for each large piece state. */
protected ArrayList<Point2D> largeOffsets = new ArrayList<>();
/** Cell locations on boardForLargePiece are adjust each time we create an image, so they need to be stored and reset afterwards. */
protected ArrayList<Point2D> originalCellLocations = new ArrayList<>();
//----------------------------------------------------------------------------
public LargePieceStyle(final Bridge bridge, final Component component)
{
super(bridge, component);
}
//----------------------------------------------------------------------------
@Override
public SVGGraphics2D getSVGImageFromFilePath(final SVGGraphics2D g2dOriginal, final Context context, final int imageSize, final String filePath,
final int containerIndex, final int localState, final int value, final int hiddenValue, final int rotation, final boolean secondary)
{
// Calculate the maximum size that this piece could be.
final int maxStepsForward = component.maxStepsForward() + 1;
final int pieceScale = maxStepsForward*2 + 1;
// Board that is "walked" on when creating images of large pieces.
Board boardForLargePiece;
final int numEdges = component.numSides();
if (numEdges == 3)
boardForLargePiece = new Board(new TriangleOnTri(new DimConstant(pieceScale)), null, null, null, null, null, Boolean.valueOf(false));
else if (numEdges == 6)
boardForLargePiece = new Board(new HexagonOnHex(new DimConstant(pieceScale)), null, null, null, null, null, Boolean.valueOf(false));
else if (numEdges == 4)
boardForLargePiece = new Board(new RectangleOnSquare(new DimConstant(pieceScale), null, null, null), null, null, null, null, null, Boolean.valueOf(false));
else
return null; // Large pieces are not possible for a component with this many sides.
boardForLargePiece.createTopology(0, context.board().topology().edges().size());
boardForLargePiece.setTopology(boardForLargePiece.topology());
boardForLargePiece.topology().computeSupportedDirection(SiteType.Cell);
boardForLargePiece.setStyle(context.board().style());
for (final Cell c : boardForLargePiece.topology().cells())
originalCellLocations.add(c.centroid());
final ContainerStyle boardForLargePieceStyle = ViewControllerFactory.createStyle(bridge, boardForLargePiece, boardForLargePiece.style(), context);
// Calculate the cell locations of the graph based on the piece walk, later user for creating the piece image.
final TIntArrayList cellLocations = component.locs(context, boardForLargePiece.numSites()/2 + 1, localState, boardForLargePiece.topology());
final double boardSizeDif = (bridge.getContainerStyle(context.board().index()).cellRadius() / boardForLargePieceStyle.cellRadius()) * bridge.getContainerStyle(context.board().index()).containerZoom();
final int boardForLargePieceSize = (int) (bridge.getContainerStyle(0).placement().getWidth() * boardSizeDif);
// default values
int imageX = 0;
int imageY = 0;
int imageWidth = 0;
int imageHeight = 0;
double minCellX = 9999;
double maxCellX = -9999;
double minCellY = 9999;
double maxCellY = -9999;
final Point2D startPoint = boardForLargePiece.topology().cells().get(cellLocations.getQuick(0)).centroid();
Point2D currentPoint = null;
for (int i = 0; i < cellLocations.size(); i++)
{
if (i > 0)
{
currentPoint = boardForLargePiece.topology().cells().get(cellLocations.get(i)).centroid();
currentPoint.setLocation((currentPoint.getX() - startPoint.getX()) * boardForLargePieceSize, (currentPoint.getY() - startPoint.getY()) * boardForLargePieceSize);
// Adjust the position of the graphs cells to line up with the screen position.
boardForLargePiece.topology().cells().get(cellLocations.get(i)).setCentroid(currentPoint.getX(), currentPoint.getY(), 0);
}
else
{
currentPoint = startPoint;
}
if (minCellX > currentPoint.getX())
minCellX = currentPoint.getX();
if (maxCellX < currentPoint.getX())
maxCellX = currentPoint.getX();
if (minCellY > currentPoint.getY())
minCellY = currentPoint.getY();
if (maxCellY < currentPoint.getY())
maxCellY = currentPoint.getY();
imageX = (int) Math.min(imageX, currentPoint.getX());
imageY = (int) Math.min(imageY, currentPoint.getY());
imageWidth = (int) Math.max(imageWidth, currentPoint.getX() + imageSize);
imageHeight = (int) Math.max(imageHeight, currentPoint.getY() + imageSize);
}
// Set the offset for the large piece.
final Point2D offsetPoint = new Point();
offsetPoint.setLocation((minCellX+((maxCellX-minCellX)/2.0)), (minCellY+((maxCellY-minCellY)/2.0)));
while(largeOffsets.size() <= localState)
largeOffsets.add(null);
largeOffsets.set(localState,offsetPoint);
// set the size of the large piece
size = new Point(imageWidth + Math.abs(imageX), imageHeight + Math.abs(imageY));
// set the origin point of the large piece
while(origin.size() <= localState)
origin.add(null);
final int x = -imageX;
final int y = size.y + imageY - imageSize;
origin.set(localState, new Point(x, y));
// store the image to return, because we need to reset the cells first.
final SVGGraphics2D g2d = new SVGGraphics2D(size.x, size.y);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
final SVGGraphics2D imageToReturn = drawLargePieceVisuals(g2d, cellLocations, imageSize, imageX, imageY, localState, value, context, secondary, hiddenValue, rotation, boardForLargePiece, containerIndex);
// reset the positions of the cells on the board
for (int i = 0; i < boardForLargePiece.topology().cells().size(); i++)
boardForLargePiece.topology().cells().get(i).setCentroid(originalCellLocations.get(i).getX(), originalCellLocations.get(i).getY(), 0);
return imageToReturn;
}
//----------------------------------------------------------------------------
/**
* Creates the image of the large piece based on the cell locations and state that is passed in.
*/
protected SVGGraphics2D drawLargePieceVisuals(final SVGGraphics2D g2d, final TIntArrayList cellLocations, final int imageSize, final int imageX, final int imageY,
final int state, final int value, final Context context, final boolean secondary, final int hiddenValue, final int rotation, final Board boardForLargePiece, final int containerIndex)
{
final String defaultFilePath = "/svg/shapes/square.svg";
final InputStream in = getClass().getResourceAsStream(defaultFilePath);
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(in)))
{
for (int i = 0; i < cellLocations.size(); i++)
{
final Point2D currentPoint = boardForLargePiece.topology().cells().get(cellLocations.get(i)).centroid();
final int y = size.y - ((int) currentPoint.getY() - imageY) - imageSize;
final int x = (int) currentPoint.getX() - imageX;
final SVGGraphics2D g2dIndividual = super.getSVGImageFromFilePath(g2d, context, imageSize, defaultFilePath, containerIndex, state, value, hiddenValue, rotation, secondary);
SVGtoImage.loadFromSource
(
g2d, g2dIndividual.getSVGDocument(), new Rectangle(x, y, imageSize+4, imageSize+4),
fillColour, fillColour, 0
);
}
}
catch (final IOException e)
{
e.printStackTrace();
}
return g2d;
}
//----------------------------------------------------------------------------
@Override
public ArrayList<Point2D> getLargeOffsets()
{
return largeOffsets;
}
@Override
public ArrayList<Point> origin()
{
return origin;
}
@Override
public Point largePieceSize()
{
return size;
}
}
| 9,032 | 38.445415 | 205 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/component/custom/large/TileStyle.java
|
package view.component.custom.large;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import java.util.Arrays;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.equipment.component.Component;
import game.equipment.component.tile.Path;
import game.functions.dim.DimConstant;
import game.functions.graph.generators.shape.Regular;
import game.types.board.SiteType;
import game.util.graph.Face;
import game.util.graph.Graph;
import other.context.Context;
import util.HiddenUtil;
import view.component.custom.PieceStyle;
/**
* Style for drawing pieces that fill the cells they are on.
* Can also include paths on the piece between edges, if specified.
*
* @author Matthew.Stephenson
*/
public class TileStyle extends PieceStyle
{
public TileStyle(final Bridge bridge, final Component component)
{
super(bridge, component);
}
//-------------------------------------------------------------------------
@Override
protected SVGGraphics2D getSVGImageFromFilePath(final SVGGraphics2D g2dOriginal, final Context context, final int imageSize,
final String filePath, final int containerIndex, final int localState, final int value, final int hiddenValue, final int rotation, final boolean secondary)
{
SVGGraphics2D g2d = new SVGGraphics2D(imageSize, imageSize);
// Rotate graphics object if needed
g2d.rotate(Math.toRadians(rotation), imageSize/2, imageSize/2);
if (HiddenUtil.intToBitSet(hiddenValue).get(HiddenUtil.hiddenIndex))
return new SVGGraphics2D(imageSize, imageSize);
final int numEdges = component.numSides();
// Secondary image for a tile also includes a outline.
if(secondary)
{
final Graph tileGraph = new Regular(null, new DimConstant(numEdges)).eval(context, SiteType.Cell);
tileGraph.normalise();
final Face tileGraphFace = tileGraph.faces().get(0);
final GeneralPath path = new GeneralPath();
for (int i = 0; i < tileGraphFace.vertices().size(); i++)
{
final game.util.graph.Vertex v = tileGraphFace.vertices().get(i);
if (i == 0)
path.moveTo(v.pt().x() * imageSize, v.pt().y() * imageSize);
else
path.lineTo(v.pt().x() * imageSize, v.pt().y() * imageSize);
}
path.closePath();
//final Color fillColour = context.game().metadata().graphics().pieceColour(context, component.owner(), component.name(), localState, value, PieceColourType.Fill);
if (fillColour != null)
g2d.setColor(fillColour);
else if (context.game().players().count() >= component.owner())
g2d.setColor(bridge.settingsColour().playerColour(context, component.owner()));
else
g2d.setColor(Color.BLACK);
g2d.fill(path);
//final Color pieceEdgeColour = context.game().metadata().graphics().pieceColour(context, component.owner(), component.name(), localState, value, PieceColourType.Edge);
if (edgeColour != null)
{
final java.awt.Shape oldClip = g2d.getClip();
g2d.setStroke(new BasicStroke(imageSize/10 + 1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2d.setColor(edgeColour);
g2d.setClip(path);
g2d.draw(path);
g2d.setClip(oldClip);
}
}
if (!HiddenUtil.intToBitSet(hiddenValue).get(HiddenUtil.hiddenWhatIndex))
{
// Add in any foreground specified in metadata
g2d = getForeground(g2d, context, containerIndex, localState, value, imageSize);
// Draw on the terminus lines
int[] terminus = component.terminus();
if (component.numTerminus().intValue() > 0)
{
terminus = new int[numEdges];
Arrays.fill(terminus, component.numTerminus().intValue());
g2d.setColor(Color.RED); // red colour by default
final double lineThicknessMultiplier = 0.33;
final int lineThickness = (int)(imageSize * lineThicknessMultiplier);
g2d.setStroke(new BasicStroke(lineThickness, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
drawPathLines(g2d, context, terminus, imageSize, numEdges);
}
}
else
{
// If the what of the tile is hidden, draw a question mark.
final Font valueFont = new Font("Arial", Font.BOLD, (imageSize));
g2d.setColor(Color.BLACK);
g2d.setFont(valueFont);
final Rectangle2D rect = valueFont.getStringBounds("?", g2d.getFontRenderContext());
g2d.drawString("?", (int)(g2d.getWidth()/2 - rect.getWidth()/2) , (int)(g2d.getHeight()/2 + rect.getHeight()/3));
}
return g2d;
}
//-------------------------------------------------------------------------
/**
* Draws the path lines on the tile based on the terminus specs.
* TODO needs to be done in a more generic manner.
*/
private void drawPathLines(final SVGGraphics2D g2d, final Context context, final int[] terminus, final int imageSize, final int numEdges)
{
int terminusSpacing = (imageSize) / (terminus[0] + 1);
if (numEdges == 4) // TODO only square tile paths supported right now
{
if (component.paths() != null)
{
terminusSpacing = (imageSize) / (component.numTerminus().intValue() + 1);
for (final Path tilePath : component.paths())
{
int ax = 0;
int ay = 0;
int bx = 0;
int by = 0;
switch (tilePath.side1().intValue())
{
case 0:
ax = terminusSpacing * (tilePath.terminus1().intValue() + 1);
ay = 0;
break;
case 1:
ax = imageSize;
ay = terminusSpacing * (tilePath.terminus1().intValue() + 1);
break;
case 2:
ax = terminusSpacing * (tilePath.terminus1().intValue() + 1);
ay = imageSize;
break;
case 3:
ax = 0;
ay = terminusSpacing * (tilePath.terminus1().intValue() + 1);
break;
}
switch (tilePath.side2().intValue())
{
case 0:
bx = terminusSpacing * (tilePath.terminus2().intValue() + 1);
by = 0;
break;
case 1:
bx = imageSize;
by = terminusSpacing * (tilePath.terminus2().intValue() + 1);
break;
case 2:
bx = terminusSpacing * (tilePath.terminus2().intValue() + 1);
by = imageSize;
break;
case 3:
bx = 0;
by = terminusSpacing * (tilePath.terminus2().intValue() + 1);
break;
}
final double off = 0.666;
final int aax = ax + (int) (off * (imageSize / 2 - ax));
final int aay = ay + (int) (off * (imageSize / 2 - ay));
final int bbx = bx + (int) (off * (imageSize / 2 - bx));
final int bby = by + (int) (off * (imageSize / 2 - by));
final GeneralPath path2 = new GeneralPath();
path2.moveTo(ax, ay);
path2.curveTo(aax, aay, bbx, bby, bx, by);
g2d.setColor(bridge.settingsColour().playerColour(context, tilePath.colour().intValue()));
g2d.draw(path2);
}
}
}
else
{
// Only square done for now
}
}
//-------------------------------------------------------------------------
@Override
public double scale(final Context context, final int containerIndex, final int localState, final int value)
{
return 1.0;
}
}
| 7,005 | 31.285714 | 171 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/component/custom/types/NativeAmericanDiceType.java
|
package view.component.custom.types;
/**
* Native American Dice types.
*
* @author Matthew.Stephenson
*/
public enum NativeAmericanDiceType
{
// Patol
Patol1("PatolDice", "blank on one side, two lines on other"),
Patol2("Dice2", "blank on one side, three lines on other"),
// Notched
Notched("NotchedDice", "blank on one side, dots on the other"),
// Set Dilth
SetDilth("SetDilthDice", "blank on one side, two lines on other near middle"),
// Nebakuthana
Nebakuthana1("NebakuthanaDice1", "blank on one side, many lines on other"),
Nebakuthana2("NebakuthanaDice2", "blank on one side, cross on other"),
Nebakuthana3("NebakuthanaDice3", "blank on one side, diamond on other"),
Nebakuthana4("NebakuthanaDice4", "line and dots on one side, star pattern of lines on other"),
// Kints
Kints1("KintsDice1", "blank on one side, zigzag on other"),
Kints2("KintsDice2", "blank on one side, four lines on other"),
Kints3("KintsDice3", "blank on one side, two triangles on other"),
Kints4("KintsDice4", "blank on one side, cross on other"),
// Kolica
Kolica1("Kolica1", "blank on one side, many lines on other"),
Kolica2("Kolica2", "blank on one side, cross on other"),
Kolica3("Kolica3", "blank on one side, two lines on other near middle"),
Kolica4("Kolica4", "blank on one side, two lines on other near middle");
//-------------------------------------------------------------------------
private String englishName;
private String description;
//--------------------------------------------------------------------------
NativeAmericanDiceType(final String englishName, final String description)
{
this.englishName = englishName;
this.description = description;
}
//-------------------------------------------------------------------------
public String englishName()
{
return englishName;
}
public String description()
{
return description;
}
//-------------------------------------------------------------------------
}
| 1,986 | 29.569231 | 95 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/component/custom/types/ShogiType.java
|
package view.component.custom.types;
/**
* Shogi types.
*
* @author Matthew.Stephenson and Eric Piette
*/
public enum ShogiType
{
KING("玉将", "gyokushō", "King"),
PRINCE("太子", "taishi", "Prince"),
GOLDGENERAL("金将", "kinshō", "Gold general"),
RIGHTGENERAL("右将", "ushō", "Right general"),
RIGHTARMY("右軍", "ugun", "Right army"),
LEFTGENERAL("左将", "sashō", "Left general"),
LEFTARMY("左軍", "sagun", "Left army"),
REARSTANDARD("後旗", "kōki", "Rear standard"),
QUEEN("奔王", "honnō", "Queen"),
FREEDREAMEATER("奔獏", "honbaku", "Free dream-eater"),
WOODENDOVE("鳩槃", "kyūhan", "Wooden dove"),
CERAMICDOVE("鳩盤", "kyūban", "Ceramic dove"),
EARTHDRAGON("地龍", "chiryū", "Earth dragon"),
FREEDEMON("奔鬼", "honki", "Free demon"),
RUNNINGHORSE("走馬", "sōma", "Running horse"),
BEASTCADET("獣曹", "jūsō", "Beast cadet"),
LONGNOSEDGOBLIN("天狗", "tengu", "Long-nosed goblin"),
MOUNTAINEAGLELEFT("山鷲鷲", "sanshū left", "Mountain eagle left"),
MOUNTAINEAGLERIGHT("山鷲山", "sanshū right", "Mountain eagle right"),
FIREDEMON("火鬼", "kaki", "Fire demon"),
FREEFIRE("奔火", "honka", "Free fire"),
WHALE("鯨鯢", "keigei", "Whale"),
GREATWHALE("大鯨", "daigei", "Great whale"),
RUNNINGRABBIT("走兎", "sōto", "Running rabbit"),
WHITETIGER("白虎", "byakko", "White tiger"),
DIVINETIGER("神虎", "shinko", "Divine tiger"),
TURTLESNAKE("玄武", "genbu", "Turtle-snake"),
DIVINETURTLE("神亀", "shinki", "Divine turtle"),
LANCE("香車", "kyōsha", "Lance"),
REVERSECHARIOT("反車", "hensha", "Reverse chariot"),
FRAGRANTELEPHANT("香象", "kōzō", "Fragrant elephant"),
ELEPHANTKING("象王", "zōō", "Elephant king"),
WHITEELEPHANT("白象", "hakuzō", "White elephant"),
TURTLEDOVE("山鳩", "sankyū", "Turtle dove"),
FLYINGSWALLOW("飛燕", "hien", "Flying swallow"),
CAPTIVEOFFICER("禽吏", "kinri", "Captive officer"),
CAPTIVEBIRD("禽鳥", "kinchō", "Captive bird"),
RAINDRAGON("雨龍", "uryū", "Rain dragon"),
FORESTDEMON("森鬼", "shinki", "Forest demon"),
THUNDERRUNNER("雷走", "raisō", "Thunder runner"),
MOUNTAINSTAG("山鹿", "sanroku", "Mountain stag"),
RUNNINGPUP("走狗", "sōku", "Running pup"),
FREELEOPARD("奔豹", "honpyō", "Free leopard"),
RUNNINGSERPENT("走蛇", "sōja", "Running serpent"),
FREESERPENT("奔蛇", "honja", "Free serpent"),
SIDESERPENT("横蛇", "ōja", "Side serpent"),
GREATSHARK("大鱗", "dairin", "Great shark"),
GREATDOVE("大鳩", "daikyū", "Great dove"),
RUNNINGTIGER("走虎", "sōko", "Running tiger"),
FREETIGER("奔虎", "honko", "Free tiger"),
RUNNINGBEAR("走熊", "sōyū", "Running bear"),
FREEBEAR("奔熊", "hon’yū", "Free bear"),
YAKSHA("夜叉", "yasha", "Yaksha"),
HEAVENLYTETRARCH("四天", "shiten", "Heavenly Tetrarch"),
BUDDHISTDEVIL("羅刹", "rasetsu", "Buddhist devil"),
GUARDIANOFTHEGODS("金剛", "kongō", "Guardian of the Gods"),
WRESTLER("力士", "rikishi", "Wrestler"),
SILVERGENERAL("銀将", "ginshō", "Silver general"),
DRUNKENELEPHANT("酔象", "suizō", "Drunken elephant"),
NEIGHBORINGKING("近王", "kinnō", "Neighboring king"),
GOLDCHARIOT("金車", "kinsha", "Gold chariot"),
PLAYFULCOCKATOO("遊母", "yūmo", "Playful cockatoo"),
SIDEDRAGON("横龍", "ōryū", "Side dragon"),
RUNNINGDRAGON("走龍", "sōryū", "Running dragon"),
RUNNINGSTAG("走鹿", "sōroku", "Running stag"),
FREESTAG("奔鹿", "honroku", "Free stag"),
RUNNINGWOLF("走狼", "sōrō", "Running wolf"),
FREEWOLF("奔狼", "honrō", "Free wolf"),
BISHOPGENERAL("角将", "kakushō", "Bishop general"),
RAINDEMON("霖鬼", "rinki", "Rain demon"),
ROOKGENERAL("飛将", "hishō", "Rook general"),
FLYINGCROCODILE("飛鰐", "higaku", "Flying crocodile"),
RIGHTTIGER("右虎", "uko", "Right tiger"),
LEFTTIGER("左虎", "sako", "Left tiger"),
RIGHTDRAGON("右龍", "uryū", "Right dragon"),
LEFTDRAGON("左龍", "saryū", "Left dragon"),
BEASTOFFICER("獣吏", "jūri", "Beast officer"),
BEASTBIRD("獣鳥", "jūchō", "Beast bird"),
WINDDRAGON("風龍", "fūryū", "Wind dragon"),
FREEDRAGON("奔龍", "honryū", "Free dragon"),
FREEPUP("奔狗", "honku", "Free pup"),
FREEDOG("奔犬", "honken", "Free dog"),
RUSHINGBIRD("行鳥", "gyōchō", "Rushing bird"),
OLDKITE("古鵄", "kotetsu", "Old kite"),
PEACOCK("孔雀", "kujaku", "Peacock"),
WATERDRAGON("水龍", "suiryū", "Water dragon"),
FIREDRAGON("火龍", "karyū", "Fire dragon"),
COPPERGENERAL("銅将", "dōshō", "Copper general"),
PHOENIXMASTER("鳳師", "hōshi", "Phoenix master"),
KIRINMASTER("麟師", "rinshi", "Kirin master"),
SILVERCHARIOT("銀車", "ginsha", "Silver chariot"),
GOOSEWING("鴻翼", "kōyoko", "Goose wing"),
VERTICALBEAR("竪熊", "shuyū", "Vertical bear"),
KNIGHT("桂馬", "keima", "Knight"),
PIGGENERAL("豚将", "tonshō", "Pig general"),
FREEPIG("奔豚", "honton", "Free pig"),
CHICKENGENERAL("鶏将", "keishō", "Chicken general"),
FREECHICKEN("奔鶏", "honkei", "Free chicken"),
PUPGENERAL("狗将", "kushō", "Pup general"),
HORSEGENERAL("馬将", "bashō", "Horse general"),
FREEHORSE("奔馬", "honba", "Free horse"),
OXGENERAL("牛将", "gyūshō", "Ox general"),
FREEOX("奔牛", "hongyū", "Free ox"),
CENTERSTANDARD("中旗", "chūki", "Center standard"),
SIDEBOAR("横猪", "ōcho", "Side boar"),
FREEBOAR("奔猪", "honcho", "Free boar"),
SILVERRABBIT("銀兎", "ginto", "Silver rabbit"),
GOLDENDEER("金鹿", "konroku", "Golden deer"),
LION("獅子", "shishi", "Lion"),
FURIOUSFIEND("奮迅", "funjin", "Furious fiend"),
CAPTIVECADET("禽曹", "kinsō", "Captive cadet"),
GREATSTAG("大鹿", "dairoku", "Great stag"),
VIOLENTDRAGON("猛龍", "mōryū", "Violent dragon"),
WOODLANDDEMON("林鬼", "rinki", "Woodland demon"),
RIGHTPHOENIX("右鵰", "ushū", "Right phoenix"),
VICEGENERAL("副将", "fukushō", "Vice general"),
GREATGENERAL("大将", "taishō", "Great general"),
STONECHARIOT("石車", "sekisha", "Stone chariot"),
WALKINGHERON("歩振", "fushin", "Walking heron"),
CLOUDEAGLE("雲鷲", "unjū", "Cloud eagle"),
STRONGEAGLE("勁鷲", "keijū", "Strong eagle"),
BISHOP("角行", "kakugyō", "Bishop"),
ROOK("飛車", "hisha", "Rook"),
SIDEWOLF("横狼", "ōrō", "Side wolf"),
FLYINGCAT("飛猫", "hibyō", "Flying cat"),
MOUNTAINFALCON("山鷹", "san’ō", "Mountain falcon"),
VERTICALTIGER("竪虎", "shuko", "Vertical tiger"),
SOLDIER("兵士", "heishi", "Soldier"),
CAVALIER("騎士", "kishi", "Cavalier"),
LITTLESTANDARD("小旗", "shōki", "Little standard"),
CLOUDDRAGON("雲龍", "unryū", "Cloud dragon"),
COPPERCHARIOT("銅車", "dōsha", "Copper chariot"),
COPPERELEPHANT("銅象", "dōzō", "Copper elephant"),
RUNNINGCHARIOT("走車", "sōsha", "Running chariot"),
BURNINGCHARIOT("炮車", "hōsha", "Burning chariot"),
RAMSHEADSOLDIER("羊兵", "yōhei", "Ram's-head soldier"),
TIGERSOLDIER("虎兵", "kohei", "Tiger soldier"),
VIOLENTOX("猛牛", "mōgyū", "Violent ox"),
GREATDRAGON("大龍", "dairyū", "Great dragon"),
ANCIENTDRAGON("元龍", "genryū, ganryū", "Ancient dragon"),
GOLDENBIRD("金翅", "kinshi", "Golden bird"),
FREEBIRD("奔翅", "honshi", "Free bird"),
DARKSPIRIT("無明", "mumyō", "Dark spirit"),
BUDDHISTSPIRIT("法性", "hōsei", "Buddhist spirit"),
DEVA("提婆", "daiba", "Deva"),
TEACHINGKING("教王", "kyōō", "Teaching king"),
WOODCHARIOT("木車", "mokusha", "Wood chariot"),
WINDSNAPPINGTURTLE("風鼈", "fūbetsu", "Wind snapping turtle"),
WHITEHORSE("白駒", "hakku", "White horse"),
GREATHORSE("大駒", "daiku", "Great horse"),
HOWLINGDOG("駒犬", "kiken", "Howling dog"), //symbol not correct, but won't render otherwise
RIGHTDOG("右犬", "uken", "Right dog"),
LEFTDOG("左犬", "saken", "Left dog"),
SIDEMOVER("横行", "ōgyō", "Side mover"),
PRANCINGSTAG("踊鹿", "yōroku", "Prancing stag"),
WATERBUFFALO("水牛", "suigyū", "Water buffalo"),
GREATDREAMEATER("大獏", "daibaku", "Great dream-eater"),
FEROCIOUSLEOPARD("猛豹", "mōhyō", "Ferocious leopard"),
FIERCEEAGLE("猛鷲", "mōjū", "Fierce eagle"),
FLYINGDRAGON("飛龍", "hiryū", "Flying dragon"),
POISONOUSSNAKE("毒蛇", "dokuja", "Poisonous snake"),
FLYINGGOOSE("鳫飛", "ganhi", "Flying goose"),
STRUTTINGCROW("烏行", "ukō", "Strutting crow"),
FLYINGFALCON("飛鷹", "hiyō", "Flying falcon"),
BLINDDOG("盲犬", "mōken", "Blind dog"),
WATERGENERAL("水将", "suishō", "Water general"),
FIREGENERAL("火将", "kashō", "Fire general"),
PHOENIX("鳳凰", "hōō", "Phoenix"),
KIRIN("麒麟", "kirin", "Kirin"),
HOOKMOVER("鉤行", "kōgyō", "Hook mover"),
LITTLETURTLE("小亀", "shōki", "Little turtle"),
TREASURETURTLE("宝亀", "hōki", "Treasure turtle"),
GREATTURTLE("大亀", "daiki", "Great turtle"),
SPIRITTURTLE("霊亀", "reiki", "Spirit turtle"),
CAPRICORN("摩羯", "makatsu", "Capricorn"),
TILECHARIOT("瓦車", "gasha", "Tile chariot"),
RUNNINGTILE("走瓦", "sōga", "Running tile"),
VERTICALWOLF("竪狼", "shurō", "Vertical wolf"),
SIDEOX("横牛", "ōgyū", "Side ox"),
DONKEY("驢馬", "roba", "Donkey"),
FLYINGHORSE("馬麟", "barin", "Flying horse"),
VIOLENTBEAR("猛熊", "mōyū", "Violent bear"),
GREATBEAR("大熊", "daiyū", "Great bear"),
ANGRYBOAR("嗔猪", "shincho", "Angry boar"),
EVILWOLF("悪狼", "akurō", "Evil wolf"),
VENOMOUSWOLF("毒狼", "dokurō", "Venomous wolf"),
LIBERATEDHORSE("風馬", "fūma", "Liberated horse"),
HEAVENLYHORSE("天馬", "temma", "Heavenly horse"),
FLYINGCOCK("鶏飛", "keihi", "Flying cock"),
RAIDINGFALCON("延鷹", "en’yō", "Raiding falcon"),
OLDMONKEY("古猿", "koen", "Old monkey"),
MOUNTAINWITCH("山母", "sanbo", "Mountain witch"),
CHINESECOCK("淮鶏", "waikei", "Chinese cock"),
WIZARDSTORK("仙鷦", "senkaku", "Wizard stork"),
NORTHERNBARBARIAN("北狄", "hokuteki", "Northern barbarian"),
SOUTHERNBARBARIAN("南蛮", "nanban", "Southern barbarian"),
WESTERNBARBARIAN("西戎", "seijū", "Western barbarian"),
EASTERNBARBARIAN("東夷", "tōi", "Eastern barbarian"),
VIOLENTSTAG("猛鹿", "mōroku", "Violent stag"),
RUSHINGBOAR("行猪", "gyōcho", "Rushing boar"),
VIOLENTWOLF("猛狼", "mōrō", "Violent wolf"),
BEARSEYES("熊眼", "yūgan", "Bear's eyes"),
TREACHEROUSFOX("隠狐", "inko, onko", "Treacherous fox"),
MOUNTAINCRANE("山鶻", "sankotsu", "Mountain crane"),
CENTERMASTER("中師", "chūshi", "Center master"),
ROCMASTER("鵬師", "hōshi", "Roc master"),
EARTHCHARIOT("土車", "dosha", "Earth chariot"),
YOUNGBIRD("𦬨鳥", "shakuchō", "Young bird"),
VERMILLIONSPARROW("朱雀", "suzaku", "Vermillion sparrow"),
DIVINESPARROW("神雀", "shinjaku", "Divine sparrow"),
BLUEDRAGON("青龍", "seiryū", "Blue dragon"),
DIVINEDRAGON("神龍", "shinryū", "Divine dragon"),
ENCHANTEDBADGER("変狸", "henri", "Enchanted badger"),
HORSEMAN("騎兵", "kihei", "Horseman"),
SWOOPINGOWL("鴟行", "shigyō", "Swooping owl"),
CLIMBINGMONKEY("登猿", "tōen", "Climbing monkey"),
CATSWORD("猫刄", "myōjin", "Cat sword"),
SWALLOWSWINGS("燕羽", "en’u", "Swallow's wings"),
GLIDINGSWALLOW("燕行", "engyō", "Gliding swallow"),
BLINDMONKEY("盲猿", "mōen", "Blind monkey"),
FLYINGSTAG("飛鹿", "hiroku", "Flying stag"),
BLINDTIGER("盲虎", "mōko", "Blind tiger"),
OXCART("牛車", "gissha", "Oxcart"),
PLODDINGOX("歬牛", "sengyū", "Plodding ox"),
SIDEFLIER("横飛", "ōhi", "Side flier"),
BLINDBEAR("盲熊", "mōyū", "Blind bear"),
OLDRAT("老鼠", "rōso", "Old rat"),
BIRDOFPARADISE("古寺", "jichō", "Bird of paradise"),
SQUAREMOVER("方行", "hōgyō", "Square mover"),
STRONGCHARIOT("強車", "kyōsha", "Strong chariot"),
COILEDSERPENT("蟠蛇", "banja", "Coiled serpent"),
COILEDDRAGON("蟠龍", "banryū", "Coiled dragon"),
RECLININGDRAGON("臥龍", "garyū", "Reclining dragon"),
FREEEAGLE("奔鷲", "honjū", "Free eagle"),
LIONHAWK("獅鷹", "shiō", "Lion hawk"),
CHARIOTSOLDIER("車兵", "shahei", "Chariot soldier"),
HEAVENLYTETRARCHKING("四天王", "shitennō", "Heavenly Tetrarch king"),
SIDESOLDIER("横兵", "ōhei", "Side soldier"),
VERTICALSOLDIER("竪兵", "shuhei", "Vertical soldier"),
WINDGENERAL("風将", "fūshō", "Wind general"),
VIOLENTWIND("暴風", "bōfū", "Violent wind"),
RIVERGENERAL("川将", "senshō", "River general"),
CHINESERIVER("淮川", "waisen", "Chinese river"),
MOUNTAINGENERAL("山将", "sanshō", "Mountain general"),
PEACEFULMOUNTAIN("泰山", "taizan", "Peaceful mountain"),
FRONTSTANDARD("前旗", "zenki", "Front standard"),
HORSESOLDIER("馬兵", "bahei", "Horse soldier"),
WOODGENERAL("木将", "mokushō", "Wood general"),
OXSOLDIER("牛兵", "gyūhei", "Ox soldier"),
RUNNINGOX("走牛", "sōgyū", "Running ox"),
EARTHGENERAL("土将", "doshō", "Earth general"),
BOARSOLDIER("猪兵", "chohei", "Boar soldier"),
RUNNINGBOAR("走猪", "sōcho", "Running boar"),
STONEGENERAL("石将", "sekishō", "Stone general"),
LEOPARDSOLDIER("豹兵", "hyōhei", "Leopard soldier"),
RUNNINGLEOPARD("走豹", "sōhyō", "Running leopard"),
TILEGENERAL("瓦将", "gashō", "Tile general"),
BEARSOLDIER("熊兵", "yūhei", "Bear soldier"),
STRONGBEAR("強熊", "kyōyū", "Strong bear"),
IRONGENERAL("鉄将", "tesshō", "Iron general"),
GREATSTANDARD("大旗", "daiki", "Great standard"),
GREATMASTER("大師", "daishi", "Great master"),
RIGHTCHARIOT("右車", "usha", "Right chariot"),
RIGHTIRONCHARIOT("右鉄車", "utessha", "Right iron chariot"),
LEFTCHARIOT("左車", "sasha", "Left chariot"),
LEFTIRONCHARIOT("左鉄車", "satessha", "Left iron chariot"),
SIDEMONKEY("横猿", "ōen", "Side monkey"),
VERTICALMOVER("竪行", "shugyō", "Vertical mover"),
FLYINGOX("飛牛", "higyū", "Flying ox"),
FIREOX("火牛", "kagyū", "Fire ox"),
LONGBOWSOLDIER("弩兵", "dohei", "Longbow soldier"),
LONGBOWGENERAL("弩将", "doshō", "Longbow general"),
VERTICALPUP("竪狗", "shuku", "Vertical pup"),
LEOPARDKING("豹王", "hyōō", "Leopard king"),
VERTICALHORSE("竪馬", "shuba", "Vertical horse"),
BURNINGSOLDIER("炮兵", "hōhei", "Burning soldier"),
BURNINGGENERAL("炮将", "hōshō", "Burning general"),
DRAGONHORSE("龍馬", "ryūme", "Dragon horse"),
DRAGONKING("龍王", "ryūō", "Dragon king"),
SWORDSOLDIER("刀兵", "tōhei", "Sword soldier"),
SWORDGENERAL("刀将", "tōshō", "Sword general"),
HORNEDFALCON("角鷹", "kakuō", "Horned falcon"),
GREATFALCON("大鷹", "daiō", "Great falcon"),
SOARINGEAGLE("飛鷲", "hijū", "Soaring eagle"),
GREATEAGLE("大鷲", "daijū", "Great eagle"),
SPEARSOLDIER("鎗兵", "sōhei", "Spear soldier"),
SPEARGENERAL("鎗将", "sōshō", "Spear general"),
VERTICALLEOPARD("竪豹", "shuhyō", "Vertical leopard"),
GREATLEOPARD("大豹", "daihyō", "Great leopard"),
SAVAGETIGER("猛虎", "mōko", "Savage tiger"),
GREATTIGER("大虎", "daiko", "Great tiger"),
CROSSBOWSOLDIER("弓兵", "kyūhei", "Cross-bow soldier"),
CROSSBOWGENERAL("弓将", "kyūshō", "Cross-bow general"),
ROARINGDOG("吼犬", "kōken", "Roaring dog"),
LIONDOG("狛犬", "komainu", "Lion dog"),
GREATELEPHANT("大象", "taizō", "Great elephant"),
DOG("犬", "inu", "Dog"),
MULTIGENERAL("雜将", "suishō", "Multi general"),
GOBETWEEN("仲人", "chūnin", "Go between"),
PAWN("歩兵", "fuhyō", "Pawn"),
EMPEROR("天王", "tennō", "Emperor"),
DOVE("鳩槃", "kyūhan", "Dove"),
POISONSNAKE("毒蛇", "dokuja", "Poison snake"),
SIDECHARIOT("走車", "sōsha", "Side chariot"),
SILVERHARE("銀兎", "ginto", "Silver hare"),
SHEDEVIL("夜叉", "yasha", "She devil"),
NEIGHBORKING("近王", "kinnō", "Neighbor king"),
STANDARDBEARER("前旗", "zenki", "Standard bearer"),
FREEEARTH("奔土", "hondo", "Free earth"),
FREEGOER("奔人", "honnin", "Free goer"),
FREESTONE("奔石", "honseki", "Free stone"),
FREEIRON("奔鉄", "hontetsu", "Free iron"),
FREETILE("奔瓦", "honga", "Free tile"),
FREECOPPER("奔銅", "hondō", "Free copper"),
FREESILVER("奔銀", "hongin", "Free silver"),
FREEGOLD("奔金", "honkin", "Free gold"),
FREECAT("奔猫", "honmyō", "Free cat"),
BAT("蝙蝠", "kōmori", "Bat"),
CHUNIN("中忍", "Chūnin", "Chunin"),
TOKIN("と", "Tokin", "Tokin"),
OSHO("玉将", "Osho", "King"),
SUIZO("酔象", "suizō", "Drunken elephant"),
PHENIX("鳳凰", "Hoo", "Phenix"),
CRANEKING("靏玉", "Kakugyoku", "Crane King"),
TENACIOUSFALCON("力鷹", "Keiyo", "Tenacious Falcon"),
SPARROWPAWN("萑歩", "Jakufu", "Sparrow Pawn"),
RACINGCHARIOT("走車", "Sosha", "Racing Chariot"),
ENCHANTEDFOX("走車", "Henko", "Enchanted Fox"),
;
//-------------------------------------------------------------------------
private String kanji;
private String romaji;
private String englishName;
//--------------------------------------------------------------------------
ShogiType(final String kanji, final String romaji, final String englishName)
{
this.kanji = kanji;
this.romaji = romaji;
this.englishName = englishName;
}
//-------------------------------------------------------------------------
public String kanji()
{
return kanji;
}
public String romaji()
{
return romaji;
}
public String englishName()
{
return englishName;
}
}
| 15,685 | 41.280323 | 97 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/component/custom/types/XiangqiType.java
|
package view.component.custom.types;
/**
* Xiangqi types.
*
* @author Matthew.Stephenson
*/
public enum XiangqiType
{
KING("周", "Zhou", "King"),
WHITEGENERAL("秦", "Qin Jiang", "General White"),
REDGENERAL("楚", "Chu Jiang", "General Red"),
ORANGEGENERAL("韓", "Han Jiang", "General Orange"),
BLUEGENERAL("齊", "Qi Jiang", "General Blue"),
GREENGENERAL("魏", "Wei Jiang", "General Green"),
BLACKGENERAL("趙", "Yan Jiang", "General Grey"),
PURPLEGENERAL("燕", "Zhao Jiang", "General Magenta"),
DEPUTYGENERAL("偏", "Pian", "Deputy General"),
OFFICER("裨", "Bai", "Officer"),
DIPLOMAT("行人", "Xing ren", "Diplomat"),
CATAPULT("砲", "Pao", "Catapult"),
ARCHER("弓", "Gong", "Archer"),
CROSSBOW("弩", "Nu", "Crossbow"),
KNIFE("刀", "Dao", "Knife"),
BROADSWORD("劍", "Jian", "Broadsword"),
KNIGHT("騎", "Qi", "Knight"),
FIRE("火", "Huo", "Fire"),
FLAG("旗", "Qi", "Flag"),
OCEAN("海", "Hai", "Ocean"),
MOUNTAIN("山", "Shan", "Mountain"),
CITY("城", "Cheng", "City"),
CHARIOT("車","Ju","Chariot"),
HORSE("馬","Ma","Horse"),
ELEPHANT("象","Xiang","Elephant"),
GUARD("仕","Shi","Guard"),
GENERAL("帅","Jiang","General"),
SOLDIER("卒","Zu","Soldier")
;
//-------------------------------------------------------------------------
private String kanji;
private String romaji;
private String englishName;
//--------------------------------------------------------------------------
XiangqiType(final String kanji, final String romaji, final String englishName)
{
this.kanji = kanji;
this.romaji = romaji;
this.englishName = englishName;
}
//-------------------------------------------------------------------------
public String kanji()
{
return kanji;
}
public String romaji()
{
return romaji;
}
public String englishName()
{
return englishName;
}
}
| 1,825 | 24.71831 | 79 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/BaseContainerStyle.java
|
package view.container;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.equipment.container.Container;
import game.types.board.SiteType;
import main.Constants;
import metadata.graphics.util.PieceStackType;
import metadata.graphics.util.PuzzleDrawHintType;
import metadata.graphics.util.StackPropertyType;
import other.context.Context;
import other.location.FullLocation;
import other.location.Location;
import other.state.container.ContainerState;
import other.topology.Cell;
import other.topology.Edge;
import other.topology.Topology;
import other.topology.TopologyElement;
import other.topology.Vertex;
import util.ContainerUtil;
import util.DeveloperGUI;
import util.GraphUtil;
import util.LocationUtil;
import util.PlaneType;
import util.StackVisuals;
import util.StringUtil;
import view.container.aspects.axes.ContainerAxis;
import view.container.aspects.components.ContainerComponents;
import view.container.aspects.designs.ContainerDesign;
import view.container.aspects.placement.ContainerPlacement;
import view.container.aspects.tracks.ContainerTrack;
/**
* Implementation of container style.
* @author matthew.stephenson and mrraow and cambolbro
*/
public abstract class BaseContainerStyle implements ContainerStyle
{
// Container components from the ECS framework
protected ContainerComponents containerComponents;
protected ContainerTrack containerTrack;
protected ContainerAxis containerAxis;
protected ContainerDesign containerDesign;
protected ContainerPlacement containerPlacement;
//-------------------------------------------------------------------------
/** Container to which this style applies. */
private final Container container;
/** Image for rendering. */
protected String imageSVGString = null;
/** Image to display the graph. */
protected String graphSVGString = null;
/** Image to display the dual. */
protected String connectionsSVGString = null;
protected Bridge bridge;
//-------------------------------------------------------------------------
/**
* Constructor.
*/
public BaseContainerStyle(final Bridge bridge, final Container container)
{
this.container = container;
this.bridge = bridge;
ContainerUtil.normaliseGraphElements(topology());
ContainerUtil.centerGraphElements(topology());
containerPlacement = new ContainerPlacement(bridge, this);
containerComponents = new ContainerComponents(bridge, this);
containerTrack = new ContainerTrack();
containerAxis = new ContainerAxis();
containerDesign = new ContainerDesign();
}
//-------------------------------------------------------------------------
/**
* Set all the required rendering values for drawing the board.
*/
public SVGGraphics2D setSVGRenderingValues()
{
final SVGGraphics2D g2d = new SVGGraphics2D((int)containerPlacement.unscaledPlacement().getWidth(), (int)containerPlacement.unscaledPlacement().getHeight());
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
return g2d;
}
//-------------------------------------------------------------------------
@Override
public void draw(final Graphics2D g2d, final PlaneType plane, final Context oriContext)
{
final Context context = oriContext.currentInstanceContext();
try
{
switch (plane)
{
case BOARD:
bridge.graphicsRenderer().drawBoard(context, g2d, containerPlacement.unscaledPlacement());
break;
case TRACK:
containerTrack.drawTracks(bridge, g2d, context, this);
break;
case AXES:
containerAxis.drawAxes(bridge, g2d);
break;
case GRAPH:
bridge.graphicsRenderer().drawGraph(context, g2d, containerPlacement.unscaledPlacement());
break;
case CONNECTIONS:
bridge.graphicsRenderer().drawConnections(context, g2d, containerPlacement.unscaledPlacement());
break;
case HINTS:
if (context.game().metadata().graphics().drawHintType() == PuzzleDrawHintType.None)
break;
containerDesign.drawPuzzleHints(g2d, context);
break;
case CANDIDATES:
containerDesign.drawPuzzleCandidates(g2d, context);
break;
case COMPONENTS:
containerComponents.drawComponents(g2d, context);
break;
case PREGENERATION:
DeveloperGUI.drawPregeneration(bridge, g2d, context, this);
break;
case INDICES:
drawIndices(g2d, context);
break;
case POSSIBLEMOVES:
drawPossibleMoves(g2d, context);
break;
case COSTS:
drawElementCost(g2d, context);
break;
default:
break;
}
}
catch (final Exception e)
{
bridge.settingsVC().setErrorReport(bridge.settingsVC().errorReport() + "VC_ERROR: Error detected when attempting to draw " + plane.name() + "\n");
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
@Override
public void render(final PlaneType plane, final Context oriContext)
{
final Context context = oriContext.currentInstanceContext();
try
{
switch (plane)
{
case BOARD:
imageSVGString = containerDesign.createSVGImage(bridge, context);
break;
case TRACK:
break;
case AXES:
break;
case GRAPH:
graphSVGString = GraphUtil.createSVGGraphImage(this);
break;
case CONNECTIONS:
connectionsSVGString = GraphUtil.createSVGConnectionsImage(this);
break;
case HINTS:
break;
case CANDIDATES:
break;
case COMPONENTS:
break;
case PREGENERATION:
break;
case INDICES:
break;
case POSSIBLEMOVES:
break;
case COSTS:
break;
default:
break;
}
}
catch (final Exception e)
{
bridge.settingsVC().setErrorReport(bridge.settingsVC().errorReport() + "VC_ERROR: Error detected when attempting to render " + plane.name() + "\n");
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Draw the cost of each element on the board (if enabled in metadata).
*/
public void drawElementCost(final Graphics2D g2d, final Context context)
{
if (context.metadata().graphics().showCost())
{
g2d.setFont(new Font(g2d.getFont().getFontName(), Font.BOLD, cellRadiusPixels()/5));
for (final TopologyElement graphElement : drawnCells())
{
g2d.setColor(new Color(0, 200, 0));
StringUtil.drawStringAtPoint(g2d, String.valueOf(graphElement.cost()), graphElement, screenPosn(graphElement.centroid()), true);
}
for (final TopologyElement graphElement : drawnEdges())
{
g2d.setColor(new Color(100, 0, 100));
StringUtil.drawStringAtPoint(g2d, String.valueOf(graphElement.cost()), graphElement, screenPosn(graphElement.centroid()), true);
}
for (final TopologyElement graphElement : drawnVertices())
{
g2d.setColor(new Color(255, 0, 0));
StringUtil.drawStringAtPoint(g2d, String.valueOf(graphElement.cost()), graphElement, screenPosn(graphElement.centroid()), true);
}
}
}
//-------------------------------------------------------------------------
/**
* Draws indices/coordinates of all graph elements, based on set preferences.
*/
public void drawIndices(final Graphics2D g2d, final Context context)
{
g2d.setFont(bridge.settingsVC().displayFont());
final List<TopologyElement> possibleElements = drawnGraphElements();
for (final TopologyElement graphElement : possibleElements)
{
if (graphElement.elementType() == SiteType.Cell)
g2d.setColor(new Color(0, 200, 0));
else if (graphElement.elementType() == SiteType.Edge)
g2d.setColor(new Color(100, 0, 100));
else if (graphElement.elementType() == SiteType.Vertex)
g2d.setColor(new Color(255, 0, 0));
if (container.index() > 0 || context.board().defaultSite() == graphElement.elementType())
drawIndexIfRequired(bridge.settingsVC().showIndices(), bridge.settingsVC().showCoordinates(), g2d, graphElement);
if (graphElement.elementType() == SiteType.Cell)
drawIndexIfRequired(bridge.settingsVC().showCellIndices(), bridge.settingsVC().showCellCoordinates(), g2d, graphElement);
else if (graphElement.elementType() == SiteType.Edge)
drawIndexIfRequired(bridge.settingsVC().showEdgeIndices(), bridge.settingsVC().showEdgeCoordinates(), g2d, graphElement);
else if (graphElement.elementType() == SiteType.Vertex)
drawIndexIfRequired(bridge.settingsVC().showVertexIndices(), bridge.settingsVC().showVertexCoordinates(), g2d, graphElement);
}
// Draw container index
g2d.setColor(new Color(0, 0, 0));
g2d.setFont(new Font("Arial", Font.BOLD, bridge.settingsVC().displayFont().getSize()*3));
if (bridge.settingsVC().showContainerIndices())
{
final Point2D.Double contianerCenter = new Point2D.Double(containerPlacement.placement().getCenterX(), containerPlacement.placement().getCenterY());
if (container.index() > 0)
contianerCenter.y = contianerCenter.y + containerPlacement.cellRadiusPixels();
StringUtil.drawStringAtPoint(g2d, "" + container.index(), null, contianerCenter, bridge.settingsVC().coordWithOutline());
}
}
/**
* Draws the index/coordinate of the specified graphElement, depending on the set preferences.
*/
private void drawIndexIfRequired(final boolean showIndices, final boolean showCoordinates, final Graphics2D g2d, final TopologyElement graphElement)
{
if (showIndices)
StringUtil.drawStringAtPoint(g2d, "" + graphElement.index(), graphElement, screenPosn(graphElement.centroid()), bridge.settingsVC().coordWithOutline());
if (showCoordinates)
StringUtil.drawStringAtPoint(g2d, "" + graphElement.label(), graphElement, screenPosn(graphElement.centroid()), bridge.settingsVC().coordWithOutline());
}
//-------------------------------------------------------------------------
/**
* Draw the possible moves that the user can perform.
* @param g2d
*/
public void drawPossibleMoves(final Graphics2D g2d, final Context context)
{
if (bridge.settingsVC().thisFrameIsAnimated() || context.game().isDeductionPuzzle())
return;
final int transparencyAmount = 125; // between 0 and 255
final int sz = Math.min(16, (int)(0.4 * containerPlacement.cellRadiusPixels()));
// Possible consequence move locations
if (bridge.settingsVC().selectingConsequenceMove())
{
for (final Location possibleToLocation : bridge.settingsVC().possibleConsequenceLocations())
{
if (ContainerUtil.getContainerId(context, possibleToLocation.site(), possibleToLocation.siteType()) == container().index())
{
final int indexOnContainer = ContainerUtil.getContainerSite(context, possibleToLocation.site(), possibleToLocation.siteType());
Point drawPosn = null;
if (possibleToLocation.siteType() == SiteType.Cell)
drawPosn = screenPosn(drawnCells().get(indexOnContainer).centroid());
if (possibleToLocation.siteType() == SiteType.Edge)
drawPosn = screenPosn(drawnEdges().get(indexOnContainer).centroid());
if (possibleToLocation.siteType() == SiteType.Vertex)
drawPosn = screenPosn(drawnVertices().get(indexOnContainer).centroid());
final ContainerState cs = context.state().containerStates()[container().index()];
final int localState = cs.state(possibleToLocation.site(), possibleToLocation.level(), possibleToLocation.siteType());
final int value = cs.value(possibleToLocation.site(), possibleToLocation.level(), possibleToLocation.siteType());
final PieceStackType componentStackType = PieceStackType.getTypeFromValue((int) context.metadata().graphics().stackMetadata(context, container(), possibleToLocation.site(), possibleToLocation.siteType(), localState, value, StackPropertyType.Type));
final int stackSize = cs.sizeStack(possibleToLocation.site(), possibleToLocation.siteType());
final Point2D.Double offsetDistance = StackVisuals.calculateStackOffset(bridge, context, container(), componentStackType, containerPlacement.cellRadiusPixels(), possibleToLocation.level(), possibleToLocation.site(), possibleToLocation.siteType(), stackSize, localState, value);
g2d.setColor(new Color(0, 0, 0, transparencyAmount));
g2d.fillOval((int) (drawPosn.x-2 - sz/2 + offsetDistance.x), (int) (drawPosn.y-2 - sz/2 + offsetDistance.y), sz+4, sz+4);
g2d.setColor(new Color(249, 166, 0, transparencyAmount));
g2d.fillOval((int) (drawPosn.x - sz/2 + offsetDistance.x), (int) (drawPosn.y - sz/2 + offsetDistance.y), sz, sz);
}
}
}
// Possible from move locations
else if (bridge.settingsVC().selectedFromLocation().equals(new FullLocation(Constants.UNDEFINED)) && !context.trial().over() && bridge.settingsVC().showPossibleMoves())
{
for (final Location location : LocationUtil.getLegalFromLocations(context))
{
if (ContainerUtil.getContainerId(context, location.site(), location.siteType()) == container().index())
{
final int indexOnContainer = ContainerUtil.getContainerSite(context, location.site(), location.siteType());
Point2D drawPosn = new Point();
if (location.siteType() == SiteType.Cell)
drawPosn = screenPosn(drawnCells().get(indexOnContainer).centroid());
if (location.siteType() == SiteType.Edge)
drawPosn = screenPosn(drawnEdges().get(indexOnContainer).centroid());
if (location.siteType() == SiteType.Vertex)
drawPosn = screenPosn(drawnVertices().get(indexOnContainer).centroid());
// take into account placement on the stack
final ContainerState cs = context.state().containerStates()[container().index()];
final int localState = cs.state(location.site(), location.level(), location.siteType());
final int value = cs.value(location.site(), location.level(), location.siteType());
final PieceStackType componentStackType = PieceStackType.getTypeFromValue((int) context.metadata().graphics().stackMetadata(context, container(), location.site(), location.siteType(), localState, value, StackPropertyType.Type));
final int stackSize = cs.sizeStack(location.site(), location.siteType());
final Point2D.Double offsetDistance = StackVisuals.calculateStackOffset(bridge, context, container(), componentStackType, containerPlacement.cellRadiusPixels(), location.level(), location.site(), location.siteType(), stackSize, localState, value);
g2d.setColor(new Color(0, 0, 0, transparencyAmount));
g2d.fillOval((int) (drawPosn.getX()-2 - sz/2 + offsetDistance.x), (int) (drawPosn.getY()-2 - sz/2 + offsetDistance.y), sz+4, sz+4);
g2d.setColor(new Color(0, 127, 255, transparencyAmount));
g2d.fillOval((int) (drawPosn.getX() - sz/2 + offsetDistance.x), (int) (drawPosn.getY() - sz/2 + offsetDistance.y), sz, sz);
}
}
}
// Possible to move locations
else
{
if (!bridge.settingsVC().selectedFromLocation().equals(new FullLocation(Constants.UNDEFINED)) && !context.trial().over() && bridge.settingsVC().showPossibleMoves())
{
for (final Location location : LocationUtil.getLegalToLocations(bridge, context))
{
if (ContainerUtil.getContainerId(context, location.site(), location.siteType()) == container().index())
{
final int indexOnContainer = ContainerUtil.getContainerSite(context, location.site(), location.siteType());
Point2D drawPosn = new Point();
if (location.siteType() == SiteType.Cell)
drawPosn = screenPosn(drawnCells().get(indexOnContainer).centroid());
if (location.siteType() == SiteType.Edge)
drawPosn = screenPosn(drawnEdges().get(indexOnContainer).centroid());
if (location.siteType() == SiteType.Vertex)
drawPosn = screenPosn(drawnVertices().get(indexOnContainer).centroid());
// take into account placement on the stack
final ContainerState cs = context.state().containerStates()[container().index()];
final int localState = cs.state(location.site(), location.level(), location.siteType());
final int value = cs.value(location.site(), location.level(), location.siteType());
final PieceStackType componentStackType = PieceStackType.getTypeFromValue((int) context.metadata().graphics().stackMetadata(context, container(), location.site(), location.siteType(), localState, value, StackPropertyType.Type));
final int stackSize = cs.sizeStack(location.site(), location.siteType());
final Point2D.Double offsetDistance = StackVisuals.calculateStackOffset(bridge, context, container(), componentStackType, containerPlacement.cellRadiusPixels(), location.level(), location.site(), location.siteType(), stackSize, localState, value);
g2d.setColor(new Color(0, 0, 0, transparencyAmount));
g2d.fillOval((int) (drawPosn.getX()-2 - sz/2 + offsetDistance.x), (int) (drawPosn.getY()-2 - sz/2 + offsetDistance.y), sz+4, sz+4);
g2d.setColor(new Color(255, 0, 0, transparencyAmount));
g2d.fillOval((int) (drawPosn.getX() - sz/2 + offsetDistance.x), (int) (drawPosn.getY() - sz/2 + offsetDistance.y), sz, sz);
}
}
}
}
}
//-------------------------------------------------------------------------
@Override
public List<TopologyElement> drawnGraphElements()
{
final List<TopologyElement> allGraphElements = new ArrayList<>();
for (final TopologyElement g : drawnCells())
allGraphElements.add(g);
for (final TopologyElement g : drawnEdges())
allGraphElements.add(g);
for (final TopologyElement g : drawnVertices())
allGraphElements.add(g);
return allGraphElements;
}
//-------------------------------------------------------------------------
@Override
public TopologyElement drawnGraphElement(final int index, final SiteType graphElementType)
{
if (graphElementType == SiteType.Cell)
for (final TopologyElement g : drawnCells())
if (g.index() == index)
return g;
if (graphElementType == SiteType.Edge)
for (final TopologyElement g : drawnEdges())
if (g.index() == index)
return g;
if (graphElementType == SiteType.Vertex)
for (final TopologyElement g : drawnVertices())
if (g.index() == index)
return g;
return null;
}
//-------------------------------------------------------------------------
public SiteType getElementType(final int index)
{
for (final TopologyElement element : drawnGraphElements())
if (element.index() == index)
return element.elementType();
return null;
}
//-------------------------------------------------------------------------
@Override
public String graphSVGImage()
{
return graphSVGString;
}
@Override
public String dualSVGImage()
{
return connectionsSVGString;
}
@Override
public String containerSVGImage()
{
return imageSVGString;
}
@Override
public List<Cell> drawnCells()
{
return containerPlacement.drawnCells();
}
@Override
public List<Edge> drawnEdges()
{
return containerPlacement.drawnEdges();
}
@Override
public List<Vertex> drawnVertices()
{
return containerPlacement.drawnVertices();
}
@Override
public Topology topology()
{
return container().topology();
}
@Override
public final double pieceScale()
{
return containerComponents.pieceScale();
}
@Override
public double containerZoom()
{
return containerPlacement.containerZoom();
}
@Override
public void drawPuzzleValue(final int value, final int site, final Context context, final Graphics2D g2d, final Point drawPosn, final int imageSize)
{
containerComponents.drawPuzzleValue(value, site, context, g2d, drawPosn, imageSize);
}
@Override
public Container container()
{
return container;
}
@Override
public Rectangle placement()
{
return containerPlacement.placement();
}
@Override
public int maxDim()
{
return (int) Math.max(containerPlacement.placement().getWidth(), containerPlacement.placement().getHeight());
}
@Override
public double cellRadius()
{
return containerPlacement.cellRadius();
}
@Override
public int cellRadiusPixels()
{
return containerPlacement.cellRadiusPixels();
}
@Override
public Point screenPosn(final Point2D posn)
{
return containerPlacement.screenPosn(posn);
}
@Override
public void setPlacement(final Context context, final Rectangle placement)
{
containerPlacement.setPlacement(context, placement);
}
@Override
public final double containerScale()
{
return containerPlacement.containerScale();
}
@Override
public boolean ignorePieceSelectionLimit()
{
return containerDesign.ignorePieceSelectionLimit();
}
@Override
public Rectangle unscaledPlacement()
{
return containerPlacement.unscaledPlacement();
}
}
| 20,848 | 34.517888 | 282 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/ContainerStyle.java
|
package view.container;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.util.List;
import game.equipment.container.Container;
import game.types.board.SiteType;
import other.context.Context;
import other.topology.Cell;
import other.topology.Edge;
import other.topology.Topology;
import other.topology.TopologyElement;
import other.topology.Vertex;
import util.PlaneType;
/**
* Something to be drawn.
* View part of MVC for equipment.
* @author Matthew.Stephenson and cambolbro
*/
public interface ContainerStyle
{
/**
* Renders the string description of SVG graphic to a graphics plane.
*/
void render(final PlaneType plane, final Context context);
/**
* Draws specified layer to the supplied graphics context.
*/
void draw(Graphics2D g2d, final PlaneType plane, final Context context);
/**
* Sets the dimensions of the container, set by the view that it is to be placed in.
* @param context
* @param rectangle
*/
void setPlacement(final Context context, final Rectangle rectangle);
void setDefaultBoardScale(final double scale);
//-------------------------------------------------------------------------
/**
* Get the SVG image for the container (i.e. the board image).
*/
String containerSVGImage();
/**
* Get the SVG image for the graph of the container.
*/
String graphSVGImage();
/**
* Get the SVG image for the dual of the container.
*/
String dualSVGImage();
/**
* Get the cells of the graph that should be visible.
*/
List<Cell> drawnCells();
/**
* Get the edges of the graph that should be visible.
*/
List<Edge> drawnEdges();
/**
* Get the vertices of the graph that should be visible.
*/
List<Vertex> drawnVertices();
/**
* Get all graph elements that should be visible.
*/
List<TopologyElement> drawnGraphElements();
/**
* Return the visible graph element defined by the index and type specified.
* @param index
* @param graphElementType
*/
TopologyElement drawnGraphElement(int index, SiteType graphElementType);
/**
* Get the placement of the container.
*/
Rectangle placement();
/**
* Get the placement of the container.
*/
Rectangle unscaledPlacement();
/**
* Get the cell radius of the container (between 0 and 1).
*/
double cellRadius();
/**
* Get the cell radius of the container (screen position).
*/
int cellRadiusPixels();
/**
* Get the screen position for a specified world position.
*/
Point screenPosn(final Point2D posn);
/**
* Get the scale of the container.
*/
double containerScale();
/**
* Get the zoom of the container.
*/
double containerZoom();
/**
* Get the container style specific piece scale.
*/
double pieceScale();
/**
* Get the graph of the container for this style.
*/
Topology topology();
/**
* Draw the puzzle value on the graphics object.
*/
void drawPuzzleValue(int puzzleValue, int site, Context context, Graphics2D graphics, Point point, int buttonSize);
/**
* If there is no minimum selection distance for a piece.
*/
boolean ignorePieceSelectionLimit();
/**
* The container associated with this style
*/
Container container();
int maxDim();
}
| 3,264 | 20.480263 | 116 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/axes/BoardAxis.java
|
package view.container.aspects.axes;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import bridge.Bridge;
import other.topology.AxisLabel;
import other.topology.TopologyElement;
import util.StringUtil;
import view.container.styles.BoardStyle;
/**
* Board axis properties.
*
* @author Matthew.Stephenson
*/
public class BoardAxis extends ContainerAxis
{
protected BoardStyle boardStyle;
//-------------------------------------------------------------------------
public BoardAxis(final BoardStyle boardStyle)
{
this.boardStyle = boardStyle;
}
//-------------------------------------------------------------------------
@Override
public void drawAxes(final Bridge bridge, final Graphics2D g2d)
{
final double fontBufferSize = bridge.settingsVC().displayFont().getSize()/boardStyle.placement().getHeight();
final List<AxisLabel> axisLabels = getAxisLabels(fontBufferSize);
final Font oldFont = g2d.getFont();
g2d.setFont(bridge.settingsVC().displayFont());
g2d.setColor(new Color(0, 0, 0));
for (final AxisLabel al : axisLabels)
{
final String label = al.label();
final Point drawPosn = boardStyle.screenPosn(al.posn());
StringUtil.drawStringAtPoint(g2d, label, null, drawPosn, true);
}
g2d.setFont(oldFont);
}
//-------------------------------------------------------------------------
/**
* Determine the axis labels for the board.
*/
protected List<AxisLabel> getAxisLabels(final double fontSize)
{
final int numCols = boardStyle.container().topology().columns(boardStyle.container().defaultSite()).size();
final int numRows = boardStyle.container().topology().rows(boardStyle.container().defaultSite()).size();
final double cellRadius = boardStyle.cellRadius();
final List<AxisLabel> axisLabels = new ArrayList<>();
double minX = 9999.9;
double minY = 9999.9;
double maxX = -9999.9;
double maxY = -9999.9;
for (final TopologyElement v : boardStyle.topology().getGraphElements(boardStyle.container().defaultSite()))
{
if (v.centroid().getX() < minX)
minX = v.centroid().getX();
if (v.centroid().getY() < minY)
minY = v.centroid().getY();
if (v.centroid().getX() > maxX)
maxX = v.centroid().getX();
if (v.centroid().getY() > maxY)
maxY = v.centroid().getY();
}
if (boardStyle.container().topology().numEdges() == 4)
{
final int[] dim = {numRows, numCols};
// Create axis labels
axisLabels.clear();
for (int row = 0; row < dim[0]; row++)
{
final String label = String.format("%d", Integer.valueOf((row + 1)));
final double x = minX - cellRadius - fontSize;
final double y = minY + cellRadius*2 * row;
final AxisLabel axisLabel = new AxisLabel(label, x, y);
axisLabels.add(axisLabel);
}
for (int col = 0; col < dim[1]; col++)
{
final String label = String.format("%c", Character.valueOf((char) ('A' + col)));
final double x = minX + cellRadius*2 * col;
final double y = minY - cellRadius - fontSize;
final AxisLabel axisLabel = new AxisLabel(label, x, y);
axisLabels.add(axisLabel);
}
}
return axisLabels;
}
}
| 3,226 | 26.117647 | 111 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/axes/ContainerAxis.java
|
package view.container.aspects.axes;
import java.awt.Graphics2D;
import bridge.Bridge;
/**
* Container axis properties
*
* @author Matthew.Stephenson
*/
public class ContainerAxis
{
public void drawAxes(final Bridge bridge, final Graphics2D g2d)
{
// No axes by default.
}
}
| 291 | 13.6 | 64 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/components/ContainerComponents.java
|
package view.container.aspects.components;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import bridge.Bridge;
import game.equipment.component.Component;
import game.equipment.container.Container;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import main.Constants;
import metadata.graphics.util.PieceColourType;
import metadata.graphics.util.PieceStackType;
import metadata.graphics.util.StackPropertyType;
import other.context.Context;
import other.location.FullLocation;
import other.location.Location;
import other.state.State;
import other.state.container.ContainerState;
import other.topology.Cell;
import other.topology.TopologyElement;
import other.topology.Vertex;
import util.ContainerUtil;
import util.GraphUtil;
import util.HiddenUtil;
import util.ImageInfo;
import util.StackVisuals;
import view.container.BaseContainerStyle;
/**
* Defines how the components are drawn on the associated container style.
*
* @author Matthew.Stephenson
*/
public class ContainerComponents
{
/** The container style associated with this components aspect. */
private final BaseContainerStyle containerStyle;
/** Additional piece scale multiplier for components in this style. */
private double pieceScale = 1.0;
/** Parent bridge object. */
protected Bridge bridge;
//-------------------------------------------------------------------------
public ContainerComponents(final Bridge bridge, final BaseContainerStyle containerStyle)
{
this.bridge = bridge;
this.containerStyle = containerStyle;
}
//-------------------------------------------------------------------------
/**
* Draw all necessary components on the container.
*/
public void drawComponents(final Graphics2D g2d, final Context context)
{
final List<TopologyElement> allGraphElements = GraphUtil.reorderGraphElementsTopDown(containerStyle.drawnGraphElements(), context);
drawComponents(g2d, context, (ArrayList<? extends TopologyElement>) allGraphElements);
}
//-------------------------------------------------------------------------
/**
* Draw all necessary components on the container, on a provided set of graphElements.
*/
protected void drawComponents(final Graphics2D g2d, final Context context, final ArrayList<? extends TopologyElement> allGraphElements)
{
final State state = context.state();
final Container container = containerStyle.container();
final int cellRadiusPixels = containerStyle.cellRadiusPixels();
final Moves legal = context.moves(context);
if (container != null && state.containerStates().length > container.index())
{
if (context.metadata().graphics().replaceComponentsWithFilledCells())
{
fillCellsBasedOnOwner(g2d, context);
return;
}
final ContainerState cs = state.containerStates()[container.index()];
// Draw pieces
for (int j = 0; j < allGraphElements.size(); j++)
{
final TopologyElement graphElement = allGraphElements.get(j);
final Point2D posn = graphElement.centroid();
final int site = allGraphElements.get(j).index();
final SiteType type = graphElement.elementType();
final boolean isEmpty = cs.isEmpty(site, type);
final int stackSize = cs.sizeStack(site, type);
for (int level = 0; level < stackSize; level++)
{
final int what = cs.what(site, level, type);
if (!isEmpty)
{
int localState = cs.state(site, level, type);
final int value = cs.value(site, level, type);
final Component component = context.equipment().components()[what];
// if the what is zero, then it's a hidden piece.
if (what == 0)
{
// Cannot hide the what for games with large pieces.
if (context.game().hasLargePiece())
continue;
component.setRoleFromPlayerId(cs.who(site, level, type));
component.create(context.game());
}
// When drawing dice, use local state of the next roll.
if (component.isDie())
{
final int diceLocalState = context.diceSiteState().get(site);
if (diceLocalState != -99)
localState = diceLocalState;
}
final int mover = context.state().mover();
int count = cs.count(site, type);
if (HiddenUtil.siteCountHidden(context, cs, site, level, mover, type))
count = -1;
if (HiddenUtil.siteHidden(context, cs, site, level, mover, type))
count = 0;
double transparency = 0;
if
(
bridge.settingsVC().selectedFromLocation().site() == site
&&
bridge.settingsVC().selectedFromLocation().level() == level
&&
bridge.settingsVC().selectedFromLocation().siteType() == type
)
transparency = 0.5;
int imageSize = (int) (cellRadiusPixels * 2 * pieceScale() * bridge.getComponentStyle(component.index()).scale(context, container.index(), localState, value));
imageSize = Math.max(imageSize, Constants.MIN_IMAGE_SIZE); // Image must be at least 2 pixels in size.
final PieceStackType componentStackType = PieceStackType.getTypeFromValue((int) context.metadata().graphics().stackMetadata(context, container, site, type, localState, value, StackPropertyType.Type));
final Point2D.Double stackOffset = StackVisuals.calculateStackOffset(bridge, context, container, componentStackType, cellRadiusPixels, level, site, type, stackSize, localState,value);
final Point drawPosn = containerStyle.screenPosn(posn);
drawPosn.x += stackOffset.x - imageSize/2;
drawPosn.y += stackOffset.y - imageSize/2;
// These values are used for large pieces to represent vector from origin to center
if (component.isLargePiece() && bridge.getComponentStyle(component.index()).origin().size() > localState && container.index() == 0)
{
final Point origin = bridge.getComponentStyle(component.index()).origin().get(localState);
if (origin != null)
{
drawPosn.x -= origin.x;
drawPosn.y -= origin.y;
}
}
if (bridge.settingsVC().pieceBeingDragged() || bridge.settingsVC().thisFrameIsAnimated())
{
try
{
Location location;
if (bridge.settingsVC().pieceBeingDragged())
location = bridge.settingsVC().selectedFromLocation();
else
location = bridge.settingsVC().getAnimationMove().getFromLocation();
if
(
location.equals(new FullLocation(site, level, type))
||
(
// If dragging/animating a piece in a stack, don't draw the above pieces either.
site == location.site()
&&
type == location.siteType()
&&
level >= StackVisuals.getLevelMinAndMax(legal, location)[0]
&&
level <= StackVisuals.getLevelMinAndMax(legal, location)[1]
)
)
{
if (count > 1)
count--;
else
continue;
}
}
catch (final Exception e)
{
// carry on, sometimes animation timers don't line up...
}
}
if (component.isTile() && container.index() == 0 && !HiddenUtil.siteHidden(context, cs, site, level, mover, type))
for (final Integer cellIndex : ContainerUtil.cellsCoveredByPiece(context, container, component, site, localState))
drawTilePiece(g2d, context, component, cellIndex.intValue(), stackOffset.x, stackOffset.y, container, localState, value, imageSize);
bridge.graphicsRenderer().drawComponent(g2d, context, new ImageInfo(drawPosn, site, level, type, component, localState, value, transparency, cs.rotation(site, level, type), container.index(), imageSize, count));
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Draws a tile component at the specified site.
*/
private void drawTilePiece(final Graphics2D g2d, final Context context, final Component component, final int site, final double stackOffsetX, final double stackOffsetY, final Container container, final int localState, final int value, final int imageSize)
{
final GeneralPath path = new GeneralPath();
final int containerSite = ContainerUtil.getContainerSite(context, site, SiteType.Cell);
final int containerIndex = ContainerUtil.getContainerId(context, containerSite, SiteType.Cell);
final Cell cellToFill = bridge.getContainerStyle(container.index()).drawnCells().get(containerSite);
Point nextPoint = bridge.getContainerStyle(container.index()).screenPosn(cellToFill.vertices().get(0).centroid());
path.moveTo(nextPoint.x + stackOffsetX, nextPoint.y + stackOffsetY);
for (final Vertex vertex : cellToFill.vertices())
{
nextPoint = bridge.getContainerStyle(container.index()).screenPosn(vertex.centroid());
path.lineTo(nextPoint.x + stackOffsetX, nextPoint.y + stackOffsetY);
}
path.closePath();
final Color fillColour = context.game().metadata().graphics().pieceColour(context, component.owner(), component.name(), containerIndex, localState, value, PieceColourType.Fill);
if (fillColour != null)
g2d.setColor(fillColour);
else
g2d.setColor(bridge.settingsColour().playerColour(context, component.owner()));
g2d.fill(path);
final Color pieceEdgeColour = context.game().metadata().graphics().pieceColour(context, component.owner(), component.name(), containerIndex, localState, value, PieceColourType.Edge);
if (pieceEdgeColour != null)
{
final Shape oldClip = g2d.getClip();
g2d.setStroke(new BasicStroke(imageSize/10 + 1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2d.setColor(pieceEdgeColour);
g2d.setClip(path);
g2d.draw(path);
g2d.setClip(oldClip);
}
}
//-------------------------------------------------------------------------
/**
* Fills cells of the container that are owned by specific players with their colour.
*/
public void fillCellsBasedOnOwner(final Graphics2D g2d, final Context context)
{
final ContainerState cs = context.state().containerStates()[0];
for (int f = 0; f < context.topology().cells().size(); f++)
{
if (cs.whoCell(f) != 0)
{
final Cell face = context.topology().cells().get(f);
final GeneralPath path = new GeneralPath();
for (int v = 0; v < face.vertices().size(); v++)
{
if (path.getCurrentPoint() == null)
{
final Vertex prev = face.vertices().get(face.vertices().size() - 1);
final Point drawPrev = containerStyle.screenPosn(prev.centroid());
path.moveTo(drawPrev.x, drawPrev.y);
}
final Vertex corner = face.vertices().get(v);
final Point drawCorner = containerStyle.screenPosn(corner.centroid());
path.lineTo(drawCorner.x, drawCorner.y);
}
g2d.setColor(bridge.settingsColour().playerColour(context, cs.whoCell(f)));
g2d.fill(path);
}
}
}
//-------------------------------------------------------------------------
/**
* Draws a puzzle value at a specified site.
*/
public void drawPuzzleValue(final int value, final int site, final Context context, final Graphics2D g2d, final Point drawPosn, final int imageSize)
{
// Do nothing by default.
}
//-------------------------------------------------------------------------
public double pieceScale()
{
return pieceScale;
}
public void setPieceScale(final double pieceScale)
{
this.pieceScale = pieceScale;
}
//-------------------------------------------------------------------------
}
| 11,691 | 35.198142 | 256 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/components/board/BackgammonComponents.java
|
package view.container.aspects.components.board;
import bridge.Bridge;
import view.container.BaseContainerStyle;
import view.container.aspects.components.ContainerComponents;
/**
* Backgammon components properties.
*
* @author Matthew.Stephenson
*/
public class BackgammonComponents extends ContainerComponents
{
public BackgammonComponents(final Bridge bridge, final BaseContainerStyle containerStyle)
{
super(bridge, containerStyle);
setPieceScale(1.1);
}
//-------------------------------------------------------------------------
}
| 555 | 23.173913 | 91 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/components/board/Connect4Components.java
|
package view.container.aspects.components.board;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.util.List;
import bridge.Bridge;
import game.equipment.container.Container;
import other.context.Context;
import other.state.State;
import other.state.container.ContainerState;
import other.topology.Cell;
import view.container.aspects.components.ContainerComponents;
import view.container.aspects.placement.Board.Connect4Placement;
import view.container.styles.board.Connect4Style;
/**
* Connect4 components properties.
*
* @author Matthew.Stephenson
*/
public class Connect4Components extends ContainerComponents
{
private final Connect4Style boardStyle;
private final Connect4Placement boardPlacement;
//-------------------------------------------------------------------------
public Connect4Components(final Bridge bridge, final Connect4Style containerStyle, final Connect4Placement containerPlacement)
{
super(bridge, containerStyle);
boardStyle = containerStyle;
boardPlacement = containerPlacement;
}
//-------------------------------------------------------------------------
@Override
public void drawComponents(final Graphics2D g2d, final Context context)
{
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
final List<Cell> cells = boardStyle.topology().cells();
final Rectangle placement = boardStyle.placement();
final String label = "Board";
final Container equip = context.game().mapContainer().get(label);
if (cells.isEmpty())
{
System.out.println("** Connect4Style.drawStyle(): Board has no cells.");
return;
}
final int u = (int) ((cells.get(1).centroid().getX() - cells.get(0).centroid().getX()) * placement.width);
final int r = (int) (0.425 * u + 0.5);
if (equip != null)
{
// This game has a board
final State state = context.state();
final ContainerState cs = state.containerStates()[0];
for (int site = 0; site < boardStyle.topology().cells().size(); site++)
{
final Point2D pixel = cells.get(site).centroid();
final int levelNumber = cs.sizeStackCell(site);
for (int level = 0; level < levelNumber; level++)
{
final int who = cs.whoCell(site, level);
if (who == 0)
break;
// Draw this piece
final int cx = (int) (pixel.getX() * placement.width);
final int cy = (int) (pixel.getY() * placement.width + (boardPlacement.connect4Rows() - 1) * u - level * u
+ placement.y);
g2d.setColor(bridge.settingsColour().playerColour(context, who));
g2d.fillArc(cx - r, cy - r, 2 * r, 2 * r, 0, 360);
}
}
}
}
//-------------------------------------------------------------------------
}
| 3,294 | 33.322917 | 127 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/components/board/MancalaComponents.java
|
package view.container.aspects.components.board;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import bridge.Bridge;
import game.equipment.component.Component;
import game.equipment.container.Container;
import game.equipment.container.board.Board;
import game.equipment.container.board.custom.MancalaBoard;
import game.equipment.other.Map;
import game.types.board.SiteType;
import game.types.board.StoreType;
import graphics.ImageProcessing;
import main.math.MathRoutines;
import metadata.graphics.Graphics;
import other.concept.Concept;
import other.context.Context;
import other.state.State;
import other.state.container.ContainerState;
import other.topology.Topology;
import view.container.aspects.components.ContainerComponents;
import view.container.styles.BoardStyle;
import view.container.styles.board.MancalaStyle;
/**
* Mancala components properties.
*
* @author Matthew.Stephenson and cambolbro and Eric.Piette
*/
public class MancalaComponents extends ContainerComponents
{
private final BoardStyle boardStyle;
//-------------------------------------------------------------------------
public MancalaComponents(final Bridge bridge, final MancalaStyle containerStyle)
{
super(bridge, containerStyle);
boardStyle = containerStyle;
}
//-------------------------------------------------------------------------
/** Colour of the seeds. */
private final Color seedColour = new Color(255, 255, 230);
/** Piece placements. */
private final Point2D.Double[][] offsets =
{
{},
{
// 1 seed
new Point2D.Double(0, 0),
},
{
// 2 seeds
new Point2D.Double(-1, 0),
new Point2D.Double( 1, 0),
},
{
// 3 seeds
new Point2D.Double(-1.0, -0.8),
new Point2D.Double( 1.0, -0.8),
new Point2D.Double( 0.0, 1.0),
},
{
// 4 seed
new Point2D.Double(-1.0, -1.0),
new Point2D.Double( 1.0, -1.0),
new Point2D.Double(-1.0, 1.0),
new Point2D.Double( 1.0, 1.0),
},
{
// 5 seeds
new Point2D.Double(-1.0, -1.0),
new Point2D.Double( 1.0, -1.0),
new Point2D.Double(-1.0, 1.0),
new Point2D.Double( 1.0, 1.0),
new Point2D.Double( 0.0, 0.0),
},
};
//-------------------------------------------------------------------------
@Override
public void drawComponents(final Graphics2D g2d, final Context context)
{
final boolean stackingGame = context.game().isStacking();
final Rectangle placement = boardStyle.placement();
final int cellRadiusPixels = boardStyle.cellRadiusPixels();
final boolean circleTiling = context.game().booleanConcepts().get(Concept.CircleTiling.id());
// Set the seed size
final boolean withStore = (context.board() instanceof MancalaBoard)
? !((MancalaBoard) context.board()).storeType().equals(StoreType.None)
: true;
final int indexHoleBL = (withStore) ? 1 : 0;
final Point ptA = boardStyle.screenPosn(boardStyle.topology().vertices().get(circleTiling ? 0 : indexHoleBL).centroid());
final Point ptB = boardStyle.screenPosn(
boardStyle.topology().vertices().get(circleTiling ? 1 : (indexHoleBL + 1)).centroid());
final double unit = MathRoutines.distance(ptA, ptB);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
final Board board = context.board();
final Topology graph = board.topology();
final Graphics graphics = context.metadata().graphics();
final String label = "Board";
final Container equip = context.game().mapContainer().get(label);
final Color shadeBase = seedColour;
final Color shadeDark = MathRoutines.shade(shadeBase, 0.75);
final Color shadeLight = MathRoutines.shade(shadeBase, 1.5);
if (equip == null)
return;
// This game has a board
final State state = context.state();
final ContainerState cs = state.containerStates()[0];
for (int site = 0; site < graph.vertices().size(); site++)
{
final Point pt = boardStyle.screenPosn(graph.vertices().get(site).centroid());
final int count = stackingGame ? cs.sizeStack(site, SiteType.Vertex) : cs.count(site, SiteType.Vertex);
final int cx = pt.x;
final int cy = pt.y;
final int swRing = (int) (boardStyle.cellRadius() * placement.width / 10.0);
final BasicStroke strokeRink = new BasicStroke(swRing, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
g2d.setStroke(strokeRink);
// Code for drawing the tuz (ring around holes that are coloured based on player value).
if (context.game().metadata().graphics().showPlayerHoles())
{
for (int i = 1; i <= context.game().players().count(); i++)
{
if (state.getValue(i) == site)
{
final int r = cellRadiusPixels;
g2d.setColor(bridge.settingsColour().playerColour(context, i));
g2d.drawArc(cx-r, cy-r, 2*r, 2*r, 0, 360);
}
}
}
// Code for drawing the tuz (ring around holes that are coloured based on local state).
if (context.game().metadata().graphics().holesUseLocalState())
{
for (int i = 1; i <= context.game().players().count(); i++)
{
if (i == cs.stateVertex(site))
{
final int r = cellRadiusPixels;
g2d.setColor(bridge.settingsColour().playerColour(context, i));
g2d.drawArc(cx-r, cy-r, 2*r, 2*r, 0, 360);
}
}
}
// Code for drawing rings around each kalah based on which player they are for.
if (context.game().metadata().graphics().showPits())
{
if (context.game().equipment().maps().length != 0)
{
final Map map = context.game().equipment().maps()[0];
for (int p = 1; p <= context.game().players().count(); p++)
{
final int ownedSite = map.to(p);
if (ownedSite == site)
{
final int r = cellRadiusPixels;
g2d.setColor(bridge.settingsColour().playerColour(context, p));
g2d.drawArc(cx-r, cy-r, 2*r, 2*r, 0, 360);
}
}
}
}
if(stackingGame)
{
if (count > 0)
{
final int group = Math.min(count, offsets.length-1);
for(int level = 0; level < count; level++)
{
final int what = cs.what(site, level, SiteType.Vertex);
final int who = cs.who(site, level, SiteType.Vertex);
final Component component = (what > 0) ? context.components()[what] : null;
double scale = (component == null) ? 1.0 : graphics.pieceScale(context, who, component.name(), boardStyle.container().index(), cs.state(site, SiteType.Vertex), cs.value(site, SiteType.Vertex)).getX();
scale = (scale == 0.0) ? 1.0 : scale;
final int seedRadius = Math.max((int) (1*scale), (int) (0.19 * unit* scale)) ;
Color colorWho = graphics.playerColour(context, who);
colorWho = colorWho == null ? seedColour : colorWho;
final boolean defaultSeed = (component == null) ? true : component.name().equals("Seed");
if(defaultSeed)
{
if(level < 5)
{
// Draw pieces
final int groupIndex = Math.min(5, level);
final Point2D.Double off = offsets[group][groupIndex];
final int x = cx + (int) (off.x * seedRadius + 0.5) - seedRadius + 1;
final int y = cy - (int) (off.y * seedRadius + 0.5) - seedRadius + 1;
ImageProcessing.ballImage(g2d, x, y, (seedRadius), colorWho);
}
}
else
{
// Draw pieces
final int groupIndex = Math.min(4, level);
final Point2D.Double off = offsets[group][groupIndex];
final int x = cx + (int) (off.x * seedRadius + 0.5) - seedRadius + 1;
final int y = cy - (int) (off.y * seedRadius + 0.5) - seedRadius + 1;
ImageProcessing.ballImage(g2d, x, y, (seedRadius), colorWho);
}
}
if(count > 5)
{
// Draw piece count
final Font oldFont = g2d.getFont();
final Font font = new Font(oldFont.getFontName(), Font.BOLD, (int) (0.45 * boardStyle.cellRadius() * placement.width));
g2d.setFont(font);
final String str = Integer.toString(count);
final Rectangle2D bounds = font.getStringBounds(str, g2d.getFontRenderContext());
final int tx = cx - (int)(0.5 * bounds.getWidth() + 0.5);
final int ty = cy + (int)(0.4 * bounds.getHeight() + 0.5);
g2d.setColor(Color.black);
g2d.drawString(str, tx, ty-1);
g2d.setColor(shadeLight);
g2d.drawString(str, tx, ty+1);
g2d.setColor(shadeDark);
g2d.drawString(str, tx, ty);
g2d.setFont(oldFont);
}
}
}
else
{
if (count > 0)
{
final int what = cs.what(site, SiteType.Vertex);
final int who = cs.who(site, SiteType.Vertex);
final Component component = (what > 0) ? context.components()[what] : null;
double scale = (component == null) ? 1.0 : graphics.pieceScale(context, who, component.name(), boardStyle.container().index(), cs.state(site, SiteType.Vertex), cs.value(site, SiteType.Vertex)).getX();
scale = (scale == 0.0) ? 1.0 : scale;
final int seedRadius = Math.max((int) (1*scale), (int) (0.19 * unit* scale)) ;
Color colorWho = graphics.playerColour(context, who);
colorWho = colorWho == null ? seedColour : colorWho;
// Draw pieces
final int group = Math.min(count, offsets.length-1);
for (int s = 0; s < offsets[group].length; s++)
{
final Point2D.Double off = offsets[group][s];
final int x = cx + (int) (off.x * seedRadius + 0.5) - seedRadius + 1;
final int y = cy - (int) (off.y * seedRadius + 0.5) - seedRadius + 1;
ImageProcessing.ballImage(g2d, x, y, (seedRadius), colorWho);
}
if (count > 5)
{
// Draw piece count
final Font oldFont = g2d.getFont();
final Font font = new Font(oldFont.getFontName(), Font.BOLD, (int) (0.45 * boardStyle.cellRadius() * placement.width));
g2d.setFont(font);
final String str = Integer.toString(count);
final Rectangle2D bounds = font.getStringBounds(str, g2d.getFontRenderContext());
final int tx = cx - (int)(0.5 * bounds.getWidth() + 0.5);
final int ty = cy + (int)(0.4 * bounds.getHeight() + 0.5);
g2d.setColor(Color.black);
g2d.drawString(str, tx, ty-1);
g2d.setColor(shadeLight);
g2d.drawString(str, tx, ty+1);
g2d.setColor(shadeDark);
g2d.drawString(str, tx, ty);
g2d.setFont(oldFont);
}
}
}
}
}
//-------------------------------------------------------------------------
}
| 11,024 | 33.133127 | 207 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/components/board/PenAndPaperComponents.java
|
package view.container.aspects.components.board;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
import bridge.Bridge;
import game.types.board.SiteType;
import metadata.graphics.util.BoardGraphicsType;
import other.context.Context;
import other.state.container.ContainerState;
import other.topology.Edge;
import other.topology.TopologyElement;
import other.topology.Vertex;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.designs.board.puzzle.PuzzleDesign;
import view.container.styles.board.graph.PenAndPaperStyle;
/**
* Pen and Paper components properties.
*
* @author Matthew.Stephenson
*/
public class PenAndPaperComponents extends PuzzleComponents
{
private final PenAndPaperStyle graphStyle;
private final BoardDesign boardDesign;
//-------------------------------------------------------------------------
public PenAndPaperComponents
(
final Bridge bridge, final PenAndPaperStyle containerStyle, final PuzzleDesign boardDesign
)
{
super(bridge, containerStyle, boardDesign);
graphStyle = containerStyle;
this.boardDesign = boardDesign;
}
//-------------------------------------------------------------------------
@Override
public void drawComponents(final Graphics2D g2d, final Context context)
{
final List<Vertex> vertices = graphStyle.topology().vertices();
final BasicStroke strokeThick = boardDesign.strokeThick();
final ContainerState cs = context.state().containerStates()[0];
if (context.metadata().graphics().replaceComponentsWithFilledCells())
{
fillCellsBasedOnOwner(g2d, context);
}
else
{
super.drawComponents(g2d, context, (ArrayList<? extends TopologyElement>) graphStyle.topology().cells());
super.drawComponents(g2d, context, (ArrayList<? extends TopologyElement>) graphStyle.topology().vertices());
}
// Pass 1: Draw thick black edges
g2d.setColor(Color.BLACK);
final BasicStroke slightlyThickerStroke = new BasicStroke(strokeThick.getLineWidth() + 4.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
g2d.setStroke(slightlyThickerStroke);
for (final Vertex va : vertices)
{
final Point vaPosn = graphStyle.screenPosn(va.centroid());
for (final Vertex vb : va.orthogonal())
{
for (int e = 0; e < context.topology().edges().size(); e++)
{
final Edge edge = context.topology().edges().get(e);
if ((edge.vA() == va && edge.vB() == vb) || (edge.vA() == vb && edge.vB() == va))
{
if (cs.whatEdge(e) != 0)
{
final Point vbPosn = graphStyle.screenPosn(vb.centroid());
final java.awt.Shape line = new Line2D.Double(vaPosn.x, vaPosn.y, vbPosn.x, vbPosn.y);
g2d.draw(line);
}
}
}
}
}
// Pass 2: Redraw thinner edges in player colour
final BasicStroke roundedThinStroke = new BasicStroke(strokeThick.getLineWidth(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
g2d.setStroke(roundedThinStroke);
for (final Vertex va : vertices)
{
final Point vaPosn = graphStyle.screenPosn(va.centroid());
for (final Vertex vb : va.orthogonal())
{
for (int e = 0; e < context.topology().edges().size(); e++)
{
final Edge edge = context.topology().edges().get(e);
if ((edge.vA() == va && edge.vB() == vb) || (edge.vA() == vb && edge.vB() == va))
{
if (cs.whatEdge(e) != 0)
{
final Point vbPosn = graphStyle.screenPosn(vb.centroid());
final java.awt.Shape line = new Line2D.Double(vaPosn.x, vaPosn.y, vbPosn.x, vbPosn.y);
g2d.setColor(bridge.settingsColour().playerColour(context, cs.whoEdge(e)));
g2d.draw(line);
}
}
}
}
}
// If a puzzle, and edge is set to zero, draw a cross.
final int dim = puzzleStyle.topology().rows(context.board().defaultSite()).size();
final int bigFontSize = (int) (0.75 * puzzleStyle.placement().getHeight() / dim + 0.5);
final Font bigFont = new Font("Arial", Font.BOLD, bigFontSize);
g2d.setFont(bigFont);
for (final Edge e : graphStyle.topology().edges())
{
if (cs.isResolved(e.index(), SiteType.Edge) && cs.what(e.index(), SiteType.Edge) == 0)
{
final Point drawPosn = graphStyle.screenPosn(e.centroid());
final Rectangle bounds = g2d.getFontMetrics().getStringBounds("X", g2d).getBounds();
g2d.drawString("X", drawPosn.x - bounds.width/2, drawPosn.y + bounds.height/3);
}
}
// Draw vertices
final double rO = graphStyle.baseVertexRadius();
for (final Vertex vertex : vertices)
{
if (cs.what(vertex.index(), SiteType.Vertex) != 0)
{
g2d.setColor(bridge.settingsColour().playerColour(context, cs.who(vertex.index(), SiteType.Vertex)));
}
else
{
if (context.game().metadata().graphics().boardColour(BoardGraphicsType.InnerVertices) == null)
g2d.setColor(graphStyle.baseGraphColour());
else
g2d.setColor(context.game().metadata().graphics().boardColour(BoardGraphicsType.InnerVertices));
}
final Point circlePosn = graphStyle.screenPosn(vertex.centroid());
final java.awt.Shape ellipseO = new Ellipse2D.Double(circlePosn.x-rO, circlePosn.y-rO, 2*rO, 2*rO);
g2d.fill(ellipseO);
}
}
//-------------------------------------------------------------------------
}
| 5,426 | 32.91875 | 142 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/components/board/PuzzleComponents.java
|
package view.container.aspects.components.board;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.util.BitSet;
import bridge.Bridge;
import game.equipment.component.Piece;
import game.rules.start.StartRule;
import game.rules.start.deductionPuzzle.Set;
import game.types.play.RoleType;
import gnu.trove.list.array.TIntArrayList;
import metadata.graphics.Graphics;
import other.context.Context;
import other.state.State;
import other.state.container.ContainerState;
import other.topology.TopologyElement;
import util.ImageInfo;
import view.component.BaseComponentStyle;
import view.component.custom.PieceStyle;
import view.container.aspects.components.ContainerComponents;
import view.container.aspects.designs.board.puzzle.PuzzleDesign;
import view.container.styles.board.puzzle.PuzzleStyle;
/**
* Puzzle components properties.
*
* @author Matthew.Stephenson
*/
public class PuzzleComponents extends ContainerComponents
{
/** Initial cells where values are set. */
protected TIntArrayList initialValues = new TIntArrayList();
//-------------------------------------------------------------------------
protected final PuzzleStyle puzzleStyle;
private final PuzzleDesign puzzleDesign;
//-------------------------------------------------------------------------
public PuzzleComponents(final Bridge bridge, final PuzzleStyle containerStyle, final PuzzleDesign containerDesign)
{
super(bridge, containerStyle);
puzzleStyle = containerStyle;
puzzleDesign = containerDesign;
}
//-------------------------------------------------------------------------
@Override
public void drawComponents(final Graphics2D g2d, final Context context)
{
// As the game is a deduction puzzle, we need to draw the variables rather than the components.
if (initialValues.size() == 0 && context.game().rules().start() != null)
{
final StartRule[] startRules = context.game().rules().start().rules();
for (final StartRule startRule : startRules)
{
if (startRule.isSet())
{
final Set setRule = (Set) startRule;
for (final Integer site : setRule.vars())
{
initialValues.add(site.intValue());
}
}
}
}
// This game has a board
final State state = context.state();
final ContainerState cs = state.containerStates()[0];
for (int site = 0; site < puzzleStyle.topology().getGraphElements(context.board().defaultSite()).size(); site++)
{
final TopologyElement element = puzzleStyle.topology().getGraphElements(context.board().defaultSite()).get(site);
final Point2D posn = element.centroid();
final Point drawPosn = puzzleStyle.screenPosn(posn);
final BitSet values = cs.values(context.board().defaultSite(), site);
if (cs.isResolved(site, context.board().defaultSite()))
{
final int value = values.nextSetBit(0);
final int dim = puzzleStyle.topology().rows(context.board().defaultSite()).size();
final int bigFontSize = (int)(0.75 * puzzleStyle.placement().getHeight() / dim + 0.5);
final Font bigFont = new Font("Arial", Font.BOLD, bigFontSize);
g2d.setFont(bigFont);
if (initialValues.contains(site))
g2d.setColor(Color.BLACK);
else
g2d.setColor(new Color(139,0,0));
final int pieceSize = (int) (puzzleStyle.cellRadiusPixels()*2*pieceScale()*puzzleStyle.containerScale());
drawPuzzleValue(value, site, context, g2d, drawPosn, pieceSize);
}
}
}
//-------------------------------------------------------------------------
@Override
public void drawPuzzleValue(final int value, final int site, final Context context, final Graphics2D g2d, final Point drawPosn, final int imageSize)
{
final Graphics metadataGraphics = context.game().metadata().graphics();
final String name = metadataGraphics.pieceNameReplacement(context, 1, String.valueOf(value), 0, 0, 0);
if (name != null)
{
// Draw a specific image here instead of the value
final Piece component = new Piece(name, RoleType.P1, null, null, null, null, null, null);
component.create(context.game());
component.setIndex(value);
final BaseComponentStyle componentStyle = new PieceStyle(bridge, component);
componentStyle.renderImageSVG(context, 0, imageSize, 0, 0, false, 0, 0);
bridge.graphicsRenderer().drawSVG(context, g2d, componentStyle.getImageSVG(0), new ImageInfo(drawPosn, site, 0, context.board().defaultSite(), component, 0, 0, 0.0, 0, 1, imageSize, 1));
}
else
{
// Draw the single resolved value
final String str = "" + value;
final Rectangle bounds = g2d.getFontMetrics().getStringBounds(str, g2d).getBounds();
g2d.drawString(str, drawPosn.x - bounds.width/2, drawPosn.y + bounds.height/3);
}
}
public PuzzleDesign getPuzzleDesign()
{
return puzzleDesign;
}
//-------------------------------------------------------------------------
}
| 4,965 | 33.971831 | 189 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/components/board/TableComponents.java
|
package view.container.aspects.components.board;
import bridge.Bridge;
import view.container.BaseContainerStyle;
import view.container.aspects.components.ContainerComponents;
/**
* Table components properties.
*
* @author Eric.Piette
*/
public class TableComponents extends ContainerComponents
{
public TableComponents(final Bridge bridge, final BaseContainerStyle containerStyle)
{
super(bridge, containerStyle);
setPieceScale(1.1);
}
}
| 452 | 21.65 | 85 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/BoardDesign.java
|
package view.container.aspects.designs;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Stroke;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.Game;
import game.equipment.other.Regions;
import game.types.board.SiteType;
import game.util.graph.Properties;
import graphics.ImageUtil;
import graphics.svg.SVGtoImage;
import main.math.MathRoutines;
import main.math.Vector;
import metadata.graphics.util.BoardGraphicsType;
import metadata.graphics.util.CurveType;
import metadata.graphics.util.MetadataImageInfo;
import other.context.Context;
import other.location.FullLocation;
import other.location.Location;
import other.topology.Cell;
import other.topology.Edge;
import other.topology.Topology;
import other.topology.TopologyElement;
import other.topology.Vertex;
import util.ContainerUtil;
import util.GraphUtil;
import util.ShadedCells;
import util.StringUtil;
import util.StrokeUtil;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class BoardDesign extends ContainerDesign
{
protected final BoardStyle boardStyle;
protected final BoardPlacement boardPlacement;
//-------------------------------------------------------------------------
/** various GUI values for colours and strokes */
protected Color colorEdgesInner;
protected Color colorEdgesOuter;
protected Color colorVerticesInner;
protected Color colorVerticesOuter;
protected Color colorFillPhase0;
protected Color colorFillPhase1;
protected Color colorFillPhase2;
protected Color colorFillPhase3;
protected Color colorFillPhase4;
protected Color colorFillPhase5;
protected BasicStroke strokeThin;
protected BasicStroke strokeThick;
protected Color colorSymbol;
/** If the board has a checkered pattern (set by metadata or specific board styles). */
protected boolean checkeredBoard;
/** If all lines should be drawn straight rather than curved. */
protected boolean straightLines;
//-------------------------------------------------------------------------
protected List<MetadataImageInfo> symbols = new ArrayList<>();
protected List<List<MetadataImageInfo>> symbolRegions = new ArrayList<>();
//-------------------------------------------------------------------------
public BoardDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
this.boardStyle = boardStyle;
this.boardPlacement = boardPlacement;
}
//-------------------------------------------------------------------------
/**
* fill, draw internal grid lines, draw symbols, draw outer border on top.
* @return SVG as string.
*/
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
// Set all values
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final double boardLineThickness = boardStyle.cellRadiusPixels()/15.0;
checkeredBoard = context.game().metadata().graphics().checkeredBoard();
straightLines = context.game().metadata().graphics().straightRingLines();
final float swThin = (float) Math.max(1, boardLineThickness);
final float swThick = swThin;
Color colorEdge = new Color(120, 190, 240);
if (!bridge.settingsVC().flatBoard() && !context.game().metadata().graphics().noSunken())
colorEdge = null;
setStrokesAndColours
(
bridge,
context,
colorEdge,
colorEdge,
new Color(210, 230, 255),
new Color(210, 0, 0),
new Color(0, 230, 0),
new Color(0, 0, 255),
null,
null,
new Color(0, 0, 0),
swThin,
swThick
);
// Background
drawGround(g2d, context, true);
// Cells
fillCells(bridge, g2d, context);
// Edges
drawInnerCellEdges(g2d, context);
drawOuterCellEdges(bridge, g2d, context);
// Symbols
drawSymbols(g2d, context);
// Foreground
drawGround(g2d, context, false);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
/**
* @param context
* @param colorLines
* @param colorFill1
* @param colorFill2
* @param colorFill3
* @param colorFill4
* @param colorDecoration
* @param colorBorder
*/
protected void setStrokesAndColours
(
final Bridge bridge,
final Context context,
final Color colorIn,
final Color colorOut,
final Color colorFill1,
final Color colorFill2,
final Color colorFill3,
final Color colorFill4,
final Color colorFill5,
final Color colorFill6,
final Color colorDecoration,
final float swThin,
final float swThick
)
{
// Define the default board colours and line thicknesses
bridge.settingsColour().getBoardColours()[BoardGraphicsType.InnerEdges.value()] = colorIn;
bridge.settingsColour().getBoardColours()[BoardGraphicsType.OuterEdges.value()] = colorOut;
bridge.settingsColour().getBoardColours()[BoardGraphicsType.InnerVertices.value()] = colorIn;
bridge.settingsColour().getBoardColours()[BoardGraphicsType.OuterVertices.value()] = colorIn;
bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase0.value()] = colorFill1;
bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase1.value()] = colorFill2;
bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase2.value()] = colorFill3;
bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase3.value()] = colorFill4;
bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase4.value()] = colorFill5;
bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase5.value()] = colorFill6;
bridge.settingsColour().getBoardColours()[BoardGraphicsType.Symbols.value()] = colorDecoration;
// Check the .lud metadata for overriding fill colours
for (int bid = 0; bid < bridge.settingsColour().getBoardColours().length; bid++)
{
final Color colour = context.game().metadata().graphics().boardColour(BoardGraphicsType.getTypeFromValue(bid));
if (colour != null)
{
bridge.settingsColour().getBoardColours()[bid] = colour;
}
}
final float lineThickness = swThin * context.game().metadata().graphics().boardThickness(BoardGraphicsType.InnerEdges);
final float borderThickness = swThick * context.game().metadata().graphics().boardThickness(BoardGraphicsType.OuterEdges);
colorEdgesInner = bridge.settingsColour().getBoardColours()[BoardGraphicsType.InnerEdges.value()];
colorEdgesOuter = bridge.settingsColour().getBoardColours()[BoardGraphicsType.OuterEdges.value()];
colorVerticesInner = bridge.settingsColour().getBoardColours()[BoardGraphicsType.InnerVertices.value()];
colorVerticesOuter = bridge.settingsColour().getBoardColours()[BoardGraphicsType.OuterVertices.value()];
colorFillPhase0 = bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase0.value()];
colorFillPhase1 = bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase1.value()];
colorFillPhase2 = bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase2.value()];
colorFillPhase3 = bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase3.value()];
colorFillPhase4 = bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase4.value()];
colorFillPhase5 = bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase5.value()];
setColorSymbol(bridge.settingsColour().getBoardColours()[BoardGraphicsType.Symbols.value()]);
if (bridge.settingsColour().getBoardColours()[BoardGraphicsType.InnerEdges.value()] != null)
colorEdgesInner = bridge.settingsColour().getBoardColours()[BoardGraphicsType.InnerEdges.value()];
if (bridge.settingsColour().getBoardColours()[BoardGraphicsType.OuterEdges.value()] != null)
colorEdgesOuter = bridge.settingsColour().getBoardColours()[BoardGraphicsType.OuterEdges.value()];
if (bridge.settingsColour().getBoardColours()[BoardGraphicsType.InnerVertices.value()] != null)
colorVerticesInner = bridge.settingsColour().getBoardColours()[BoardGraphicsType.InnerVertices.value()];
if (bridge.settingsColour().getBoardColours()[BoardGraphicsType.OuterVertices.value()] != null)
colorVerticesOuter = bridge.settingsColour().getBoardColours()[BoardGraphicsType.OuterVertices.value()];
if (bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase0.value()] != null)
colorFillPhase0 = bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase0.value()];
if (bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase1.value()] != null)
colorFillPhase1 = bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase1.value()];
if (bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase2.value()] != null)
colorFillPhase2 = bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase2.value()];
if (bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase3.value()] != null)
colorFillPhase3 = bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase3.value()];
if (bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase4.value()] != null)
colorFillPhase4 = bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase4.value()];
if (bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase5.value()] != null)
colorFillPhase5 = bridge.settingsColour().getBoardColours()[BoardGraphicsType.Phase5.value()];
if (bridge.settingsColour().getBoardColours()[BoardGraphicsType.Symbols.value()] != null)
setColorSymbol(bridge.settingsColour().getBoardColours()[BoardGraphicsType.Symbols.value()]);
strokeThin = new BasicStroke(lineThickness, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
strokeThick = new BasicStroke(borderThickness, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
setSymbols(bridge, context);
}
//-------------------------------------------------------------------------
/**
* Draws either the background or foreground images for the board if specified in metadata.
* @param g2d
* @param context
* @param background
*/
protected void drawGround(final SVGGraphics2D g2d, final Context context, final boolean background)
{
List<MetadataImageInfo> allGroundImages = new ArrayList<>();
if (background)
allGroundImages = context.metadata().graphics().boardBackground(context);
else
allGroundImages = context.metadata().graphics().boardForeground(context);
for (final MetadataImageInfo groundImageInfo : allGroundImages)
{
final Point drawPosn = boardStyle.screenPosn(new Point2D.Double(0.5, 0.5));
if (groundImageInfo.path() == null && groundImageInfo.text() == null)
{
drawBoardOutline(g2d, groundImageInfo.scale(), groundImageInfo.offestX(), groundImageInfo.offestY(),
groundImageInfo.mainColour(), groundImageInfo.secondaryColour(), groundImageInfo.rotation());
}
else if (groundImageInfo.path() != null)
{
final String fullPath = ImageUtil.getImageFullPath(groundImageInfo.path());
Color edgeColour = colorSymbol();
Color fillColour = null;
if (groundImageInfo.mainColour() != null)
fillColour = groundImageInfo.mainColour();
if (groundImageInfo.secondaryColour() != null)
edgeColour = groundImageInfo.secondaryColour();
final int rotation = groundImageInfo.rotation();
final int offsetX = (int) (groundImageInfo.offestX() * boardStyle.maxDim());
final int offsetY = (int) (groundImageInfo.offestY() * boardStyle.maxDim());
final Rectangle2D rect =
new Rectangle2D.Double
(
drawPosn.x + offsetX - (groundImageInfo.scaleX() * boardStyle.maxDim())/2,
drawPosn.y + offsetY - (groundImageInfo.scaleY() * boardStyle.maxDim())/2,
(int) (groundImageInfo.scaleX() * boardStyle.maxDim()),
(int) (groundImageInfo.scaleY() * boardStyle.maxDim())
);
SVGtoImage.loadFromFilePath(g2d, fullPath, rect, edgeColour, fillColour, rotation);
}
else if (groundImageInfo.text() != null)
{
g2d.setColor(groundImageInfo.mainColour());
final int fontSize = (int) ((0.85 * boardStyle.cellRadius() * boardStyle.placement().width + 0.5) * groundImageInfo.scale());
final Font font = new Font("Arial", Font.PLAIN, fontSize);
g2d.setFont(font);
g2d.drawString(groundImageInfo.text(), drawPosn.x, drawPosn.y);
}
}
}
//-------------------------------------------------------------------------
/**
* @param g2d
* @param fillColor
* @param stroke
*/
protected void fillCells(final Bridge bridge, final Graphics2D g2d, final Context context)
{
g2d.setStroke(strokeThin);
final List<Cell> cells = topology().cells();
for (final Cell cell : cells)
{
final Color[][] colours =
ShadedCells.shadedPhaseColours
(
colorFillPhase0, colorFillPhase1, colorFillPhase2,
colorFillPhase3, colorFillPhase4, colorFillPhase5
);
final GeneralPath path = new GeneralPath();
for (int v = 0; v < cell.vertices().size(); v++)
{
final Vertex vertexA = cell.vertices().get(v);
final Vertex vertexB = cell.vertices().get((v + 1) % cell.vertices().size());
if (v == 0)
{
final Point ptA = boardStyle.screenPosn(vertexA.centroid());
path.moveTo(ptA.x, ptA.y);
}
// Find which edge this is
Edge edge = null;
for (final Edge edgeA : vertexA.edges())
if (edgeA.vA().index() == vertexB.index() || edgeA.vB().index() == vertexB.index())
{
edge = edgeA;
break;
}
for (final MetadataImageInfo s : symbols)
{
if (s.line() != null && s.line().length >=2)
{
if
(
edge.vA().index() == s.line()[0].intValue() && edge.vB().index() == s.line()[1].intValue()
||
edge.vB().index() == s.line()[0].intValue() && edge.vA().index() == s.line()[1].intValue()
)
{
if (s.curve() != null)
{
edge.setTangentA(new Vector(s.curve()[0].doubleValue(),s.curve()[1].doubleValue()));
edge.setTangentB(new Vector(s.curve()[2].doubleValue(),s.curve()[3].doubleValue()));
}
}
}
}
addEdgeToPath(context.game(), path, edge, edge.vA().index() == vertexA.index(), 0);
}
g2d.setColor(colorFillPhase0);
if (checkeredBoard)
ShadedCells.setCellColourByPhase
(
g2d, cell.index(), topology(),
colorFillPhase0, colorFillPhase1, colorFillPhase2,
colorFillPhase3, colorFillPhase4, colorFillPhase5
);
// if cell is marked as a symbol, but no symbol is specified, then just fill the cell with the decoration colour
for (final List<MetadataImageInfo> regionInfo : symbolRegions)
{
for (final MetadataImageInfo d : regionInfo)
{
if (d.siteType() == SiteType.Cell && d.site() == cell.index() && d.path() == null && d.text() == null)
{
g2d.setColor(d.mainColour());
final int phase = !checkeredBoard ? 0 : topology().phaseByElementIndex(SiteType.Cell, cell.index());
colours[phase][1] = d.mainColour();
break;
}
}
}
if (bridge.settingsVC().flatBoard() || context.game().metadata().graphics().noSunken())
g2d.fill(path);
else
ShadedCells.drawShadedCell(g2d, cell, path, colours, checkeredBoard, topology());
}
}
//-------------------------------------------------------------------------
protected void drawEdges
(
final Graphics2D g2d,
final Context context,
final Color lineColour,
final Stroke lineStroke,
final List<Edge> edges,
final double offsetY
)
{
drawEdgesWithMetadata(g2d, context, lineColour, lineStroke, edges, offsetY);
for (final List<MetadataImageInfo> regionInfo : symbolRegions)
{
final List<Edge> regionEdges = new ArrayList<>();
Color regionColour = null;
for (final MetadataImageInfo d : regionInfo)
{
if (d.siteType() == SiteType.Edge && d.path() == null)
{
regionEdges.add(topology().edges().get(d.site()));
regionColour = d.mainColour();
}
}
final Color originalColour = g2d.getColor();
drawEdgesWithMetadata(g2d, context, regionColour, lineStroke, regionEdges, offsetY);
g2d.setColor(originalColour);
}
}
private void drawEdgesWithMetadata
(
final Graphics2D g2d,
final Context context,
final Color lineColour,
final Stroke lineStroke,
final List<Edge> edges,
final double offsetY
)
{
final double errorDistanceBuffer = 0.0001;
g2d.setStroke(lineStroke);
g2d.setColor(lineColour);
final GeneralPath path = new GeneralPath();
final List<Edge> edgesToDraw = new ArrayList<>();
for (final Edge edge : edges)
if
(
getMetadataImageInfoForEdge(edge) == null // Ignore edges which have already been drawn as part of the metadata (symbols).
&&
(
(context.game().metadata().graphics().showStraightEdges() && !edge.isCurved())
||
(context.game().metadata().graphics().showCurvedEdges() && edge.isCurved())
)
)
edgesToDraw.add(edge);
Vertex vertexA;
Vertex vertexB;
while (edgesToDraw.size() > 0)
{
Edge edge = edgesToDraw.get(0);
boolean nextEdgeFound = true;
vertexA = edge.vA();
final Point2D centroidA = edge.vA().centroid();
final Point drawPosnA = boardStyle.screenPosn(centroidA);
path.moveTo(drawPosnA.x, drawPosnA.y + offsetY);
vertexB = edge.vB();
Point2D centroidB = edge.vB().centroid();
while (nextEdgeFound == true)
{
nextEdgeFound = false;
addEdgeToPath(context.game(), path, edge, edge.vA().index() == vertexA.index(), offsetY);
edgesToDraw.remove(edge);
for (final Edge nextEdge : edgesToDraw)
{
// Forwards direction (vB of nextEdge is the next vertex).
if
(
Math.abs(centroidB.getX() - nextEdge.vA().centroid().getX()) < errorDistanceBuffer
&&
Math.abs(centroidB.getY() - nextEdge.vA().centroid().getY()) < errorDistanceBuffer
)
{
nextEdgeFound = true;
edge = nextEdge;
vertexA = edge.vA();
vertexB = edge.vB();
centroidB = vertexB.centroid();
break;
}
// Backwards direction (vA of nextEdge is the next vertex).
else if
(
Math.abs(centroidB.getX() - nextEdge.vB().centroid().getX()) < errorDistanceBuffer
&&
Math.abs(centroidB.getY() - nextEdge.vB().centroid().getY()) < errorDistanceBuffer
)
{
nextEdgeFound = true;
edge = nextEdge;
vertexA = edge.vB();
vertexB = edge.vA();
centroidB = vertexB.centroid();
break;
}
}
}
// If we have come full loop back to where we started, then close the path.
if (Math.abs(centroidA.getX() - centroidB.getX()) < errorDistanceBuffer
&& Math.abs(centroidA.getY() - centroidB.getY()) < errorDistanceBuffer)
path.closePath();
}
g2d.draw(path);
}
//-------------------------------------------------------------------------
/**
* Draw Vertices based on the board's graph.
*/
protected void drawVertices(final Bridge bridge, final Graphics2D g2d, final Context context, final double radius)
{
drawVertices(bridge, g2d, context, null, radius);
}
protected void drawVertices(final Bridge bridge, final Graphics2D g2d, final Context context, final Color vertexColour, final double radius)
{
drawVertices(bridge, g2d, context, vertexColour, radius, 0);
}
protected void drawVertices(final Bridge bridge, final Graphics2D g2d, final Context context, final Color vertexColour, final double radius, final double offsetY)
{
if (context.game().metadata().graphics().showRegionOwner() && !context.game().isDeductionPuzzle())
{
// Show region vertices in owner's colour
final Regions[] regionsList = context.game().equipment().regions();
final Color borderColor = new Color(127, 127, 127);
final double rI = radius * 2;
final double rO = rI + 2;
for (final Regions currentRegions : regionsList)
{
final int owner = currentRegions.owner();
final int[] sites = currentRegions.eval(context);
for (final int sid : sites)
{
// Show this site in the owner's colour
final Vertex vertex = topology().vertices().get(sid);
final Point pt = boardStyle.screenPosn(vertex.centroid());
pt.setLocation(pt.x, pt.y + offsetY);
g2d.setColor(borderColor);
final java.awt.Shape ellipseO = new Ellipse2D.Double(pt.x-rO, pt.y-rO, 2*rO, 2*rO);
g2d.fill(ellipseO);
final Color playerColour = bridge.settingsColour().playerColour(context, owner);
g2d.setColor(playerColour);
final java.awt.Shape ellipseI = new Ellipse2D.Double(pt.x-rI, pt.y-rI, 2*rI, 2*rI);
g2d.fill(ellipseI);
}
}
}
for (final Vertex vertex : topology().vertices())
{
g2d.setStroke(strokeThin);
if (vertex.properties().get(Properties.OUTER))
g2d.setColor(colorVerticesOuter);
else
g2d.setColor(colorVerticesInner);
if (vertexColour != null && g2d.getColor().getAlpha() != 0)
g2d.setColor(vertexColour);
// if vertex is marked as a symbol, but no symbol is specified, then just colour the vertex with the decoration colour
for (final List<MetadataImageInfo> regionInfo : symbolRegions)
{
for (final MetadataImageInfo d : regionInfo)
{
if (d.siteType() == SiteType.Vertex && d.site() == vertex.index() && d.path() == null && d.text() == null)
{
g2d.setColor(d.mainColour());
break;
}
}
}
final Point pt = boardStyle.screenPosn(vertex.centroid());
pt.setLocation(pt.x, pt.y + offsetY);
// Draw the vertex
final java.awt.Shape ellipseO = new Ellipse2D.Double(pt.x-radius, pt.y-radius, 2*radius, 2*radius);
g2d.fill(ellipseO);
}
}
//-------------------------------------------------------------------------
protected void drawBoardOutline(final SVGGraphics2D g2d)
{
drawBoardOutline(g2d, 1, 0, 0, null, null, 0);
}
/**
* Draws the rectangular outline of the board
* @param rotation
* @param secondaryColour
* @param mainColour
* @param offestY
* @param offestX
*/
protected void drawBoardOutline
(
final SVGGraphics2D g2d, final double scale, final float offestX,
final float offestY, final Color mainColour, final Color secondaryColour,
final int rotation
)
{
final List<Vertex> vertices = topology().vertices();
g2d.setStroke(strokeThin);
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
final GeneralPath path = new GeneralPath();
for (final Vertex vertex : vertices)
{
final Point posn = boardStyle.screenPosn(vertex.centroid());
final int x = posn.x;
final int y = posn.y;
if (minX > x)
minX = x;
if (minY > y)
minY = y;
if (maxX < x)
maxX = x;
if (maxY < y)
maxY = y;
g2d.setColor(mainColour == null ? colorFillPhase0 : mainColour);
}
minX += offestX;
maxX += offestX;
minY += offestY;
maxY += offestY;
// Margin of empty area around board
final int margin = (int)(boardStyle.cellRadiusPixels() * scale + 0.5);
path.moveTo(minX - margin, minY - margin);
path.lineTo(minX - margin, maxY + margin);
path.lineTo(maxX + margin, maxY + margin);
path.lineTo(maxX + margin, minY - margin);
path.lineTo(minX - margin, minY - margin);
g2d.rotate(rotation);
g2d.fill(path);
if (secondaryColour != null)
{
g2d.setColor(secondaryColour);
g2d.draw(path);
}
}
//-------------------------------------------------------------------------
/**
* Draw symbols on the board.
*/
protected void drawSymbols(final Graphics2D g2d, final Context context)
{
for (final MetadataImageInfo s : symbols)
{
// Draw lines
if (s.line() != null && s.line().length >= 2)
{
Color colour = s.mainColour();
final float scale = s.scale();
if (colour == null)
colour = colorEdgesOuter;
g2d.setColor(colour);
final BasicStroke strokeLineThin = new BasicStroke(strokeThin.getLineWidth() * scale, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
final BasicStroke strokeLineThick = new BasicStroke(strokeThick.getLineWidth() * scale, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
final Stroke strokeLine = StrokeUtil.getStrokeFromStyle(s.lineStyle(), strokeLineThin, strokeLineThick);
g2d.setStroke(strokeLine);
final TopologyElement v1 = boardStyle.container().topology().getGraphElements(s.siteType()).get(s.line()[0].intValue());
final TopologyElement v2 = boardStyle.container().topology().getGraphElements(s.siteType()).get(s.line()[1].intValue());
if (s.curve() == null)
{
g2d.drawLine
(
boardStyle.screenPosn(v1.centroid()).x,
boardStyle.screenPosn(v1.centroid()).y,
boardStyle.screenPosn(v2.centroid()).x,
boardStyle.screenPosn(v2.centroid()).y
);
}
else
{
final Vector tangentA = new Vector(s.curve()[0].floatValue(), s.curve()[1].floatValue());
final Vector tangentB = new Vector(s.curve()[2].floatValue(), s.curve()[3].floatValue());
final GeneralPath path = new GeneralPath();
path.moveTo(boardStyle.screenPosn(v1.centroid()).x, boardStyle.screenPosn(v1.centroid()).y);
curvePath(context.game(), path, v1.centroid(), v2.centroid(), tangentA, tangentB, 0, s.curveType());
g2d.draw(path);
}
}
// Draw regular symbols (images)
if ((s.path() == null && s.text() == null) || s.site() == -1)
continue;
TopologyElement e = null;
if (s.siteType() == SiteType.Cell)
{
e = boardStyle.topology().cells().get(s.site());
}
else if (s.siteType() == SiteType.Edge)
{
e = boardStyle.topology().edges().get(s.site());
}
else if (s.siteType() == SiteType.Vertex)
{
e = boardStyle.topology().vertices().get(s.site());
}
final Point drawPosn = boardStyle.screenPosn(e.centroid());
if (s.path() != null)
{
final String fullPath = ImageUtil.getImageFullPath(s.path());
Color edgeColour = colorSymbol();
Color fillColour = null;
if (s.mainColour() != null)
fillColour = s.mainColour();
if (s.secondaryColour() != null)
edgeColour = s.secondaryColour();
final int rotation = s.rotation();
final int offsetX = (int) (s.offestX() * boardStyle.cellRadiusPixels() * 2);
final int offsetY = (int) (s.offestY() * boardStyle.cellRadiusPixels() * 2);
final Rectangle2D rect = new Rectangle2D.Double
(
drawPosn.x + offsetX - s.scaleX() * boardStyle.cellRadiusPixels(),
drawPosn.y + offsetY - s.scaleY() * boardStyle.cellRadiusPixels(),
(int) (s.scaleX() * boardStyle.cellRadiusPixels() * 2),
(int) (s.scaleY() * boardStyle.cellRadiusPixels() * 2)
);
SVGtoImage.loadFromFilePath(g2d, fullPath, rect, edgeColour, fillColour, rotation);
}
if (s.text() != null)
{
g2d.setColor(s.mainColour());
final int fontSize = (int) ((0.85 * boardStyle.cellRadius() * boardStyle.placement().width + 0.5) * s.scale());
final Font font = new Font("Arial", Font.PLAIN, fontSize);
g2d.setFont(font);
StringUtil.drawStringAtPoint(g2d, s.text(), e, drawPosn, true);
}
}
// Draw indices on sites if specified.
for (final TopologyElement e : boardStyle.topology().getAllGraphElements())
{
final Integer additionalValue = context.game().metadata().graphics().showSiteIndex(context.game(), e);
if (additionalValue != null)
{
final Point drawPosn = boardStyle.screenPosn(e.centroid());
g2d.setColor(Color.WHITE);
final int fontSize = (int) (0.85 * boardStyle.cellRadius() * boardStyle.placement().width + 0.5);
final Font font = new Font("Arial", Font.PLAIN, fontSize);
g2d.setFont(font);
StringUtil.drawStringAtPoint(g2d, String.valueOf(e.index() + additionalValue.intValue()), e, drawPosn, true);
}
}
}
//-------------------------------------------------------------------------
private MetadataImageInfo getMetadataImageInfoForEdge(final Edge edge)
{
for (final MetadataImageInfo s : symbols)
if (s.line() != null && s.line().length >=2 && s.siteType() == SiteType.Vertex)
if
(
edge.vA().index() == s.line()[0].intValue() && edge.vB().index() == s.line()[1].intValue()
||
edge.vB().index() == s.line()[0].intValue() && edge.vA().index() == s.line()[1].intValue()
)
return s;
return null;
}
//-------------------------------------------------------------------------
/**
* Sets the locations for drawing symbols and colouring regions.
*/
private void setSymbols(final Bridge bridge, final Context context)
{
symbols.clear();
symbolRegions.clear();
// all cells that the player wants to colour
for (final List<MetadataImageInfo> regionInfo : context.game().metadata().graphics().regionsToFill(context))
{
if (regionInfo.size() == 0)
continue;
final MetadataImageInfo regionGraphics = regionInfo.get(0);
// Site type of the region is the same as what should be drawn on.
if (regionGraphics.regionSiteType() == regionGraphics.siteType())
{
symbolRegions.add(regionInfo);
}
// Region is defined using cells, but we want to draw the (perimeter) edges.
else if(regionGraphics.regionSiteType() == SiteType.Cell && regionGraphics.siteType() == SiteType.Edge)
{
final ArrayList<Location> region = new ArrayList<>();
for (final MetadataImageInfo m : regionInfo)
{
region.add(new FullLocation(m.site(), 0, m.siteType()));
}
final List<Edge> edgeLocations = ContainerUtil.getOuterRegionEdges(region, topology());
for (int e = 0; e < edgeLocations.size(); e++)
{
Color colour = regionGraphics.mainColour();
if (colour == null)
{
final Regions r = ContainerUtil.getRegionOfEdge(context, edgeLocations.get(e));
if (r != null)
// If the color wasn't specified, check if any player owns this region.
colour = bridge.settingsColour().playerColour(context, r.role().owner());
else
// If no player owns this region, set colour to Symbol colour.
colour = colorSymbol();
}
final Integer[] line = {Integer.valueOf(edgeLocations.get(e).vA().index()), Integer.valueOf(edgeLocations.get(e).vB().index())};
symbols.add(new MetadataImageInfo(line, SiteType.Vertex, colour, regionGraphics.scale()));
}
}
}
symbols.addAll(context.game().metadata().graphics().drawLines(context));
symbols.addAll(context.game().metadata().graphics().drawSymbol(context));
}
//-------------------------------------------------------------------------
private void addEdgeToPath(final Game game, final GeneralPath path, final Edge edge, final boolean forwards, final double offsetY)
{
final Vertex vertexA = forwards ? edge.vA() : edge.vB();
final Vertex vertexB = forwards ? edge.vB() : edge.vA();
final Vector tangentA = forwards ? edge.tangentA() : edge.tangentB();
final Vector tangentB = forwards ? edge.tangentB() : edge.tangentA();
if (tangentA != null && tangentB != null && !straightLines)
{
CurveType curveType = CurveType.Spline;
if (getMetadataImageInfoForEdge(edge) != null)
curveType = getMetadataImageInfoForEdge(edge).curveType();
// Draw curve for this edge
curvePath(game, path, vertexA.centroid(), vertexB.centroid(), tangentA, tangentB, offsetY, curveType);
}
else
{
// Draw straight line
final Point ptB = boardStyle.screenPosn(vertexB.centroid());
ptB.setLocation(ptB.x, ptB.y + offsetY);
path.lineTo(ptB.x, ptB.y);
}
}
//-------------------------------------------------------------------------
/**
* Draws a curved path based on a spline curve
* @param path
* @param vACentroid
* @param vBCentroid
* @param tangentA
* @param tangentB
* @param offsetY
*/
private void curvePath(final Game game, final GeneralPath path, final Point2D vACentroid, final Point2D vBCentroid, final Vector tangentA, final Vector tangentB, final double offsetY, final CurveType curveType)
{
final double dist = MathRoutines.distance(vACentroid, vBCentroid);
final double off = game.metadata().graphics().boardCurvature();
double aax = vACentroid.getX() + off * dist * tangentA.x();
double aay = vACentroid.getY() + off * dist * tangentA.y();
double bbx = vBCentroid.getX() + off * dist * tangentB.x();
double bby = vBCentroid.getY() + off * dist * tangentB.y();
if (curveType == CurveType.Bezier)
{
aax = tangentA.x();
aay = tangentA.y();
bbx = tangentB.x();
bby = tangentB.y();
}
final Point ptAA = boardStyle.screenPosn(new Point2D.Double(aax, aay));
final Point ptBB = boardStyle.screenPosn(new Point2D.Double(bbx, bby));
final Point ptB = boardStyle.screenPosn(vBCentroid);
ptB.setLocation(ptB.x, ptB.y + offsetY);
path.curveTo(ptAA.x, ptAA.y, ptBB.x, ptBB.y, ptB.x, ptB.y);
}
//-------------------------------------------------------------------------
protected void drawInnerCellEdges(final Graphics2D g2d, final Context context)
{
drawInnerCellEdges(g2d, context, colorEdgesInner, strokeThin);
}
protected void drawInnerCellEdges(final Graphics2D g2d, final Context context, final Color lineColour, final Stroke lineStroke)
{
drawInnerCellEdges(g2d, context, lineColour, lineStroke, 0);
}
protected void drawInnerCellEdges(final Graphics2D g2d, final Context context, final Color lineColour, final Stroke lineStroke, final double offsetY)
{
if (lineColour != null && lineColour.getAlpha() > 0)
drawEdges(g2d, context, lineColour, lineStroke, GraphUtil.innerEdgeRelations(topology()), offsetY);
}
//-------------------------------------------------------------------------
protected void drawOuterCellEdges(final Bridge bridge, final Graphics2D g2d, final Context context)
{
drawOuterCellEdges(g2d, context, colorEdgesOuter, strokeThick());
}
protected void drawOuterCellEdges(final Graphics2D g2d, final Context context, final Color lineColour, final Stroke lineStroke)
{
drawOuterCellEdges(g2d, context, lineColour, lineStroke, 0);
}
protected void drawOuterCellEdges(final Graphics2D g2d, final Context context, final Color lineColour, final Stroke lineStroke, final double offsetY)
{
if (lineColour != null && lineColour.getAlpha() > 0)
drawEdges(g2d, context, lineColour, lineStroke, GraphUtil.outerEdgeRelations(topology()), offsetY);
}
//-------------------------------------------------------------------------
protected void drawDiagonalEdges(final Graphics2D g2d, final Context context)
{
drawDiagonalEdges(g2d, context, colorEdgesInner, strokeThin);
}
protected void drawDiagonalEdges(final Graphics2D g2d, final Context context, final Color lineColour, final Stroke lineStroke)
{
drawDiagonalEdges(g2d, context, lineColour, lineStroke, 0);
}
protected void drawDiagonalEdges(final Graphics2D g2d, final Context context, final Color lineColour, final Stroke lineStroke, final double offsetY)
{
drawEdges(g2d, context, lineColour, lineStroke, GraphUtil.diagonalEdgeRelations(topology()), offsetY);
}
//-------------------------------------------------------------------------
protected void drawOrthogonalConnections(final Graphics2D g2d, final Context context)
{
drawOrthogonalConnections(g2d, context, colorEdgesInner, strokeThin);
}
protected void drawOrthogonalConnections(final Graphics2D g2d, final Context context, final Color lineColour, final Stroke lineStroke)
{
drawOrthogonalConnections(g2d, context, lineColour, lineStroke, 0);
}
protected void drawOrthogonalConnections(final Graphics2D g2d, final Context context, final Color lineColour, final Stroke lineStroke, final double offsetY)
{
drawEdges(g2d, context, lineColour, lineStroke, GraphUtil.orthogonalCellConnections(topology()), offsetY);
}
//-------------------------------------------------------------------------
/**
* Draw Diagonal connections based on the board's graph, using default line colour and stroke.
*/
protected void drawDiagonalConnections(final Graphics2D g2d, final Context context)
{
drawDiagonalConnections(g2d, context, colorEdgesInner, strokeThin);
}
protected void drawDiagonalConnections(final Graphics2D g2d, final Context context, final Color lineColour, final Stroke lineStroke)
{
drawDiagonalConnections(g2d, context, lineColour, lineStroke, 0);
}
/**
* Draw Diagonal connections based on the board's graph, using specified line colour and stroke.
*/
protected void drawDiagonalConnections(final Graphics2D g2d, final Context context, final Color lineColour, final Stroke lineStroke, final double offsetY)
{
drawEdges(g2d, context, lineColour, lineStroke, GraphUtil.diagonalCellConnections(topology()), offsetY);
}
//-------------------------------------------------------------------------
/**
* Draw Off Diagonal connections based on the board's graph, using default line colour and stroke.
*/
protected void drawOffDiagonalConnections(final Graphics2D g2d, final Context context)
{
drawOffDiagonalConnections(g2d, context, colorEdgesInner, strokeThin);
}
protected void drawOffDiagonalConnections(final Graphics2D g2d, final Context context, final Color lineColour, final Stroke lineStroke)
{
drawOffDiagonalConnections(g2d, context, lineColour, lineStroke, 0);
}
/**
* Draw Off Diagonal connections based on the board's graph, using specified line colour and stroke.
*/
protected void drawOffDiagonalConnections(final Graphics2D g2d, final Context context, final Color lineColour, final Stroke lineStroke, final double offsetY)
{
drawEdges(g2d, context, lineColour, lineStroke, GraphUtil.offCellConnections(topology()), offsetY);
}
//-------------------------------------------------------------------------
public BasicStroke strokeThick()
{
return strokeThick;
}
public Color colorSymbol()
{
return colorSymbol;
}
public void setColorSymbol(final Color colorSymbol)
{
this.colorSymbol = colorSymbol;
}
public Topology topology()
{
return boardStyle.topology();
}
public int cellRadiusPixels()
{
return boardStyle.cellRadiusPixels();
}
public Point screenPosn(final Point2D posn)
{
return boardStyle.screenPosn(posn);
}
//-------------------------------------------------------------------------
}
| 38,712 | 33.565179 | 211 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/ContainerDesign.java
|
package view.container.aspects.designs;
import java.awt.Graphics2D;
import bridge.Bridge;
import other.context.Context;
public class ContainerDesign
{
@SuppressWarnings("static-method")
public String createSVGImage(final Bridge bridge, final Context context)
{
return null;
}
public void drawPuzzleHints(final Graphics2D g2d, final Context context)
{
// do nothing
}
public void drawPuzzleCandidates(final Graphics2D g2d, final Context context)
{
// Do nothing.
}
@SuppressWarnings("static-method")
public boolean ignorePieceSelectionLimit()
{
return false;
}
}
| 597 | 17.6875 | 79 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/BackgammonDesign.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.GeneralPath;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import other.context.Context;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.Board.BackgammonPlacement;
import view.container.styles.board.BackgammonStyle;
public class BackgammonDesign extends BoardDesign
{
private final BackgammonStyle backgammonStyle;
private final BackgammonPlacement backgammonPlacement;
//-------------------------------------------------------------------------
public BackgammonDesign(final BackgammonStyle boardStyle, final BackgammonPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
backgammonStyle = boardStyle;
backgammonPlacement = boardPlacement;
}
//-------------------------------------------------------------------------
private final Color[] boardColours =
{
new Color(225, 182, 130), // light strip
new Color(116, 58, 41), // dark strip
new Color(140, 75, 45), // frame
new Color(185, 130, 85), // base
};
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
boardPlacement.customiseGraphElementLocations(context);
// Board image
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
setStrokesAndColours
(
bridge,
context,
new Color(120, 190, 240),
new Color(125, 75, 0),
new Color(210, 230, 255),
null,
null,
null,
null,
null,
new Color(0, 0, 0),
Math.max(1, (int) (0.0025 * boardStyle.placement().width + 0.5)),
(int) (2.0 * Math.max(1, (int) (0.0025 * boardStyle.placement().width + 0.5)))
);
drawBackgammonBoard(g2d);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
/**
* Draws the Backgammon board design.
*/
void drawBackgammonBoard(final Graphics2D g2d)
{
// N = homeSize
//
// A------------------------------------------+
// | C-----------------+ E-----------------+ |
// | |2N+1 . . . 3N|3N|3N+2 . . . 4N+1| |
// | | |+1| | |
// | | | | | |
// | | | | | |
// | | | | | |
// | | | | | |
// | | | | | |
// | | | | | |
// | | | | | |
// | |0 . . . . N-1|N |N+1 . . . 2N | |
// | +-----------------D +-----------------F |
// +------------------------------------------B
final Point pt0 = screenPosn(topology().vertices().get(0).centroid());
final Point pt1 = screenPosn(topology().vertices().get(1).centroid());
final int off = pt1.x - pt0.x;
final int unit = off;
final Point ptD = screenPosn(topology().vertices().get(backgammonPlacement.homeSize()-1).centroid());
final Point ptF = screenPosn(topology().vertices().get(2 * backgammonPlacement.homeSize()).centroid());
final Point ptC = screenPosn(topology().vertices().get(2 * backgammonPlacement.homeSize() + 1).centroid());
final Point ptE = screenPosn(topology().vertices().get(3 * backgammonPlacement.homeSize() + 2).centroid());
final int pr = (int)(off * 0.5);
final int border = (int)(off * 0.5);
final int cx = ptC.x - pr;
final int cy = ptC.y - pr;
final int ex = ptE.x - pr;
final int ey = ptE.y - pr;
final int dx = ptD.x + pr;
final int dy = ptD.y + pr;
final int fx = ptF.x + pr;
final int fy = ptF.y + pr;
final int ax = cx - border;
final int ay = cy - border;
final int bx = fx + border;
final int by = fy + border;
g2d.setColor(boardColours[2]);
g2d.fillRect(ax, ay, Math.abs(bx-ax), Math.abs(by-ay));
g2d.setColor(boardColours[3]);
g2d.fillRect(cx, cy, Math.abs(dx-cx), Math.abs(dy-cy));
g2d.fillRect(ex, ey, Math.abs(fx-ex), Math.abs(fy-ey));
// Draw the triangular strips
final GeneralPath pathD = new GeneralPath();
final GeneralPath pathL = new GeneralPath();
final int halfSize = topology().vertices().size() / 2;
int counter = 0; // counter for checking triangle parity
for (int n = 0; n < halfSize; n++)
{
if (n == backgammonPlacement.homeSize() || n == 3 * backgammonPlacement.homeSize() + 1)
continue;
counter++;
final int tx0 = cx + n % halfSize * unit;
final int ty0 = cy;
final int ty1 = ty0 + (int)(4.5 * unit + 0.5);
final int bx0 = cx + n % halfSize * unit;
final int by0 = dy;
final int by1 = by0 - (int)(4.5 * unit + 0.5);
if (counter % 2 == 0)
{
pathD.moveTo(tx0, ty0);
pathD.lineTo(tx0 + unit, ty0);
pathD.lineTo(tx0 + 0.5 * unit, ty1);
pathD.closePath();
pathL.moveTo(bx0, by0);
pathL.lineTo(bx0 + unit, by0);
pathL.lineTo(bx0 + 0.5 * unit, by1);
pathL.closePath();
}
else
{
pathL.moveTo(tx0, ty0);
pathL.lineTo(tx0 + unit, ty0);
pathL.lineTo(tx0 + 0.5 * unit, ty1);
pathL.closePath();
pathD.moveTo(bx0, by0);
pathD.lineTo(bx0 + unit, by0);
pathD.lineTo(bx0 + 0.5 * unit, by1);
pathD.closePath();
}
}
g2d.setColor(boardColours[0]);
g2d.fill(pathL);
g2d.setColor(boardColours[1]);
g2d.fill(pathD);
}
public BackgammonStyle getBackgammonStyle()
{
return backgammonStyle;
}
//-------------------------------------------------------------------------
}
| 5,612 | 27.784615 | 109 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/BoardlessDesign.java
|
package view.container.aspects.designs.board;
import bridge.Bridge;
import other.context.Context;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.Board.BoardlessPlacement;
import view.container.styles.board.BoardlessStyle;
public class BoardlessDesign extends BoardDesign
{
private final BoardlessStyle boardlessStyle;
private final BoardlessPlacement boardlessPlacement;
//-------------------------------------------------------------------------
public BoardlessDesign(final BoardlessStyle boardlessStyle, final BoardlessPlacement boardlessPlacement)
{
super(boardlessStyle, boardlessPlacement);
this.boardlessStyle = boardlessStyle;
this.boardlessPlacement = boardlessPlacement;
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
boardlessPlacement.updateZoomImage(context);
// Board image
setStrokesAndColours
(
bridge,
context,
null,
null,
null,
null,
null,
null,
null,
null,
null,
1,
1
);
return "";
}
public BoardlessStyle getBoardlessStyle()
{
return boardlessStyle;
}
}
| 1,221 | 21.218182 | 106 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/ChessDesign.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import other.context.Context;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class ChessDesign extends BoardDesign
{
public ChessDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
checkeredBoard = true;
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 5 / 1000.0f;
final float swThin = Math.max(1, (int) (swRatio * boardStyle.placement().width + 0.5));
final float swThick = 1 * swThin;
setStrokesAndColours
(
bridge,
context,
new Color(0,0,0),
new Color(150, 75, 0), // border
new Color(200, 150, 75), // dark cells
new Color(250, 221, 144), // light cells
new Color(223, 178, 110), // middle cells
new Color(255, 240, 200), // other cells
null,
null,
new Color(0,0,0),
swThin,
swThick
);
drawGround(g2d, context, true);
fillCells(bridge, g2d, context);
drawSymbols(g2d, context);
drawGround(g2d, context, false);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
}
| 1,543 | 23.125 | 90 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/Connect4Design.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import java.awt.Graphics2D;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.types.board.SiteType;
import other.context.Context;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.board.Connect4Style;
public class Connect4Design extends BoardDesign
{
private static final int Connect4Rows = 6;
private final Connect4Style connect4Style;
//-------------------------------------------------------------------------
public Connect4Design(final Connect4Style boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
connect4Style = boardStyle;
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
// Board image
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
setStrokesAndColours
(
bridge,
context,
new Color(120, 190, 240),
new Color(125, 75, 0),
new Color(210, 230, 255),
null,
null,
null,
null,
null,
new Color(0, 0, 0),
Math.max(1, (int) (0.0025 * boardStyle.placement().width + 0.5)),
(int) (2.0 * Math.max(1, (int) (0.0025 * boardStyle.placement().width + 0.5)))
);
drawConnect4Board(g2d);
topology().vertices().clear();
topology().edges().clear();
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
/**
* Draws the connect-4 board design.
*/
void drawConnect4Board(final Graphics2D g2d)
{
final int cols = topology().columns(SiteType.Cell).size();
final int rows = Connect4Rows;
final int u = boardStyle.placement().width / (cols + 1);
final int r = (int) (0.425 * u + 0.5);
final int x0 = boardStyle.placement().width / 2 - (int) (0.5 * cols * u + 0.5);
final int y0 = boardStyle.placement().width / 2 - (int) (0.5 * rows * u + 0.5);
final int expand = (int) (0.1 * u);
g2d.setColor(new Color(0, 100, 200));
final int corner = u / 4;
g2d.fillRoundRect(x0 - expand, y0 - expand, cols * u + 2 * expand, rows * u + 2 * expand, corner, corner);
// Draw the holes
g2d.setColor(Color.white);
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
final int cx = x0 + col * u + u / 2;
final int cy = y0 + row * u + u / 2;
g2d.fillArc(cx - r, cy - r, 2 * r, 2 * r, 0, 360);
}
}
}
//-------------------------------------------------------------------------
@Override
public boolean ignorePieceSelectionLimit()
{
return true;
}
public Connect4Style getConnect4Style()
{
return connect4Style;
}
//-------------------------------------------------------------------------
}
| 2,875 | 24.678571 | 108 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/ConnectiveGoalDesign.java
|
package view.container.aspects.designs.board;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.util.BitSet;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.equipment.other.Regions;
import game.functions.region.RegionFunction;
import game.util.graph.Properties;
import main.math.MathRoutines;
import other.context.Context;
import other.topology.Cell;
import other.topology.Edge;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class ConnectiveGoalDesign extends BoardDesign
{
public ConnectiveGoalDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
/**
* fill, draw internal grid lines, draw symbols, draw outer border on top.
* @return SVG as string.
*/
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
// Set all values
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final double boardLineThickness = boardStyle.cellRadiusPixels()/15.0;
checkeredBoard = context.game().metadata().graphics().checkeredBoard();
straightLines = context.game().metadata().graphics().straightRingLines();
final float swThin = (float) Math.max(1, boardLineThickness);
final float swThick = swThin;
setStrokesAndColours
(
bridge,
context,
new Color(120, 190, 240),
new Color(120, 190, 240),
new Color(210, 230, 255),
new Color(210, 0, 0),
new Color(0, 230, 0),
new Color(0, 0, 255),
null,
null,
new Color(0, 0, 0),
swThin,
swThick
);
// Background
drawGround(g2d, context, true);
// Cells
fillCells(bridge, g2d, context);
// Edges
drawOuterCellEdges(bridge, g2d, context);
// Symbols
drawSymbols(g2d, context);
// Foreground
drawGround(g2d, context, false);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
@Override
protected void drawOuterCellEdges(final Bridge bridge, final Graphics2D g2d, final Context context)
{
final Regions[] regionsList = context.game().equipment().regions();
final int numPlayers = context.game().players().count();
final Point2D.Double centre = topology().centrePoint();
final Point ptCentre = screenPosn(centre);
// Create a path for each player
final GeneralPath[] paths = new GeneralPath[context.game().players().count()+1];
for (int pid = 0; pid < paths.length; pid++)
paths[pid] = new GeneralPath();
// Locate sites shared by more than one player
final BitSet[] shared = new BitSet[numPlayers+2];
for (int pid = 0; pid < shared.length; pid++)
shared[pid] = new BitSet();
for (final Regions regionsO : regionsList)
{
final int pid = regionsO.owner();
final int[] sites = regionsO.eval(context);
for (final int cid : sites)
shared[pid].set(cid, true);
}
for (int pidA = 1; pidA < shared.length; pidA++)
for (int pidB = 2; pidB < shared.length; pidB++)
{
if (pidA == pidB)
continue;
final BitSet bs = (BitSet)shared[pidA].clone();
bs.and(shared[pidB]);
shared[0].or(bs);
}
for (int pid = 1; pid < shared.length; pid++)
shared[pid].and(shared[0]);
// Generate the paths
for (final Regions regionsO : regionsList)
{
final int pid = regionsO.owner();
final int[] sites = regionsO.eval(context);
for (final int site : sites)
{
final Cell cell = topology().cells().get(site);
for (final Edge edge : cell.edges())
{
if (edge.properties().get(Properties.OUTER))
{
final Point2D va = edge.vA().centroid();
final Point2D vb = edge.vB().centroid();
final Point ptA = screenPosn(va);
final Point ptB = screenPosn(vb);
paths[pid].moveTo(ptA.x, ptA.y);
paths[pid].lineTo(ptB.x, ptB.y);
}
}
}
}
// Draw the border and player colour in thick strokes
final int thickness = (int)(4 * strokeThick.getLineWidth());
final BasicStroke borderStroke = new BasicStroke(thickness+2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
final Stroke playerStroke = new BasicStroke(thickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
// Draw each region, clipped as necessary
final Shape oldClip = g2d.getClip();
for (final Regions regionsO : regionsList)
{
if (regionsO.region() == null)
continue;
final int pid = regionsO.owner();
final Color playerColour = bridge.settingsColour().playerColour(context, pid);
final Color borderColour = MathRoutines.shade(playerColour, 0.75);
for (final RegionFunction region : regionsO.region())
{
final int[] sites = region.eval(context).sites();
final GeneralPath path = new GeneralPath();
Point ptSharedA = null;
Point ptSharedB = null;
for (final int site : sites)
{
final Cell cell = topology().cells().get(site);
if (shared[0].get(site))
{
// Shared cell: store its pixel location
final Point pt = screenPosn(cell.centroid());
if (ptSharedA == null)
ptSharedA = pt;
else
ptSharedB = pt;
}
for (final Edge edge : cell.edges())
{
if (edge.properties().get(Properties.OUTER))
{
final Point2D va = edge.vA().centroid();
final Point2D vb = edge.vB().centroid();
final Point ptA = screenPosn(va);
final Point ptB = screenPosn(vb);
path.moveTo(ptA.x, ptA.y);
path.lineTo(ptB.x, ptB.y);
}
}
}
g2d.setClip(oldClip);
if (ptSharedA != null && ptSharedB != null)
{
// Clip triangle from centre to lines projected through
// shared cells (should be extremities of regions).
final int ax = ptCentre.x + 2 * (ptSharedA.x - ptCentre.x);
final int ay = ptCentre.y + 2 * (ptSharedA.y - ptCentre.y);
final Point ptA = new Point(ax, ay);
final int bx = ptCentre.x + 2 * (ptSharedB.x - ptCentre.x);
final int by = ptCentre.y + 2 * (ptSharedB.y - ptCentre.y);
final Point ptB = new Point(bx, by);
final GeneralPath pathClip = new GeneralPath();
pathClip.moveTo(ptCentre.x, ptCentre.y);
pathClip.lineTo(ptA.x, ptA.y);
pathClip.lineTo(ptB.x, ptB.y);
pathClip.closePath();
g2d.setClip(pathClip);
}
else if (ptSharedA != null)
{
// Clip triangle from centre to lines projected through shared cell
// Only one shared cell!
final int ax = ptCentre.x + 2 * (ptSharedA.x - ptCentre.x);
final int ay = ptCentre.y + 2 * (ptSharedA.y - ptCentre.y);
final Point ptA = new Point(ax, ay);
// Find furthest cell in region
Point ptBestB = null;
double maxDist = 0;
for (final int site : sites)
{
final Cell cell = topology().cells().get(site);
final Point pt = screenPosn(cell.centroid());
final double dist = MathRoutines.distance(pt, ptA);
if (dist > maxDist)
{
ptBestB = new Point(pt.x, pt.y);
maxDist = dist;
}
}
if (ptBestB == null)
{
System.out.println("** Failed to find furthest point.");
return;
}
// Extend beyond further point, so it isn't clipped
final int bestBx = ptA.x + (int)(1.25 * (ptBestB.x - ptA.x));
final int bestBy = ptA.y + (int)(1.25 * (ptBestB.y - ptA.y));
ptBestB = new Point(bestBx, bestBy);
final int bx = ptCentre.x + 2 * (ptBestB.x - ptCentre.x);
final int by = ptCentre.y + 2 * (ptBestB.y - ptCentre.y);
final Point ptB = new Point(bx, by);
final GeneralPath pathClip = new GeneralPath();
pathClip.moveTo(ptCentre.x, ptCentre.y);
pathClip.lineTo(ptA.x, ptA.y);
pathClip.lineTo(ptB.x, ptB.y);
pathClip.closePath();
g2d.setClip(pathClip);
}
// Draw extra thick line in dark border colour
g2d.setColor(borderColour);
g2d.setStroke(borderStroke);
g2d.draw(path); //s[pid]);
// Draw thick line in player colour
g2d.setColor(playerColour);
g2d.setStroke(playerStroke);
g2d.draw(path);
}
}
g2d.setClip(oldClip);
}
//-------------------------------------------------------------------------
}
| 8,588 | 27.822148 | 111 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/GoDesign.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import java.util.ArrayList;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.types.board.SiteType;
import metadata.graphics.util.MetadataImageInfo;
import other.context.Context;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class GoDesign extends BoardDesign
{
public GoDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 0.002f;
final float swThin = Math.max(0.5f, swRatio * boardStyle.placement().width);
final float swThick = swThin;
final Color colourInner = new Color(160, 140, 100);
final Color colourOuter = new Color( 0, 0, 0);
final Color colourFill = new Color(255, 230, 150);
final Color colourDot = new Color(130, 120, 90); //colourInner;
setStrokesAndColours
(
bridge,
context,
colourInner,
colourOuter,
colourFill,
null,
null,
null,
null,
null,
colourDot,
swThin,
swThick
);
fillCells(bridge, g2d, context);
drawInnerCellEdges(g2d, context);
drawOuterCellEdges(bridge, g2d, context);
final ArrayList<Integer> symbolLocations = new ArrayList<Integer>();
final int boardCellsWidth = topology().columns(context.board().defaultSite()).size();
final int boardCellsHeight = topology().rows(context.board().defaultSite()).size();
if (boardCellsWidth > 13)
{
symbolLocations.add(Integer.valueOf(boardCellsWidth * 3 + 3));
symbolLocations.add(Integer.valueOf(boardCellsWidth * 3 + boardCellsWidth/2));
symbolLocations.add(Integer.valueOf(boardCellsWidth * 3 + boardCellsWidth - 4));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-1)/2 + 3));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-1)/2 + boardCellsWidth/2));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-1)/2 + boardCellsWidth - 4));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-4) + 3));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-4) + boardCellsWidth/2));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-4) + boardCellsWidth - 4));
}
else if (boardCellsWidth > 9)
{
symbolLocations.add(Integer.valueOf(boardCellsWidth * 3 + 3));
symbolLocations.add(Integer.valueOf(boardCellsWidth * 3 + boardCellsWidth - 4));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-1)/2 + boardCellsWidth/2));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-4) + 3));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-4) + boardCellsWidth - 4));
}
else
{
symbolLocations.add(Integer.valueOf(boardCellsWidth * 2 + 2));
symbolLocations.add(Integer.valueOf(boardCellsWidth * 2 + boardCellsWidth - 3));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-1)/2 + boardCellsWidth/2));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-3) + 2));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-3) + boardCellsWidth - 3));
}
for (final int i : symbolLocations)
{
symbols.add(new MetadataImageInfo(i, SiteType.Vertex, "dot", (float)0.3));
}
drawSymbols(g2d, context);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
}
| 3,825 | 35.788462 | 104 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/HoundsAndJackalsDesign.java
|
package view.container.aspects.designs.board;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Arc2D;
import java.awt.geom.GeneralPath;
import java.util.BitSet;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import other.context.Context;
import other.topology.Vertex;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class HoundsAndJackalsDesign extends BoardDesign
{
final private BitSet specialDots = new BitSet();
//-------------------------------------------------------------------------
public HoundsAndJackalsDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
specialDots.set(0);
specialDots.set(5);
specialDots.set(7);
specialDots.set(9);
specialDots.set(14);
specialDots.set(19);
specialDots.set(24);
specialDots.set(29);
specialDots.set(34);
specialDots.set(36);
specialDots.set(38);
specialDots.set(43);
specialDots.set(48);
specialDots.set(53);
specialDots.set(58);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 5 / 1000.0f;
final float swThin = Math.max(1, (int) (swRatio * boardStyle.placement().width + 0.5));
final float swThick = 2 * swThin;
setStrokesAndColours
(
bridge,
context,
new Color(200, 200, 200),
null,
null,
null,
null,
null,
null,
null,
new Color(140,140,140),
swThin,
swThick
);
drawHoundsAndJackalsBoard(g2d);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
/**
* Draws the hounds and Jackals board design.
*/
void drawHoundsAndJackalsBoard(final Graphics2D g2d)
{
// Draw the board
GeneralPath path = new GeneralPath();
final Point pt0 = screenPosn(topology().vertices().get(0).centroid());
final Point pt1 = screenPosn(topology().vertices().get(1).centroid());
final int unit = pt1.y - pt0.y;
final Point ptA = screenPosn(topology().vertices().get(10).centroid());
final Point ptB = screenPosn(topology().vertices().get(23).centroid());
final Point ptE = screenPosn(topology().vertices().get(58).centroid());
final Point ptH = screenPosn(topology().vertices().get(52).centroid());
final Point ptI = screenPosn(topology().vertices().get(39).centroid());
final int border = (int)(0.9 * unit);
// CPs up left side
int ax = ptA.x - border;
int ay = ptA.y + border;
int bx = ax;
int by = ptB.y;
int cx = ax;
int cy = by - 3 * unit;
// CPs along top
final int ex = ptE.x;
final int ey = ptE.y - border;
int dx = ex - 1 * unit;
int dy = ey;
final int fx = ex + 1 * unit;
final int fy = ey;
// CPs down right side
final int hx = ptH.x + border;
final int hy = ptH.y;
final int gx = hx;
final int gy = hy - 3 * unit;
final int ix = hx;
final int iy = ptI.y + border;
path.moveTo(ax, ay);
path.lineTo(bx, by);
path.curveTo(cx, cy, dx, dy, ex, ey);
path.curveTo(fx, fy, gx, gy, hx, hy);
path.lineTo(ix, iy);
path.closePath();
g2d.setColor(new Color(255, 240, 220));
g2d.fill(path);
final BasicStroke strokeB = new BasicStroke(0.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
g2d.setStroke(strokeB);
g2d.setColor(new Color(127, 120, 110));
g2d.draw(path);
// Draw the dots
final int rO = (int)(0.15 * unit);
final int rI = rO / 2;
final float sw = 0.03f * unit;
final BasicStroke strokeD = new BasicStroke(sw, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
g2d.setStroke(strokeD);
final Color dotColour = new Color(190, 150, 100);
g2d.setColor(dotColour);
for (int vid = 0; vid < topology().vertices().size(); vid++)
{
final Vertex vertex = topology().vertices().get(vid);
final Point pt = screenPosn(vertex.centroid());
final java.awt.Shape arcO = new Arc2D.Double(pt.x-rO, pt.y-rO, 2*rO+1, 2*rO+1, 0, 360, 0);
g2d.draw(arcO);
if (specialDots.get(vid))
{
// Also draw inner dot
final java.awt.Shape arcI = new Arc2D.Double(pt.x-rI, pt.y-rI, 2*rI+1, 2*rI+1, 0, 360, 0);
g2d.draw(arcI);
}
}
// Draw short curves
final BasicStroke strokeC = new BasicStroke(2*sw, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
g2d.setStroke(strokeC);
final Point pt5 = screenPosn(topology().vertices().get(5).centroid());
final Point pt7 = screenPosn(topology().vertices().get(7).centroid());
final Point pt9 = screenPosn(topology().vertices().get(9).centroid());
final Point pt19 = screenPosn(topology().vertices().get(19).centroid());
final Point pt34 = screenPosn(topology().vertices().get(34).centroid());
final Point pt36 = screenPosn(topology().vertices().get(36).centroid());
final Point pt38 = screenPosn(topology().vertices().get(38).centroid());
final Point pt48 = screenPosn(topology().vertices().get(48).centroid());
final int d1 = (int)(0.333 * unit);
final int d2 = (int)(1.333 * unit);
// Lower left
ax = pt9.x - d1;
ay = pt9.y;
bx = pt9.x - d2;
by = pt9.y;
cx = pt7.x - d2;
cy = pt7.y;
dx = pt7.x - d1;
dy = pt7.y;
path = new GeneralPath();
path.moveTo(ax, ay);
path.curveTo(bx, by, cx, cy, dx, dy);
g2d.draw(path);
// Lower right
ax = pt38.x + d1;
ay = pt38.y;
bx = pt38.x + d2;
by = pt38.y;
cx = pt36.x + d2;
cy = pt36.y;
dx = pt36.x + d1;
dy = pt36.y;
path = new GeneralPath();
path.moveTo(ax, ay);
path.curveTo(bx, by, cx, cy, dx, dy);
g2d.draw(path);
// Upper left
ax = pt5.x - d1;
ay = pt5.y;
bx = pt5.x - d2;
by = pt5.y;
cx = pt19.x + d2;
cy = pt19.y;
dx = pt19.x + d1;
dy = pt19.y;
path = new GeneralPath();
path.moveTo(ax, ay);
path.curveTo(bx, by, cx, cy, dx, dy);
g2d.draw(path);
// Upper right
ax = pt34.x + d1;
ay = pt34.y;
bx = pt34.x + d2;
by = pt34.y;
cx = pt48.x - d2;
cy = pt48.y;
dx = pt48.x - d1;
dy = pt48.y;
path = new GeneralPath();
path.moveTo(ax, ay);
path.curveTo(bx, by, cx, cy, dx, dy);
g2d.draw(path);
}
//-------------------------------------------------------------------------
}
| 6,450 | 24.003876 | 99 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/IsometricDesign.java
|
package view.container.aspects.designs.board;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class IsometricDesign extends BoardDesign
{
public IsometricDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 464 | 26.352941 | 90 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/JanggiDesign.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import other.context.Context;
import other.topology.Vertex;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class JanggiDesign extends BoardDesign
{
public JanggiDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 5 / 1000.0f;
final float swThin = Math.max(1, (int) (swRatio * boardStyle.placement().width + 0.5));
final float swThick = swThin;
setStrokesAndColours
(
bridge,
context,
new Color(100, 75, 50),
new Color(100, 75, 50),
new Color(255, 165, 0),
null,
null,
null,
null,
null,
new Color(0, 0, 0),
swThin,
swThick
);
drawBoardOutline(g2d);
drawInnerCellEdges(g2d, context);
drawOuterCellEdges(bridge, g2d, context);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
@Override
protected void drawInnerCellEdges(final Graphics2D g2d, final Context context)
{
// Draw cell edges (inner)
g2d.setStroke(strokeThin);
g2d.setColor(colorEdgesInner);
final GeneralPath path = new GeneralPath();
for (final Vertex vA : topology().vertices())
{
for (final Vertex vB : vA.orthogonal())
{
final Point2D va = vA.centroid();
final Point2D vb = vB.centroid();
// only draw inner edges if not overlapping the river
if ((va.getY() < 0.5 || vb.getY() > 0.5) && (va.getY() > 0.5 || vb.getY() < 0.5))
{
final Point vaWorld = screenPosn(vA.centroid());
final Point vbWorld = screenPosn(vB.centroid());
path.moveTo(vaWorld.x, vaWorld.y);
path.lineTo(vbWorld.x, vbWorld.y);
}
}
}
Point screenPosn = screenPosn(topology().vertices().get(3).centroid());
path.moveTo(screenPosn.x, screenPosn.y);
screenPosn = screenPosn(topology().vertices().get(23).centroid());
path.lineTo(screenPosn.x, screenPosn.y);
screenPosn = screenPosn(topology().vertices().get(5).centroid());
path.moveTo(screenPosn.x, screenPosn.y);
screenPosn = screenPosn(topology().vertices().get(21).centroid());
path.lineTo(screenPosn.x, screenPosn.y);
screenPosn = screenPosn(topology().vertices().get(86).centroid());
path.moveTo(screenPosn.x, screenPosn.y);
screenPosn = screenPosn(topology().vertices().get(66).centroid());
path.lineTo(screenPosn.x, screenPosn.y);
screenPosn = screenPosn(topology().vertices().get(84).centroid());
path.moveTo(screenPosn.x, screenPosn.y);
screenPosn = screenPosn(topology().vertices().get(68).centroid());
path.lineTo(screenPosn.x, screenPosn.y);
g2d.draw(path);
}
//-------------------------------------------------------------------------
}
| 3,259 | 27.596491 | 90 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/LascaDesign.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import other.context.Context;
import other.topology.TopologyElement;
import other.topology.Vertex;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class LascaDesign extends BoardDesign
{
public LascaDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 5 / 1000.0f;
final float swThin = Math.max(1, (int) (swRatio * boardStyle.placement().width + 0.5));
final float swThick = 2 * swThin;
setStrokesAndColours
(
bridge,
context,
null,
null,
new Color(200, 200, 200),
null,
null,
new Color(255, 255, 255),
null,
null,
null,
swThin,
swThick
);
final double vertexRadius = boardStyle.cellRadiusPixels() * 0.95;
drawBoardOutline(g2d);
drawVertices(bridge, g2d, context, vertexRadius);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
@Override
protected void drawVertices(final Bridge bridge, final Graphics2D g2d, final Context context, final double vertexRadius)
{
g2d.setColor(colorFillPhase3);
for (final Vertex vertex : topology().vertices())
{
final Point position = screenPosn(vertex.centroid());
final java.awt.Shape ellipseO = new Ellipse2D.Double(position.x - vertexRadius, position.y - vertexRadius, 2*vertexRadius, 2*vertexRadius);
g2d.fill(ellipseO);
}
}
//-------------------------------------------------------------------------
@Override
public void drawBoardOutline(final SVGGraphics2D g2d)
{
g2d.setStroke(strokeThin);
double minX = 9999;
double minY = 9999;
double maxX = -9999;
double maxY = -9999;
final GeneralPath path = new GeneralPath();
for (final TopologyElement cell : topology().vertices())
{
final Point posn = screenPosn(cell.centroid());
final int x = posn.x;
final int y = posn.y;
if (minX > x)
minX = x;
if (minY > y)
minY = y;
if (maxX < x)
maxX = x;
if (maxY < y)
maxY = y;
}
g2d.setColor(colorFillPhase0);
final int OuterBufferDistance = (int) (cellRadiusPixels() * 1.1);
path.moveTo(minX - OuterBufferDistance, minY - OuterBufferDistance);
path.lineTo(minX - OuterBufferDistance, maxY + OuterBufferDistance);
path.lineTo(maxX + OuterBufferDistance, maxY + OuterBufferDistance);
path.lineTo(maxX + OuterBufferDistance, minY - OuterBufferDistance);
path.lineTo(minX - OuterBufferDistance, minY - OuterBufferDistance);
g2d.fill(path);
}
//-------------------------------------------------------------------------
}
| 3,176 | 25.475 | 142 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/MancalaDesign.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.equipment.container.board.custom.MancalaBoard;
import game.types.board.StoreType;
import gnu.trove.list.array.TIntArrayList;
import metadata.graphics.util.HoleType;
import other.concept.Concept;
import other.context.Context;
import other.topology.Vertex;
import view.container.aspects.designs.BoardDesign;
import view.container.styles.BoardStyle;
/**
* Graphics for Mancala boards.
*
* @author cambolbro and Eric.Piette
*/
public class MancalaDesign extends BoardDesign
{
public MancalaDesign(final BoardStyle boardStyle)
{
super(boardStyle, null);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final int swThin = Math.max(1, (int)(0.001 * boardStyle.placement().width + 0.5));
final int swThick = 2 * swThin;
setStrokesAndColours
(
bridge,
context,
null,
new Color(125, 75, 0),
new Color(255, 220, 100),
null,
null,
null,
null,
null,
new Color(127, 100, 50),
swThin,
swThick
);
final Rectangle2D bounds = context.board().graph().bounds();
final int numColumns = (context.board() instanceof MancalaBoard) ? ((MancalaBoard) context.board()).numColumns()
: (int) (bounds.getWidth() - 0.5);
final int numRows = (context.board() instanceof MancalaBoard) ? ((MancalaBoard) context.board()).numRows()
: (int) (bounds.getHeight() + 0.5) + 1;
final boolean withStore = (context.board() instanceof MancalaBoard)
? !((MancalaBoard) context.board()).storeType().equals(StoreType.None)
: true;
final int[] specialHoles = context.metadata().graphics().sitesAsSpecialHoles();
final HoleType type = context.metadata().graphics().shapeSpecialHole();
final boolean circleTiling = context.game().booleanConcepts().get(Concept.CircleTiling.id());
final boolean notMancalaBoard = !circleTiling && !(context.board() instanceof MancalaBoard);
drawMancalaBoard(g2d, numRows, numColumns, withStore, circleTiling, new TIntArrayList(specialHoles), type, notMancalaBoard);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
/**
* Draw the Mancala board.
*
* @param g2d The graphics 2D.
* @param rows The number of rows.
* @param cols The number of columns.
* @param withStore True if the board has storage for each player.
* @param circleTiling True if the tiling used is circle.
* @param specialHoles The sites which should be squares.
* @param type The shape of the special holes.
* @param notMancalaBoard True if the board is not mancala and not a circle.
*/
void drawMancalaBoard
(
final Graphics2D g2d,
final int rows,
final int cols,
final boolean withStore,
final boolean circleTiling,
final TIntArrayList specialHoles,
final HoleType type,
final boolean notMancalaBoard
)
{
final int indexHoleBL = (withStore) ? 1 : 0;
final int indexHoleTR = (withStore) ? rows * cols : rows * cols - 1;
final int indexHoleBR = (withStore) ? cols : cols - 1;
final int indexHoleTL = indexHoleBR + 1 + (rows - 2) * cols;
// Distance between pits in x direction
final Point pt1 = screenPosn(topology().vertices().get(circleTiling ? 0 : indexHoleBL).centroid());
final Point pt2 = screenPosn(topology().vertices().get(circleTiling ? 1 : (indexHoleBL + 1)).centroid());
final int dx = Math.abs(pt2.x - pt1.x);
final double radius = 0.666 * dx; // radius of rounded board ends
Point pt = null;
if (circleTiling)
{
// Compute the centre of the board.
double sumX = 0.0;
double sumY = 0.0;
// Compute the radius of the board;
double circleDx = 0.0;
double circleDy = 0.0;
for (final Vertex v : topology().vertices())
{
sumX += screenPosn(v.centroid()).getX();
sumY += screenPosn(v.centroid()).getY();
for (final Vertex v2 : topology().vertices())
{
final double currentDx = Math
.abs(screenPosn(v.centroid()).getX() - screenPosn(v2.centroid()).getX());
final double currentDy = Math
.abs(screenPosn(v.centroid()).getY() - screenPosn(v2.centroid()).getY());
if (currentDx > circleDx)
circleDx = currentDx;
if (currentDy > circleDy)
circleDy = currentDy;
}
}
final double centreX = sumX / topology().vertices().size();
final double centreY = sumY / topology().vertices().size();
circleDx = circleDx / 2 + radius;
circleDy = circleDy / 2 + radius;
g2d.setColor(colorFillPhase0);
final Shape circleShape = new Ellipse2D.Double(centreX - circleDx, centreY - circleDy, 2.0 * circleDx,
2.0 * circleDy);
g2d.fill(circleShape);
g2d.setColor(colorEdgesOuter);
g2d.setStroke(strokeThick());
g2d.draw(circleShape);
}
else if (notMancalaBoard)
{
// Compute the centre of the board.
double maxDx = 0.0;
double maxDy = 0.0;
double topY = screenPosn(topology().vertices().get(0).centroid()).getY();
double leftX = screenPosn(topology().vertices().get(0).centroid()).getX();
for (final Vertex v : topology().vertices())
{
final Point2D screenPosnV = screenPosn(v.centroid());
if (topY > screenPosnV.getY())
topY = screenPosnV.getY();
if (leftX > screenPosnV.getX())
leftX = screenPosnV.getX();
for (final Vertex v2 : topology().vertices())
{
final Point2D screenPosnV2 = screenPosn(v2.centroid());
final double dY = Math.abs(screenPosnV.getY() - screenPosnV2.getY());
if (maxDy < dY)
maxDy = dY;
final double dX = Math.abs(screenPosnV.getX() - screenPosnV2.getX());
if (maxDx < dX)
maxDx = dX;
}
}
// final int angle = (rows < 30) ? rows * 15 : rows * 10; // arc angle for board
// corners (30 and 60)
final int angle = 60;
maxDx += dx;
maxDy += dx;
leftX -= dx / 2;
topY -= dx / 2;
final RoundRectangle2D shape = new RoundRectangle2D.Double(leftX, topY, maxDx, maxDy,
angle, angle);
g2d.setColor(colorFillPhase0);
g2d.fill(shape);
g2d.setColor(colorEdgesOuter);
g2d.setStroke(strokeThick());
g2d.draw(shape);
}
else if (withStore)
{
final Point2D ptBL = topology().vertices().get(indexHoleBL).centroid();
final Point2D ptTR = topology().vertices().get(indexHoleTR).centroid();
final Point2D ptBR = topology().vertices().get(indexHoleBR).centroid();
final Point2D ptTL = topology().vertices().get(indexHoleTL).centroid();
// correct only if the board has stores.
final Point2D ptL = topology().vertices().get(0).centroid();
final Point2D ptR = (withStore) ? topology().vertices().get(rows * cols + 1).centroid()
: topology().vertices().get(0).centroid();
final int angleForStorage = 120 / rows; // arc angle for storage pits (60 and 30)
final int angleForCorners = rows * 15; // arc angle for board corners (30 and 60)
final GeneralPath boardShape = new GeneralPath();
pt = screenPosn(withStore ? ptL : ptBL);
boardShape.append(new Arc2D.Double(pt.x - radius, pt.y - radius, 2 * radius, 2 * radius,
180 - angleForStorage, 2 * angleForStorage, Arc2D.OPEN), true);
pt = screenPosn(ptBL);
boardShape.append(new Arc2D.Double(pt.x - radius, pt.y - radius, 2 * radius, 2 * radius,
270 - angleForCorners, angleForCorners, Arc2D.OPEN), true);
pt = screenPosn(ptBR);
boardShape.append(new Arc2D.Double(pt.x - radius, pt.y - radius, 2 * radius, 2 * radius, 270,
angleForCorners, Arc2D.OPEN), true);
pt = screenPosn(ptR);
boardShape.append(new Arc2D.Double(pt.x - radius, pt.y - radius, 2 * radius, 2 * radius,
360 - angleForStorage, 2 * angleForStorage, Arc2D.OPEN), true);
pt = screenPosn(ptTR);
boardShape.append(new Arc2D.Double(pt.x - radius, pt.y - radius, 2 * radius, 2 * radius,
90 - angleForCorners, angleForCorners, Arc2D.OPEN), true);
pt = screenPosn(ptTL);
boardShape.append(new Arc2D.Double(pt.x - radius, pt.y - radius, 2 * radius, 2 * radius, 90,
angleForCorners, Arc2D.OPEN), true);
boardShape.closePath();
g2d.setColor(colorFillPhase0);
g2d.fill(boardShape);
g2d.setColor(colorEdgesOuter);
g2d.setStroke(strokeThick());
g2d.draw(boardShape);
}
else
{
final Point2D ptBL = topology().vertices().get(indexHoleBL).centroid();
final Point2D ptTR = topology().vertices().get(indexHoleTR).centroid();
final Point2D ptBR = topology().vertices().get(indexHoleBR).centroid();
final Point2D ptTL = topology().vertices().get(indexHoleTL).centroid();
// correct only if the board has stores.
final Point2D ptL = topology().vertices().get(0).centroid();
pt = screenPosn(withStore ? ptL : ptBL);
pt = screenPosn(ptTL);
final double width = screenPosn(ptBR).x - screenPosn(ptBL).x + 2 * radius;
final double height = screenPosn(ptBR).y - screenPosn(ptTR).y + 2 * radius;
final int angle = (rows < 30) ? rows * 15 : rows * 10; // arc angle for board corners (30 and 60)
final RoundRectangle2D shape = new RoundRectangle2D.Double(pt.x - radius, pt.y - radius, width, height,
angle, angle);
g2d.setColor(colorFillPhase0);
g2d.fill(shape);
g2d.setColor(colorEdgesOuter);
g2d.setStroke(strokeThick());
g2d.draw(shape);
}
// Determine pit colours based on board colour
final int fillR = colorFillPhase0.getRed();
final int fillG = colorFillPhase0.getGreen();
final int fillB = colorFillPhase0.getBlue();
final float[] hsv = new float[3];
Color.RGBtoHSB(fillR, fillG, fillB, hsv);
final Color dark = new Color(Color.HSBtoRGB(hsv[0], hsv[1], 0.75f * hsv[2]));
final Color darker = new Color(Color.HSBtoRGB(hsv[0], hsv[1], 0.5f * hsv[2]));
// Draw pits
g2d.setStroke(strokeThin);
final int r = (int) (0.45 * dx); // pit radius
for (final Vertex vertex : topology().vertices())
{
pt = screenPosn(vertex.centroid());
if (specialHoles.contains(vertex.index()))
{
if (type == HoleType.Square)
drawSquare(g2d, pt.x, pt.y, r, null, dark, darker);
else if (type == HoleType.Oval)
drawOval(g2d, pt.x, pt.y, r, null, dark, darker);
}
else
drawPit(g2d, pt.x, pt.y, r, null, dark, darker);
}
}
//-------------------------------------------------------------------------
/**
* Draws a board pit at the specified location.
*/
@SuppressWarnings("static-method")
void drawPit
(
final Graphics2D g2d, final int x, final int y, final int r,
final Color lines, final Color dark, final Color darker
)
{
final int rr = (int)(0.85 * r);
g2d.setColor(darker);
g2d.fillArc(x-r, y-r, 2*r, 2*r, 0, 360);
g2d.setColor(dark);
g2d.fillArc(x-r, y-r, 2*r, 2*r, 180, 180);
g2d.fillArc(x-r, y-rr, 2*r, 2*rr, 0, 360);
if (lines != null)
{
g2d.setColor(lines);
g2d.drawArc(x-r, y-r, 2*r, 2*r, 0, 360);
}
}
/**
* Draws a square pit at the specified location.
*/
@SuppressWarnings("static-method")
void drawSquare
(
final Graphics2D g2d, final int x, final int y, final int r,
final Color lines, final Color dark, final Color darker
)
{
final int rr = (int) (0.95 * r);
g2d.setColor(darker);
g2d.fillRect(x - r, y - r, r * 2, r * 2);
g2d.setColor(dark);
g2d.fillRect(x - rr, y - rr, rr * 2, rr * 2);
}
/**
* Draws an oval pit at the specified location.
*/
@SuppressWarnings("static-method")
void drawOval
(
final Graphics2D g2d, final int x, final int y, final int r,
final Color lines, final Color dark, final Color darker
)
{
final int rr = (int)(0.85 * r);
g2d.setColor(darker);
g2d.fillArc(x - 3 * r, y - r, 6 * r, 2 * r, 0, 360);
g2d.setColor(dark);
g2d.fillArc(x - r * 3, y - r, 6 * r, 2 * r, 180, 180);
g2d.fillArc(x - r * 3, y - rr, 6 * r, 2 * rr, 0, 360);
if (lines != null)
{
g2d.setColor(lines);
g2d.drawArc(x - r * 3, y - r, 6 * r, 2 * r, 0, 360);
}
}
//-------------------------------------------------------------------------
}
| 12,433 | 30.478481 | 126 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/ShibumiDesign.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Path2D;
import java.util.List;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.types.board.SiteType;
import other.context.Context;
import other.topology.TopologyElement;
import other.topology.Vertex;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
/**
* Shibumi board design.
*
* @author cambolbro
*/
public class ShibumiDesign extends BoardDesign
{
public ShibumiDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 5 / 1000.0f;
final float swThin = Math.max(1, (int) (swRatio * boardStyle.placement().width + 0.5));
final float swThick = 2 * swThin;
setStrokesAndColours
(
bridge,
context,
null,
null,
null,
null,
new Color(66, 165, 245),
new Color(255, 255, 255),
null,
null,
null,
swThin,
swThick
);
drawBoardOutline(g2d);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
@Override
public void drawBoardOutline(final SVGGraphics2D g2d)
{
final List<TopologyElement> corners = topology().corners(SiteType.Vertex);
final int rO = (int)(boardStyle.cellRadiusPixels() * 1.1);
final int rI = (int)(boardStyle.cellRadiusPixels() * 0.75);
final Point[] pts =
{
screenPosn(corners.get(0).centroid()),
screenPosn(corners.get(2).centroid()),
screenPosn(corners.get(3).centroid()),
screenPosn(corners.get(1).centroid()),
};
final GeneralPath path = new GeneralPath(Path2D.WIND_EVEN_ODD);
// Outer board shape with rounded corners
path.moveTo(pts[3].x, pts[3].y+rO);
path.quadTo(pts[3].x+rO, pts[3].y+rO, pts[3].x+rO, pts[3].y);
path.lineTo(pts[2].x+rO, pts[2].y);
path.quadTo(pts[2].x+rO, pts[2].y-rO, pts[2].x, pts[2].y-rO);
path.lineTo(pts[1].x, pts[1].y-rO);
path.quadTo(pts[1].x-rO, pts[1].y-rO, pts[1].x-rO, pts[1].y);
path.lineTo(pts[0].x-rO, pts[0].y);
path.quadTo(pts[0].x-rO, pts[0].y+rO, pts[0].x, pts[0].y+rO);
path.closePath();
// Cut out holes for playable sites
for (final Vertex vertex : topology().vertices())
if (vertex.layer() == 0)
{
final Point pt = screenPosn(vertex.centroid());
final Shape shape = new Ellipse2D.Double(pt.x-rI, pt.y-rI, 2*rI, 2*rI);
path.append(shape, false);
}
// Dark base
g2d.setColor(new Color(60, 120, 200));
final AffineTransform atDown = new AffineTransform();
atDown.translate(0, rI/4);
path.transform(atDown);
g2d.fill(path);
// Light surface
g2d.setColor(new Color(80, 170, 255));
final AffineTransform atUp = new AffineTransform();
atUp.translate(0, -rI/4);
path.transform(atUp);
g2d.fill(path);
}
//-------------------------------------------------------------------------
}
| 3,399 | 25.984127 | 90 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/ShogiDesign.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import java.util.ArrayList;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.types.board.SiteType;
import metadata.graphics.util.MetadataImageInfo;
import other.context.Context;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class ShogiDesign extends BoardDesign
{
public ShogiDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 4 / 1000.0f;
final float swThin = Math.max(1, (int) ((swRatio * 100) / topology().vertices().size() * boardStyle.placement().width + 0.5));
final float swThick = swThin;
setStrokesAndColours
(
bridge,
context,
new Color(100, 75, 50),
new Color(100, 75, 50),
new Color(255, 230, 130),
null,
null,
null,
null,
null,
new Color(0, 0, 0),
swThin,
swThick
);
fillCells(bridge, g2d, context);
drawInnerCellEdges(g2d, context);
// Load the decoration for special cells
final int boardCellsWidth = topology().columns(context.board().defaultSite()).size() + 1;
final int boardCellsHeight = topology().rows(context.board().defaultSite()).size() + 1;
int dotInwardsValueVertical, dotInwardsValueHorizontal;
dotInwardsValueVertical = dotInwardsValueHorizontal = boardCellsWidth/3;
// Taikyoku Shogi
if (topology().cells().size() == 1296)
{
dotInwardsValueVertical = 6;
dotInwardsValueHorizontal = 7;
}
final ArrayList<Integer> symbolLocations = new ArrayList<>();
symbolLocations.add(Integer.valueOf(boardCellsWidth * dotInwardsValueVertical + dotInwardsValueHorizontal));
symbolLocations.add(Integer.valueOf(boardCellsWidth * dotInwardsValueVertical + boardCellsWidth - dotInwardsValueHorizontal-1));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-dotInwardsValueVertical-1) + dotInwardsValueHorizontal));
symbolLocations.add(Integer.valueOf(boardCellsWidth * (boardCellsHeight-dotInwardsValueVertical-1) + boardCellsWidth - dotInwardsValueHorizontal-1));
if (topology().numEdges() == 4)
for (final int i : symbolLocations)
symbols.add(new MetadataImageInfo(i,SiteType.Vertex,"dot",(float)0.2));
drawSymbols(g2d, context);
drawOuterCellEdges(bridge, g2d, context);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
}
| 2,780 | 30.602273 | 151 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/SnakesAndLaddersDesign.java
|
package view.container.aspects.designs.board;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.List;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.Game;
import game.equipment.other.Map;
import main.math.MathRoutines;
import other.context.Context;
import other.topology.Cell;
import other.topology.Vertex;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class SnakesAndLaddersDesign extends BoardDesign
{
public SnakesAndLaddersDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 5 / 1000.0f;
final float swThin = Math.max(1, (int) (swRatio * boardStyle.placement().width + 0.5));
final float swThick = Math.max(2, (int) (0.002 * boardStyle.placement().width + 0.5));
final Color shade0 = new Color(210, 240, 255);
final Color shade1 = new Color(190, 220, 255); // Global.shade(shade0, 0.9);
final Color shadeEdge = MathRoutines.shade(shade0, 0.25);
setStrokesAndColours
(
bridge,
context,
null,
null,
shade0, // new Color(250, 221, 144),
shade1, // new Color(200, 150, 75),
null,
null,
null,
null,
shadeEdge, // new Color(153, 51, 0),
swThin,
swThick
);
fillCells(bridge, g2d, context);
drawSnakesAndLadders(g2d, context.game());
drawOuterCellEdges(bridge, g2d, context);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
/**
* Draws the snakes and ladders graphics on the board.
*/
private void drawSnakesAndLadders(final Graphics2D g2d, final Game game)
{
// Draw snakes
for (final Map map : game.equipment().maps())
for (int n = 0; n < map.map().size(); n++) {
final int from = map.map().keys()[n];
final int to = map.map().values()[n];
if (from > to)
drawSnake(g2d, from, to);
}
// Draw ladders
for (final Map map : game.equipment().maps())
for (int n = 0; n < map.map().size(); n++) {
final int from = map.map().keys()[n];
final int to = map.map().values()[n];
if (from < to)
drawLadder(g2d, from, to);
}
}
//-------------------------------------------------------------------------
/**
* Draws the snakes on the board.
*/
private void drawLadder(final Graphics2D g2d, final int from, final int to)
{
final List<Cell> cells = topology().cells();
// Amount to clip ladder ends
final double clip = 0.5 * boardStyle.cellRadius() * boardStyle.placement().width;
final Cell cellA = cells.get(from);
final Cell cellB = cells.get(to);
final Point pixelA = screenPosn(cellA.centroid());
final Point pixelB = screenPosn(cellB.centroid());
final double angle = Math.atan2(pixelB.y - pixelA.y, pixelB.x - pixelA.x);
final Point2D.Double ptA = new Point2D.Double(pixelA.x + clip * Math.cos(angle), pixelA.y + clip * Math.sin(angle));
final Point2D.Double ptB = new Point2D.Double(pixelB.x + clip * Math.cos(angle + Math.PI), pixelB.y + clip * Math.sin(angle + Math.PI));
// Spacing between rails
final double width = 0.3 * boardStyle.cellRadius() * boardStyle.placement().width;
final double l0x = ptA.x + width * Math.cos(angle + Math.PI / 2);
final double l0y = ptA.y + width * Math.sin(angle + Math.PI / 2);
final double l1x = ptB.x + width * Math.cos(angle + Math.PI / 2);
final double l1y = ptB.y + width * Math.sin(angle + Math.PI / 2);
final double r0x = ptA.x + width * Math.cos(angle - Math.PI / 2);
final double r0y = ptA.y + width * Math.sin(angle - Math.PI / 2);
final double r1x = ptB.x + width * Math.cos(angle - Math.PI / 2);
final double r1y = ptB.y + width * Math.sin(angle - Math.PI / 2);
// Draw rungs
final double length = MathRoutines.distance(ptA, ptB);
final int numRungs = (int) (0.75 * length / width);
final BasicStroke stroke = new BasicStroke((float) (0.125 * boardStyle.cellRadius() * boardStyle.placement().width),
BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
g2d.setStroke(stroke);
g2d.setColor(new Color(255, 127, 0));
for (int r = 1; r < numRungs - 1; r++) {
final double t = r / (double) (numRungs - 1);
final double rungLx = l0x + t * (l1x - l0x);
final double rungLy = l0y + t * (l1y - l0y);
final double rungRx = r0x + t * (r1x - r0x);
final double rungRy = r0y + t * (r1y - r0y);
final java.awt.Shape rung = new Line2D.Double(rungLx, rungLy, rungRx, rungRy);
g2d.draw(rung);
}
// Draw rails
final java.awt.Shape left = new Line2D.Double(l0x, l0y, l1x, l1y);
final java.awt.Shape right = new Line2D.Double(r0x, r0y, r1x, r1y);
g2d.draw(left);
g2d.draw(right);
}
//-------------------------------------------------------------------------
/**
* Draws the snakes on the board.
*/
private void drawSnake(final Graphics2D g2d, final int from, final int to)
{
final List<Cell> cells = topology().cells();
// Amount to clip
final double u = boardStyle.cellRadius() * boardStyle.placement().width;
final double clipTail = 0.5 * u;
final double clipHead = 0.75 * u;
final Cell cellA = cells.get(from);
final Cell cellB = cells.get(to);
final Point pixelA = screenPosn(cellA.centroid());
final Point pixelB = screenPosn(cellB.centroid());
final double angle = Math.atan2(pixelB.y - pixelA.y, pixelB.x - pixelA.x);
final Point2D.Double ptA = new Point2D.Double(pixelA.x + clipTail * Math.cos(angle),
pixelA.y + clipTail * Math.sin(angle));
final Point2D.Double ptB = new Point2D.Double(pixelB.x + clipHead * Math.cos(angle + Math.PI),
pixelB.y + clipHead * Math.sin(angle + Math.PI));
// Undulations
final double offI = 0.2 * u;
final double offO = 0.6 * u;
final double length = MathRoutines.distance(ptA, ptB);
final int numBends = 4 + (int) (0.5 * length / u);
final Point2D.Double[][] cps = new Point2D.Double[numBends + 1][2];
cps[0][0] = ptA;
cps[0][1] = ptA;
cps[numBends - 1][0] = ptB;
cps[numBends - 1][1] = ptB;
for (int b = 1; b < numBends - 1; b++) {
final double t = b / (double) (numBends - 1);
final double tx = ptA.x + t * (ptB.x - ptA.x);
final double ty = ptA.y + t * (ptB.y - ptA.y);
if (b % 2 == 0) {
cps[b][0] = new Point2D.Double(tx + offI * Math.cos(angle + Math.PI / 2),
ty + offI * Math.sin(angle + Math.PI / 2));
cps[b][1] = new Point2D.Double(tx + offO * Math.cos(angle + Math.PI / 2),
ty + offO * Math.sin(angle + Math.PI / 2));
} else {
cps[b][1] = new Point2D.Double(tx + offI * Math.cos(angle - Math.PI / 2),
ty + offI * Math.sin(angle - Math.PI / 2));
cps[b][0] = new Point2D.Double(tx + offO * Math.cos(angle - Math.PI / 2),
ty + offO * Math.sin(angle - Math.PI / 2));
}
}
// Draw snake
final GeneralPath path = new GeneralPath();
path.moveTo(ptA.x, ptA.y);
final double off = 0.6;
for (int b = 0; b < numBends - 2; b++) {
final double b0x = cps[b][0].x;
final double b0y = cps[b][0].y;
final double b1x = cps[b + 1][0].x;
final double b1y = cps[b + 1][0].y;
final double b2x = cps[b + 2][0].x;
final double b2y = cps[b + 2][0].y;
final double ax = (b0x + b1x) / 2.0;
final double ay = (b0y + b1y) / 2.0;
final double dx = (b1x + b2x) / 2.0;
final double dy = (b1y + b2y) / 2.0;
final double bx = ax + off * (b1x - ax);
final double by = ay + off * (b1y - ay);
final double cx = dx + off * (b1x - dx);
final double cy = dy + off * (b1y - dy);
path.curveTo(bx, by, cx, cy, dx, dy);
}
path.lineTo(ptB.x, ptB.y);
for (int b = numBends - 3; b >= 0; b--) {
final double b0x = cps[b + 2][1].x;
final double b0y = cps[b + 2][1].y;
final double b1x = cps[b + 1][1].x;
final double b1y = cps[b + 1][1].y;
final double b2x = cps[b + 0][1].x;
final double b2y = cps[b + 0][1].y;
final double ax = (b0x + b1x) / 2.0;
final double ay = (b0y + b1y) / 2.0;
final double dx = (b1x + b2x) / 2.0;
final double dy = (b1y + b2y) / 2.0;
final double bx = ax + off * (b1x - ax);
final double by = ay + off * (b1y - ay);
final double cx = dx + off * (b1x - dx);
final double cy = dy + off * (b1y - dy);
path.curveTo(bx, by, cx, cy, dx, dy);
}
path.closePath();
g2d.setColor(new Color(0, 127, 0));
g2d.fill(path);
final BasicStroke stroke = new BasicStroke(0.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
g2d.setStroke(stroke);
g2d.setColor(new Color(0, 0, 0));
g2d.draw(path);
}
//-------------------------------------------------------------------------
@Override
protected void fillCells(final Bridge bridge, final Graphics2D g2d, final Context context)
{
final List<Cell> cells = topology().cells();
final int fontSize = (int) (0.85 * boardStyle.cellRadius() * boardStyle.placement().width + 0.5);
final Font font = new Font("Arial", Font.PLAIN, fontSize);
g2d.setFont(font);
g2d.setStroke(strokeThin);
for (final Cell cell : cells) {
final GeneralPath path = new GeneralPath();
for (int v = 0; v < cell.vertices().size(); v++) {
if (path.getCurrentPoint() == null) {
final Vertex prev = cell.vertices().get(cell.vertices().size() - 1);
final Point prevPosn = screenPosn(prev.centroid());
path.moveTo(prevPosn.x, prevPosn.y);
}
final Vertex corner = cell.vertices().get(v);
final Point cornerPosn = screenPosn(corner.centroid());
path.lineTo(cornerPosn.x, cornerPosn.y);
}
if ((cell.col() + cell.row()) % 2 == 0)
g2d.setColor(colorFillPhase1);
else
g2d.setColor(colorFillPhase0);
g2d.fill(path);
}
// Draw cell coordinates
g2d.setColor(Color.white);
for (final Cell cell : cells)
{
final String cellNumber = (cell.row() % 2 == 0)
? "" + (cell.index() + 1)
: "" + (cell.row() * 10 + 10 - cell.col());
final Rectangle bounds = g2d.getFontMetrics().getStringBounds(cellNumber, g2d).getBounds();
//final Point2D.Double pt = cell.centroid();
final Point pt = screenPosn(cell.centroid());
g2d.drawString
(
cellNumber,
pt.x - (int)(0.5 * bounds.getWidth()),
pt.y + (int)(0.3 * bounds.getHeight())
);
}
}
//-------------------------------------------------------------------------
}
| 10,760 | 30.373178 | 138 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/SpiralDesign.java
|
package view.container.aspects.designs.board;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import main.math.MathRoutines;
import main.math.Vector;
import other.context.Context;
import other.topology.Vertex;
import view.container.aspects.designs.BoardDesign;
import view.container.styles.BoardStyle;
/**
* Graphics for the spiral board (e.g. Mehen).
*
* @author cambolbro
*/
public class SpiralDesign extends BoardDesign
{
private int numSites = 1;
private int numTurns = 1;
/** The angles for calculating vertex positions. */
private double[] thetas;
//-------------------------------------------------------------------------
public SpiralDesign(final BoardStyle boardStyle)
{
super(boardStyle, null);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 5 / 1000.0f;
final float swThin = Math.max(1, (int) (swRatio * boardStyle.placement().width + 0.5));
final float swThick = 1 * swThin;
setStrokesAndColours
(
bridge,
context,
new Color(0,0,0),
new Color(150, 75, 0), // border
new Color(200, 150, 75), // dark cells
new Color(250, 221, 144), // light cells
new Color(223, 178, 110), // middle cells,
null,
null,
null,
null,
swThin,
swThick
);
// Number of turns is first dimension of Spiral shape
numTurns = context.board().graph().dim()[0];
numSites = topology().vertices().size();
setThetas();
drawSpiralBoard(g2d);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
void setThetas()
{
// Twice the number of vertices per ring, offset between rings
final int base = baseNumber();
thetas = new double[2 * numSites];
int index = 1;
int steps = base; // number of steps per ring
for (int ring = 1; ring <= numTurns + 1; ring++)
{
final double dTheta = Math.PI * 2 / steps;
double theta = Math.PI * 2 * ring;
if (ring <= 2 || ring % 2 == 1)
theta -= dTheta / 2; // offset so that lines don't coincide between rings
for (int step = 0; step < steps; step++)
{
thetas[index++] = theta;
theta += dTheta;
}
if (ring <= 2)
steps *= 2;
}
// Smoothing passes to reduce unevenness between steps
for (int vid = 2; vid < numSites; vid++)
thetas[vid] = (thetas[vid-1] + thetas[vid+1]) / 2.0;
for (int vid = 2; vid < numSites; vid++)
thetas[vid] = (thetas[vid-1] + thetas[vid+1]) / 2.0;
thetas[1] -= 0.5 * (thetas[2] - thetas[1]); // fudge to nudge vertex 1 into place
}
//-------------------------------------------------------------------------
/**
* @return Number of cells in the inner ring, doubling with each layer.
*/
private int baseNumber()
{
for (int base = 1; base < numSites; base++)
{
// Try this base
int steps = base;
int total = 1;
for (int ring = 1; ring < numTurns; ring++)
{
total += steps;
if (total > numSites)
{
if (ring <= numTurns)
return base - 1;
break;
}
if (ring <= 2)
steps *= 2;
}
}
System.out.println("** Error: Couldn't find base number for spiral.");
return 0;
}
//-------------------------------------------------------------------------
void drawSpiralBoard(final Graphics2D g2d)
{
final int rd = 2;
g2d.setColor(new Color(0, 127, 255));
for (final Vertex vertex : topology().vertices())
{
final Point pt = boardStyle.screenPosn(vertex.centroid());
g2d.fillOval(pt.x-rd, pt.y-rd, 2*rd, 2*rd);
}
final double a = 0.05;
final double b = 1.0 / (2.0 * numTurns * numTurns) * 0.8;
final double end = //(numTurns + 0.325) * 2 * Math.PI;
(thetas[thetas.length / 2 - 1] + thetas[thetas.length / 2]) / 2;
final double nudge = 0.005;
final double x0 = topology().vertices().get(0).centroid().getX();
final double y0 = topology().vertices().get(0).centroid().getY();
final List<Point> pts = new ArrayList<Point>();
for (double theta = -0.05; theta < end + 1; theta += 0.2)
{
final double clipTheta = (theta > end ? end : theta) - nudge;
final double r = a + b * clipTheta;
final double x = x0 - r * Math.cos(clipTheta);
final double y = y0 + r * Math.sin(clipTheta);
final Point2D.Double xy = new Point2D.Double(x, y);
final Point pt = boardStyle.screenPosn(xy);
pts.add(pt);
if (theta > end)
{
// Store one last sample at end point
final double r2 = a + b * theta;
final double x2 = x0 - r2 * Math.cos(theta);
final double y2 = y0 + r2 * Math.sin(theta);
final Point2D.Double xy2 = new Point2D.Double(x2, y2);
final Point pt2 = boardStyle.screenPosn(xy2);
pts.add(pt2);
// Store final point to close on
final double r3 = a - 0.1 + b * (end + nudge);
final double x3 = x0 - r3 * Math.cos(end + nudge);
final double y3 = y0 + r3 * Math.sin(end + nudge);
final Point2D.Double xy3 = new Point2D.Double(x3, y3);
final Point pt3 = boardStyle.screenPosn(xy3);
pts.add(pt3);
break;
}
}
// Draw smooth spline
GeneralPath path = new GeneralPath();
for (int n = 0; n < pts.size()-3; n++)
{
final Point pt = pts.get(n);
if (n == 0)
{
path.moveTo(pt.x, pt.y);
}
else
{
final Point ptA = pts.get(n-1);
final Point ptB = pts.get(n);
final Point ptC = pts.get(n+1);
final Point ptD = pts.get(n+2);
final Vector vecAC = new Vector(ptC.x-ptA.x, ptC.y-ptA.y);
vecAC.normalise();
final Vector vecDB = new Vector(ptB.x-ptD.x, ptB.y-ptD.y);
vecDB.normalise();
final double distBC = MathRoutines.distance(ptB, ptC);
final double off = 0.3 * distBC;
final double bx = ptB.x + vecAC.x() * off;
final double by = ptB.y + vecAC.y() * off;
final double cx = ptC.x + vecDB.x() * off;
final double cy = ptC.y + vecDB.y() * off;
final double dx = ptC.x;
final double dy = ptC.y;
path.curveTo(bx, by, cx, cy, dx, dy);
}
}
// Final closing point to draw straight edge
final Point ptN = pts.get(pts.size() - 1);
path.lineTo(ptN.x, ptN.y);
g2d.setColor(new Color(255, 240, 220));
g2d.fill(path);
g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
g2d.setColor(new Color(220, 180, 120));
g2d.draw(path);
// Draw the central cell
final Point ptC1 = boardStyle.screenPosn(topology().vertices().get(1).centroid());
final Point ptC2 = boardStyle.screenPosn(topology().vertices().get(2).centroid());
final double u = MathRoutines.distance(ptC1.x, ptC1.y, ptC2.x, ptC2.y);
path = new GeneralPath();
final Point ptA = pts.get(0);
final Point ptB = pts.get(22);
path.moveTo(ptA.x, ptA.y);
path.curveTo(ptA.x+(int)(.25 * u), ptA.y+(int)(.5 * u), ptB.x+(int)(0 * u), ptB.y-(int)(.5 * u), ptB.x, ptB.y);
g2d.draw(path);
// Draw the septum divisions
for (int vid = 1; vid < thetas.length / 2; vid++)
{
final double theta = (thetas[vid] + thetas[vid+1]) / 2;
final double r1 = a - 0.1 + b * (theta + nudge);
final double x1 = (x0 - r1 * Math.cos(theta + nudge));
final double y1 = y0 + r1 * Math.sin(theta + nudge);
final Point2D.Double xy1 = new Point2D.Double(x1, y1);
final Point pt1 = boardStyle.screenPosn(xy1);
final double r2 = a + b * (theta - nudge);
final double x2 = (x0 - r2 * Math.cos(theta - nudge));
final double y2 = y0 + r2 * Math.sin(theta - nudge);
final Point2D.Double xy2 = new Point2D.Double(x2, y2);
final Point pt2 = boardStyle.screenPosn(xy2);
g2d.drawLine(pt1.x, pt1.y, pt2.x, pt2.y);
}
}
//-------------------------------------------------------------------------
/**
* @return Point projected inwards to the ring that the specified vertex angle would lie on.
*/
@SuppressWarnings("static-method")
Point2D.Double ptOnRing
(
final double x0, final double y0, final double a, final double b,
final double theta, final double scale
)
{
final double thetaPrev = theta - 2 * Math.PI;
final double r = a + b * theta;
final double rPrev = a + b * thetaPrev;
final Point2D.Double pt = new Point2D.Double
(
x0 + r * Math.cos(theta),
y0 - r * Math.sin(theta)
);
final Point2D.Double ptP = new Point2D.Double
(
x0 + rPrev * Math.cos(thetaPrev),
y0 - rPrev * Math.sin(thetaPrev)
);
return new Point2D.Double((pt.x + ptP.x)/2.0*scale, (pt.y + ptP.y)/2.0*scale);
}
//-------------------------------------------------------------------------
}
| 9,013 | 26.735385 | 113 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/SurakartaDesign.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.GeneralPath;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.equipment.container.board.Track;
import game.equipment.container.board.Track.Elem;
import game.types.board.SiteType;
import main.math.MathRoutines;
import other.context.Context;
import other.topology.Edge;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
/**
* Custom board rendering for Surakarta-type boards.
*
* @author cambolbro and matthew.stephenson
*/
public class SurakartaDesign extends BoardDesign
{
public SurakartaDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
/** The colour of the board loops. */
private final Color[] loopColours =
{
new Color( 0, 175, 0),
new Color(230, 50, 20),
new Color( 0, 100, 200),
new Color(150, 150, 0),
new Color(150, 0, 150),
new Color( 0, 150, 150)
};
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swThin = (float)Math.max(1, 0.005 * boardStyle.placement().width + 0.5);
final float swThick = 2 * swThin;
setStrokesAndColours
(
bridge,
context,
new Color(50, 150, 255),
null,
new Color(180, 230, 255),
new Color(0, 175, 0),
new Color(230, 50, 20),
new Color(0, 100, 200),
null,
null,
null,
swThin,
swThick
);
drawBoard(g2d);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
/**
* Draws the board design.
*/
protected void drawBoard(final Graphics2D g2d)
{
switch (topology().graph().basis())
{
case Square: drawBoardSquare(g2d); break;
case Triangular: drawBoardTriangular(g2d); break;
//$CASES-OMITTED$
default: System.out.println("** Board type " + topology().graph().basis() + " not supported for Surkarta.");
}
}
//-------------------------------------------------------------------------
/**
* Draws the board design if square basis.
*/
protected void drawBoardSquare(final Graphics2D g2d)
{
final int rows = boardStyle.container().topology().rows(SiteType.Vertex).size();
final int cols = boardStyle.container().topology().columns(SiteType.Vertex).size();
// Get four corner points
final Point ptSW = screenPosn(topology().vertices().get(0).centroid());
final Point ptNW = screenPosn(topology().vertices().get(rows * cols - cols).centroid());
final Point ptNE = screenPosn(topology().vertices().get(rows * cols - 1).centroid());
final Point ptSE = screenPosn(topology().vertices().get(cols - 1).centroid());
// Fill the board area
g2d.setColor(colorFillPhase0);
final GeneralPath border = new GeneralPath();
border.moveTo(ptSW.x, ptSW.y);
border.lineTo(ptNW.x, ptNW.y);
border.lineTo(ptNE.x, ptNE.y);
border.lineTo(ptSE.x, ptSE.y);
border.closePath();
g2d.fill(border);
// for (final Cell cell : topology().cells())
// {
// final GeneralPath path = new GeneralPath();
// for (int n = 0; n < cell.vertices().size(); n++)
// {
// final Point2D pt = cell.vertices().get(n).centroid();
// if (n == 0)
// path.moveTo(pt.getX(),pt.getY());
// else
// path.lineTo(pt.getX(),pt.getY());
// }
// g2d.fill(path);
// }
// Draw the grid lines
g2d.setStroke(strokeThin);
g2d.setColor(colorEdgesInner);
// for (int row = 0; row < rows; row++)
// {
// final Point ptA = screenPosn(topology().vertices().get(row * cols).centroid());
// final Point ptB = screenPosn(topology().vertices().get(row * cols + cols - 1).centroid());
// g2d.drawLine(ptA.x, ptA.y, ptB.x, ptB.y);
// }
//
// for (int col = 0; col < cols; col++)
// {
// final Point ptA = screenPosn(topology().vertices().get(col).centroid());
// final Point ptB = screenPosn(topology().vertices().get(rows * cols - cols + col).centroid());
// g2d.drawLine(ptA.x, ptA.y, ptB.x, ptB.y);
// }
for (final Edge edge : topology().edges())
{
final Point ptA = screenPosn(edge.vA().centroid());
final Point ptB = screenPosn(edge.vB().centroid());
g2d.drawLine(ptA.x, ptA.y, ptB.x, ptB.y);
}
g2d.draw(border);
// Draw the tracks
g2d.setStroke(strokeThick());
for (int t = 0; t < boardStyle.container().tracks().size(); t += 2)
{
g2d.setColor(loopColours[(t / 2) % boardStyle.container().tracks().size() % loopColours.length]);
final Track track = boardStyle.container().tracks().get(t);
for (int e = 0; e < track.elems().length; e++)
{
final Elem elemM = track.elems()[e];
final Elem elemN = track.elems()[(e + 1) % track.elems().length];
final Point ptM = screenPosn(topology().vertices().get(elemM.site).centroid());
final Point ptN = screenPosn(topology().vertices().get(elemN.site).centroid());
if (elemM.bump > 0)
{
// Previous pair is speed bump: draw loop
final int rowM = elemM.site / cols;
final int colM = elemM.site % cols;
final int rowN = elemN.site / cols;
final int colN = elemN.site % cols;
if ((rowM == 0 || rowN == 0) && (colM == 0 || colN == 0))
{
// SW corner
final int r = (int)(MathRoutines.distance(ptM, ptSW) + 0.5);
g2d.drawArc(ptSW.x-r, ptSW.y-r, 2*r, 2*r, 90, 270);
}
else if ((rowM == rows - 1 || rowN == rows - 1) && (colM == 0 || colN == 0))
{
// NW corner
final int r = (int)(MathRoutines.distance(ptM, ptNW) + 0.5);
g2d.drawArc(ptNW.x-r, ptNW.y-r, 2*r, 2*r, 0, 270);
}
else if ((rowM == rows - 1 || rowN == rows - 1) && (colM == cols - 1 || colN == cols - 1))
{
// NE corner
final int r = (int)(MathRoutines.distance(ptM, ptNE) + 0.5);
g2d.drawArc(ptNE.x-r, ptNE.y-r, 2*r, 2*r, 270, 270);
}
else if ((rowM == 0 || rowN == 0) && (colM == cols - 1 || colN == cols - 1))
{
// SE corner
final int r = (int)(MathRoutines.distance(ptM, ptSE) + 0.5);
g2d.drawArc(ptSE.x-r, ptSE.y-r, 2*r, 2*r, 180, 270);
}
}
else
{
// Draw line
g2d.drawLine(ptM.x, ptM.y, ptN.x, ptN.y);
}
}
}
}
//-------------------------------------------------------------------------
/**
* Draws the board design if triangular basis.
*/
protected void drawBoardTriangular(final Graphics2D g2d)
{
final int rows = boardStyle.container().topology().rows(SiteType.Vertex).size();
//final int cols = boardStyle.container().topology().columns(SiteType.Vertex).size();
//System.out.println("rows=" + rows + ", cols=" + cols);
// Get four corner points
final Point ptSW = screenPosn(topology().vertices().get(0).centroid());
final Point ptTop = screenPosn(topology().vertices().get(topology().vertices().size() - 1).centroid());
final Point ptSE = screenPosn(topology().vertices().get(rows - 1).centroid());
// Fill the board area
g2d.setColor(colorFillPhase0);
final GeneralPath border = new GeneralPath();
border.moveTo( ptSW.x, ptSW.y);
border.lineTo(ptTop.x, ptTop.y);
border.lineTo( ptSE.x, ptSE.y);
border.closePath();
g2d.fill(border);
// for (final Cell cell : topology().cells())
// {
// final GeneralPath path = new GeneralPath();
// for (int n = 0; n < cell.vertices().size(); n++)
// {
// final Point2D pt = cell.vertices().get(n).centroid();
// if (n == 0)
// path.moveTo(pt.getX(),pt.getY());
// else
// path.lineTo(pt.getX(),pt.getY());
// }
// g2d.fill(path);
// }
// Draw the grid lines
g2d.setStroke(strokeThin);
g2d.setColor(colorEdgesInner);
for (final Edge edge : topology().edges())
{
final Point ptA = screenPosn(edge.vA().centroid());
final Point ptB = screenPosn(edge.vB().centroid());
g2d.drawLine(ptA.x, ptA.y, ptB.x, ptB.y);
}
g2d.draw(border);
// Draw the tracks
g2d.setStroke(strokeThick());
for (int t = 0; t < boardStyle.container().tracks().size(); t += 2)
{
g2d.setColor(loopColours[(t / 2) % boardStyle.container().tracks().size() % loopColours.length]);
final Track track = boardStyle.container().tracks().get(t);
for (int e = 0; e < track.elems().length; e++)
{
final Elem elemM = track.elems()[e];
final Elem elemN = track.elems()[(e + 1) % track.elems().length];
final Point ptM = screenPosn(topology().vertices().get(elemM.site).centroid());
final Point ptN = screenPosn(topology().vertices().get(elemN.site).centroid());
if (elemM.bump > 0)
{
final int diff = elemN.site - elemM.site;
if (diff > 0 && diff <= rows / 2)
{
// Top corner loop
final Point ptRef = ptTop;
final int r = (int)(MathRoutines.distance(ptM, ptRef) * Math.sqrt(3) / 2 + 0.5);
final int ax = ptRef.x + (int)(r * Math.cos(Math.toRadians(210)) - 0.5);
final int ay = ptRef.y - (int)(r * Math.sin(Math.toRadians(210)) + 0.5);
g2d.drawLine(ptM.x, ptM.y, ax, ay);
g2d.drawArc(ptRef.x-r, ptRef.y-r, 2 * r, 2 * r, 330, 240);
final int r2 = (int)(MathRoutines.distance(ptM, ptRef) + 0.5);
final int bx = ptRef.x + (int)(r * Math.cos(Math.toRadians(330)) + 0.5);
final int by = ptRef.y - (int)(r * Math.sin(Math.toRadians(330)) + 0.5);
final int cx = ptRef.x + (int)(r2 * Math.cos(Math.toRadians(300)) + 0.5);
final int cy = ptRef.y - (int)(r2 * Math.sin(Math.toRadians(300)) + 0.5);
g2d.drawLine(bx, by, cx, cy);
}
else if (diff >= rows / 2)
{
// Bottom left corner loop
final Point ptRef = ptSW;
final int r = (int)(MathRoutines.distance(ptM, ptRef) * Math.sqrt(3) / 2 + 0.5);
final int ax = ptRef.x + (int)(r * Math.cos(Math.toRadians(330)) + 0.5);
final int ay = ptRef.y - (int)(r * Math.sin(Math.toRadians(330)) - 0.5);
g2d.drawLine(ptM.x, ptM.y, ax, ay);
g2d.drawArc(ptRef.x-r, ptRef.y-r, 2 * r, 2 * r, 90, 240);
final int r2 = (int)(MathRoutines.distance(ptM, ptRef) + 0.5);
final int bx = ptRef.x + (int)(r * Math.cos(Math.toRadians(90)) + 0.5);
final int by = ptRef.y - (int)(r * Math.sin(Math.toRadians(90)) + 0.5);
final int cx = ptRef.x + (int)(r2 * Math.cos(Math.toRadians(60)) + 0.5);
final int cy = ptRef.y - (int)(r2 * Math.sin(Math.toRadians(60)) + 0.5);
g2d.drawLine(bx, by, cx, cy);
}
else if (diff < -rows / 2)
{
// Bottom right corner loop
final Point ptRef = ptSE;
final int r = (int)(MathRoutines.distance(ptM, ptRef) * Math.sqrt(3) / 2 + 0.5);
final int ax = ptRef.x + (int)(r * Math.cos(Math.toRadians(90)) + 0.5);
final int ay = ptRef.y - (int)(r * Math.sin(Math.toRadians(90)) + 0.5);
g2d.drawLine(ptM.x, ptM.y, ax, ay);
g2d.drawArc(ptRef.x-r, ptRef.y-r, 2 * r, 2 * r, 210, 240);
final int r2 = (int)(MathRoutines.distance(ptM, ptRef) + 0.5);
final int bx = ptRef.x + (int)(r * Math.cos(Math.toRadians(210)) + 0.5);
final int by = ptRef.y - (int)(r * Math.sin(Math.toRadians(210)) + 0.5);
final int cx = ptRef.x + (int)(r2 * Math.cos(Math.toRadians(180)) + 0.5);
final int cy = ptRef.y - (int)(r2 * Math.sin(Math.toRadians(180)) + 0.5);
g2d.drawLine(bx, by, cx, cy);
}
}
else
{
// Draw line
g2d.drawLine(ptM.x, ptM.y, ptN.x, ptN.y);
}
}
}
}
//-------------------------------------------------------------------------
}
| 11,940 | 31.185984 | 110 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/TableDesign.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Ellipse2D;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import other.context.Context;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.Board.TablePlacement;
import view.container.styles.board.TableStyle;
/**
* Design for Table board.
*
* @author Eric.Piette
*/
public class TableDesign extends BoardDesign
{
/** The style of the the table board. */
private final TableStyle tableStyle;
/** The placement in a table board. */
private final TablePlacement tablePlacement;
//-------------------------------------------------------------------------
public TableDesign(final TableStyle boardStyle, final TablePlacement boardPlacement)
{
super(boardStyle, boardPlacement);
tableStyle = boardStyle;
tablePlacement = boardPlacement;
}
//-------------------------------------------------------------------------
private final Color[] boardColours =
{
new Color(153, 76, 0), // base
new Color(223, 178, 110), // frame
};
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
boardPlacement.customiseGraphElementLocations(context);
// Board image
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
setStrokesAndColours
(
bridge,
context,
new Color(120, 190, 240),
new Color(125, 75, 0),
new Color(210, 230, 255),
null,
null,
null,
null,
null,
new Color(0, 0, 0),
Math.max(1, (int) (0.0025 * boardStyle.placement().width + 0.5)),
(int) (2.0 * Math.max(1, (int) (0.0025 * boardStyle.placement().width + 0.5)))
);
drawTableBoard(g2d);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
/**
* Draws the board design.
*/
void drawTableBoard(final Graphics2D g2d)
{
final Point pt0 = screenPosn(topology().vertices().get(0).centroid());
final Point pt1 = screenPosn(topology().vertices().get(1).centroid());
final int off = pt1.x - pt0.x;
final int unit = off;
final Point ptBottomLeftRight = screenPosn(topology().vertices().get(tablePlacement.homeSize() - 1).centroid());
final Point ptBottomRightLeft = screenPosn(topology().vertices().get(tablePlacement.homeSize()).centroid());
final Point ptBottomRightRight = screenPosn(topology().vertices().get(tablePlacement.homeSize() * 2 - 1).centroid());
final Point ptTopLeftLeft = screenPosn(topology().vertices().get(tablePlacement.homeSize() * 2).centroid());
final Point ptTopRightLeft = screenPosn(topology().vertices().get(tablePlacement.homeSize() * 3).centroid());
final int pr = (int) (unit * 0.5); // half an unit.
final int borderX = (int) (unit * 0.2); // Size border.
final int borderY = unit * 0; // Size border.
final int diameterCircle = unit; // The diameter of the circle for the pieces.
final int gapYCircle = (int) (diameterCircle * 0.7); // Gap y vertex and centre circle.
final int topLeftLeftX = ptTopLeftLeft.x - pr;
final int topLeftLeftY = ptTopLeftLeft.y - pr;
final int topRightLeftX = ptTopRightLeft.x - pr;
final int topRightLeftY = ptTopRightLeft.y - pr;
final int bottomLeftRightX = ptBottomLeftRight.x + pr;
final int bottomLeftRightY = ptBottomLeftRight.y + pr;
final int bottomRightLeftX = ptBottomRightLeft.x + pr;
final int bottomRightRightX = ptBottomRightRight.x + pr;
final int bottomRightRightY = ptBottomRightRight.y + pr;
final int topLeftBorderX = topLeftLeftX - borderX;
final int topLeftBorderY = topLeftLeftY - borderY;
final int bottomRightBorderX = bottomRightRightX + borderX;
final int bottomRightBorderY = bottomRightRightY + borderY;
// Draw the base of the board (rectangle)
g2d.setColor(boardColours[1]);
g2d.fillRect(topLeftBorderX, topLeftBorderY, Math.abs(bottomRightBorderX - topLeftBorderX),
Math.abs(bottomRightBorderY - topLeftBorderY));
// Draw middle of each side without the space for the circles
g2d.setColor(boardColours[0]);
g2d.fillRect(topLeftLeftX, topLeftLeftY + gapYCircle, Math.abs(bottomLeftRightX - topLeftLeftX),
Math.abs((bottomLeftRightY - gapYCircle) - (topLeftLeftY + gapYCircle)));
g2d.fillRect(topRightLeftX, topRightLeftY + gapYCircle, Math.abs(bottomRightRightX - topRightLeftX),
Math.abs((bottomRightRightY - gapYCircle) - (topRightLeftY + gapYCircle)));
// Draw gap in the middle bar in the middle.
final int bottomMiddleY = bottomLeftRightY - (int) (Math.abs(topRightLeftY - bottomLeftRightY) * 0.65);
final int sizeXMiddle = Math.abs(bottomLeftRightX - bottomRightLeftX);
final int sizeYMiddle = (int) Math.abs(((bottomRightRightY - topLeftLeftY) * 0.35));
g2d.fillRect(bottomLeftRightX, bottomMiddleY,
sizeXMiddle, sizeYMiddle);
g2d.setColor(boardColours[1]);
final double offErrorMiddleCircle = 1.025;
final Ellipse2D.Double topMiddleCircle = new Ellipse2D.Double(bottomLeftRightX,
bottomLeftRightY - (int) (Math.abs(topRightLeftY - bottomLeftRightY) * 0.7),
diameterCircle * offErrorMiddleCircle, diameterCircle * offErrorMiddleCircle);
g2d.fill(topMiddleCircle);
final Ellipse2D.Double bottomMiddleCircle = new Ellipse2D.Double(bottomLeftRightX,
bottomLeftRightY - (int) (Math.abs(topRightLeftY - bottomLeftRightY) * 0.35),
diameterCircle * offErrorMiddleCircle, diameterCircle * offErrorMiddleCircle);
g2d.fill(bottomMiddleCircle);
// Draw the circles
g2d.setColor(boardColours[0]);
final double offErrorCircle = 0.99;
final int halfSize = topology().vertices().size() / 2;
for (int n = 0; n < halfSize; n++)
{
final Point ptVertex = screenPosn(topology().vertices().get(n).centroid());
final Ellipse2D.Double circle = new Ellipse2D.Double(ptVertex.x - pr, ptVertex.y - gapYCircle,
diameterCircle * offErrorCircle, diameterCircle * offErrorCircle);
g2d.fill(circle);
}
for (int n = halfSize; n < halfSize * 2; n++)
{
final Point ptVertex = screenPosn(topology().vertices().get(n).centroid());
final Ellipse2D.Double circle = new Ellipse2D.Double(ptVertex.x - pr, ptVertex.y - gapYCircle / 2,
diameterCircle * offErrorCircle, diameterCircle * offErrorCircle);
g2d.fill(circle);
}
}
public TableStyle getTableStyle()
{
return tableStyle;
}
}
| 6,456 | 35.6875 | 119 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/TaflDesign.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import java.util.ArrayList;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.types.board.SiteType;
import metadata.graphics.util.MetadataImageInfo;
import other.context.Context;
import other.topology.TopologyElement;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class TaflDesign extends BoardDesign
{
public TaflDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 3 / 1000.0f;
final float swThin = Math.max(1, (int) (swRatio * boardStyle.placement().width + 0.5));
final float swThick = 2 * swThin;
setStrokesAndColours
(
bridge,
context,
new Color(220, 170, 70),
new Color(175, 125, 75),
new Color(250, 200, 100),
null,
null,
null,
null,
null,
new Color(0, 0, 0),
swThin,
swThick
);
fillCells(bridge, g2d, context);
drawInnerCellEdges(g2d, context);
final ArrayList<Integer> symbolLocations = new ArrayList<>();
// Draw the centre
for (final TopologyElement v : topology().centre(SiteType.Cell))
symbolLocations.add(Integer.valueOf(v.index()));
for (final int i : symbolLocations)
{
// If the number of sides of the cell is divisible by 3, then use a triangle knot.
if (topology().cells().get(i).vertices().size() % 3 == 0)
symbols.add(new MetadataImageInfo(i,SiteType.Cell,"knotTriangle",(float)0.8));
// Otherwise use the square knot.
else
symbols.add(new MetadataImageInfo(i,SiteType.Cell,"knotSquare",(float)0.9));
}
drawSymbols(g2d, context);
drawOuterCellEdges(bridge, g2d, context);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
}
| 2,158 | 25.654321 | 90 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/UltimateTicTacToeDesign.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import other.context.Context;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class UltimateTicTacToeDesign extends BoardDesign
{
public UltimateTicTacToeDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swThin = (float)Math.max(1, 0.005 * boardStyle.placement().width + 0.5);
final float swThick = 2 * swThin;
setStrokesAndColours
(
bridge,
context,
new Color(50, 150, 255),
null,
new Color(180, 230, 255),
new Color(0, 175, 0),
new Color(230, 50, 20),
new Color(0, 100, 200),
null,
null,
null,
swThin,
swThick
);
drawBoard(g2d);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
/**
* Draws the board design.
*/
protected void drawBoard(final Graphics2D g2d)
{
final int dots = (int) (0.9 * boardStyle.container().topology().cells().size());
final int dim = (int)(Math.sqrt(dots));
final Point ptMid = screenPosn(topology().cells().get(dots / 2).centroid());
final Point pt0 = screenPosn(topology().cells().get(0).centroid());
final Point pt1 = screenPosn(topology().cells().get(1).centroid());
final int unit = Math.abs(pt1.x - pt0.x);
// Draw faint thin lines of subgames
g2d.setColor(new Color(200, 220, 255));
g2d.setStroke(strokeThin);
final int x0 = ptMid.x - 5 * unit + unit / 2;
final int y0 = ptMid.y - 5 * unit + unit / 2;
int ax, ay, bx, by;
final double off = 0.15;
for (int n = 1; n < dim; n++)
{
ax = x0 + unit * n;
ay = y0 + (unit * 0);
bx = ax;
by = y0 + (int)(unit * (3 - off));
g2d.drawLine(ax, ay, bx, by);
ax = x0 + unit * n;
ay = y0 + (int)(unit * (3 + off));
bx = ax;
by = y0 + (int)(unit * (6 - off));
g2d.drawLine(ax, ay, bx, by);
ax = x0 + unit * n;
ay = y0 + (int)(unit * (6 + off));
bx = ax;
by = y0 + (unit * dim);
g2d.drawLine(ax, ay, bx, by);
ax = x0 + (unit * 0);
ay = y0 + unit * n;
bx = x0 + (int)(unit * (3 - off));
by = ay;
g2d.drawLine(ax, ay, bx, by);
ax = x0 + (int)(unit * (3 + off));
ay = y0 + unit * n;
bx = x0 + (int)(unit * (6 - off));
by = ay;
g2d.drawLine(ax, ay, bx, by);
ax = x0 + (int)(unit * (6 + off));
ay = y0 + unit * n;
bx = x0 + (unit * dim);
by = ay;
g2d.drawLine(ax, ay, bx, by);
}
// // Block out thick white supergame lines to separate subgames a bit
// g2d.setColor(Color.white);
// g2d.setStroke(new BasicStroke(strokeThick.getLineWidth() * 3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
// //g2d.setStroke(strokeThick);
//
// for (int n = 3; n < dim; n+=3)
// {
// ax = x0 + n * unit;
// ay = y0 + 0 * unit;
// bx = x0 + n * unit;
// by = y0 + dim * unit;
// g2d.drawLine(ax, ay, bx, by);
//
// ax = x0 + 0 * unit;
// ay = y0 + n * unit;
// bx = x0 + dim * unit;
// by = y0 + n * unit;
// g2d.drawLine(ax, ay, bx, by);
// }
// Draw thick lines for supergame
g2d.setColor(new Color(20, 100, 200));
g2d.setStroke(strokeThick());
for (int n = 3; n < dim; n+=3)
{
ax = x0 + n * unit;
ay = y0 + 0 * unit;
bx = x0 + n * unit;
by = y0 + dim * unit;
g2d.drawLine(ax, ay, bx, by);
ax = x0 + 0 * unit;
ay = y0 + n * unit;
bx = x0 + dim * unit;
by = y0 + n * unit;
g2d.drawLine(ax, ay, bx, by);
}
}
//-------------------------------------------------------------------------
}
| 4,009 | 23.906832 | 113 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/XiangqiDesign.java
|
package view.container.aspects.designs.board;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.types.board.SiteType;
import graphics.svg.SVGtoImage;
import other.context.Context;
import other.topology.Vertex;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class XiangqiDesign extends BoardDesign
{
public XiangqiDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 5 / 1000.0f;
final float swThin = Math.max(1, (int) (swRatio * boardStyle.placement().width + 0.5));
final float swThick = swThin;
setStrokesAndColours
(
bridge,
context,
new Color(100, 75, 50),
new Color(100, 75, 50),
new Color(255, 230, 130),
null,
null,
null,
null,
null,
new Color(0, 0, 0),
swThin,
swThick
);
fillCells(bridge, g2d, context);
drawInnerCellEdges(g2d, context);
drawSymbols(g2d, context);
drawXiangqiSymbols(g2d);
drawOuterCellEdges(bridge, g2d, context);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
@Override
protected void drawInnerCellEdges(final Graphics2D g2d, final Context context)
{
// Draw cell edges (inner)
g2d.setStroke(strokeThin);
g2d.setColor(colorEdgesInner);
final GeneralPath path = new GeneralPath();
for (final Vertex vA : topology().vertices())
{
for (final Vertex vB : vA.orthogonal())
{
final Point2D va = vA.centroid();
final Point2D vb = vB.centroid();
// only draw inner edges if not overlapping the river
if ((va.getY() < 0.5 || vb.getY() > 0.5) && (va.getY() > 0.5 || vb.getY() < 0.5))
{
final Point vaWorld = boardStyle.screenPosn(vA.centroid());
final Point vbWorld = boardStyle.screenPosn(vB.centroid());
path.moveTo(vaWorld.x, vaWorld.y);
path.lineTo(vbWorld.x, vbWorld.y);
}
}
}
if (context.board().topology().vertices().size() == 90)
{
Point screenPosn = boardStyle.screenPosn(topology().vertices().get(3).centroid());
path.moveTo(screenPosn.x, screenPosn.y);
screenPosn = boardStyle.screenPosn(topology().vertices().get(23).centroid());
path.lineTo(screenPosn.x, screenPosn.y);
screenPosn = boardStyle.screenPosn(topology().vertices().get(5).centroid());
path.moveTo(screenPosn.x, screenPosn.y);
screenPosn = boardStyle.screenPosn(topology().vertices().get(21).centroid());
path.lineTo(screenPosn.x, screenPosn.y);
screenPosn = boardStyle.screenPosn(topology().vertices().get(86).centroid());
path.moveTo(screenPosn.x, screenPosn.y);
screenPosn = boardStyle.screenPosn(topology().vertices().get(66).centroid());
path.lineTo(screenPosn.x, screenPosn.y);
screenPosn = boardStyle.screenPosn(topology().vertices().get(84).centroid());
path.moveTo(screenPosn.x, screenPosn.y);
screenPosn = boardStyle.screenPosn(topology().vertices().get(68).centroid());
path.lineTo(screenPosn.x, screenPosn.y);
}
g2d.draw(path);
}
//-------------------------------------------------------------------------
/**
* Draws all Xianqgi symbols on the board.
*/
public void drawXiangqiSymbols(final Graphics2D g2d)
{
final int imgSz = boardPlacement.cellRadiusPixels() * 2;
// Load the decoration for special cells
final int boardVertexWidth = topology().columns(SiteType.Vertex).size();
final ArrayList<Integer> symbolLocations = new ArrayList<>();
symbolLocations.add(Integer.valueOf(boardVertexWidth * 2 + 1));
symbolLocations.add(Integer.valueOf(boardVertexWidth * 2 + 7));
symbolLocations.add(Integer.valueOf(boardVertexWidth * 3 + 2));
symbolLocations.add(Integer.valueOf(boardVertexWidth * 3 + 4));
symbolLocations.add(Integer.valueOf(boardVertexWidth * 3 + 6));
symbolLocations.add(Integer.valueOf(boardVertexWidth * 6 + 2));
symbolLocations.add(Integer.valueOf(boardVertexWidth * 6 + 4));
symbolLocations.add(Integer.valueOf(boardVertexWidth * 6 + 6));
symbolLocations.add(Integer.valueOf(boardVertexWidth * 7 + 1));
symbolLocations.add(Integer.valueOf(boardVertexWidth * 7 + 7));
final Color edgeColour = Color.black;
final Color fillColour = colorSymbol();
for (final Vertex v : boardStyle.topology().vertices())
{
final Point drawPosn = boardStyle.screenPosn(v.centroid());
if (v.index() == boardVertexWidth * 3 || v.index() == boardVertexWidth * 6)
SVGtoImage.loadFromFilePath
(
g2d, "/svg/xiangqi/symbol_left.svg", new Rectangle(
(int)(drawPosn.x - imgSz*0.125), (int)(drawPosn.y - imgSz*0.375), (int)(imgSz*0.75), (int)(imgSz*0.75)),
edgeColour, fillColour, 0
);
if (v.index() == boardVertexWidth * 3 + 8 || v.index() == boardVertexWidth * 6 + 8)
SVGtoImage.loadFromFilePath
(
g2d, "/svg/xiangqi/symbol_right.svg", new Rectangle(
(int)(drawPosn.x - imgSz*0.6), (int)(drawPosn.y - imgSz*0.375), (int)(imgSz*0.75), (int)(imgSz*0.75)),
edgeColour, fillColour, 0
);
if (symbolLocations.contains(Integer.valueOf(v.index())))
SVGtoImage.loadFromFilePath
(
g2d, "/svg/xiangqi/symbol.svg", new Rectangle(
(int)(drawPosn.x - imgSz*0.375), (int)(drawPosn.y - imgSz*0.375), (int)(imgSz*0.75), (int)(imgSz*0.75)),
edgeColour, fillColour, 0
);
}
}
//-------------------------------------------------------------------------
}
| 5,922 | 32.089385 | 110 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/graph/GraphDesign.java
|
package view.container.aspects.designs.board.graph;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.types.board.RelationType;
import metadata.graphics.util.BoardGraphicsType;
import metadata.graphics.util.EdgeInfoGUI;
import metadata.graphics.util.EdgeType;
import metadata.graphics.util.LineStyle;
import other.context.Context;
import other.topology.Edge;
import util.StrokeUtil;
import view.container.aspects.designs.board.puzzle.PuzzleDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
import view.container.styles.board.graph.GraphStyle;
public class GraphDesign extends PuzzleDesign
{
protected boolean drawOrthogonalEdges;
protected boolean drawDiagonalEdges;
protected boolean drawOffEdges = false;
protected boolean drawOrthogonalConnections = false;
protected boolean drawDiagonalConnections = false;
protected boolean drawOffConnections = false;
//-------------------------------------------------------------------------
public GraphDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement, final boolean drawOrthogonals, final boolean drawDiagonals)
{
super(boardStyle, boardPlacement);
drawOrthogonalEdges = drawOrthogonals;
drawDiagonalEdges = drawDiagonals;
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
// Set vertex radius
double vr = 0.3 * cellRadiusPixels();
if (vr < 4)
vr = 4;
if (vr > 8)
vr = 8;
((GraphStyle)boardStyle).setBaseVertexRadius(vr * context.game().metadata().graphics().boardThickness(BoardGraphicsType.InnerVertices));
((GraphStyle)boardStyle).setBaseLineWidth(0.666 * vr);
final float swThin = (float)((GraphStyle)boardStyle).baseLineWidth(); //Math.max(1, (int)(cellRadiusPixels() * 0.075));
final float swThick = swThin;
straightLines = context.game().metadata().graphics().straightRingLines();
final Color decorationColour = new Color(200, 200, 200);
setStrokesAndColours
(
bridge,
context,
((GraphStyle)boardStyle).baseGraphColour(),
((GraphStyle)boardStyle).baseGraphColour(),
null,
null,
null,
null,
null,
null,
decorationColour,
swThin,
swThick
);
drawGround(g2d, context, true);
//detectHints(context);
// Sunken design
if (!context.game().metadata().graphics().noSunken())
{
final double offY = -1.5;
//final Color sunkenColour = Color.BLACK;
final Color sunkenColour = new Color(100, 100, 100);
// only draw sunken on parts of graph that are visible.
if (colorEdgesInner == null || colorEdgesInner.getAlpha() != 0)
{
drawEdge(g2d, context, sunkenColour, strokeThin, EdgeType.Inner, RelationType.Orthogonal, false, drawOrthogonalEdges, offY);
}
if (colorEdgesOuter == null || colorEdgesOuter.getAlpha() != 0)
{
drawEdge(g2d, context, sunkenColour, strokeThick(), EdgeType.Outer, RelationType.Orthogonal, false, drawOrthogonalEdges, offY);
}
if (colorEdgesInner == null || colorEdgesInner.getAlpha() != 0)
{
drawEdge(g2d, context, sunkenColour, StrokeUtil.getDottedStroke(strokeThin.getLineWidth()), EdgeType.All, RelationType.Diagonal, false, drawDiagonalEdges, offY);
drawEdge(g2d, context, sunkenColour, strokeThin, EdgeType.Inner, RelationType.Orthogonal, true, drawOrthogonalConnections, offY);
drawEdge(g2d, context, sunkenColour, StrokeUtil.getDottedStroke(strokeThin.getLineWidth()), EdgeType.All, RelationType.Diagonal, true, drawDiagonalConnections, offY);
drawEdge(g2d, context, sunkenColour, StrokeUtil.getDashedStroke(strokeThin.getLineWidth()), EdgeType.All, RelationType.OffDiagonal, true, drawOffConnections, offY);
}
drawVertices(bridge, g2d, context, sunkenColour, ((GraphStyle)boardStyle).baseVertexRadius(), offY);
}
drawEdge(g2d, context, colorEdgesInner, strokeThin, EdgeType.Inner, RelationType.Orthogonal, false, drawOrthogonalEdges, 0);
drawEdge(g2d, context, colorEdgesOuter, strokeThick(), EdgeType.Outer, RelationType.Orthogonal, false, drawOrthogonalEdges, 0);
drawEdge(g2d, context, colorEdgesInner, StrokeUtil.getDottedStroke(strokeThin.getLineWidth()), EdgeType.All, RelationType.Diagonal, false, drawDiagonalEdges, 0);
drawEdge(g2d, context, colorEdgesInner, strokeThin, EdgeType.Inner, RelationType.Orthogonal, true, drawOrthogonalConnections, 0);
drawEdge(g2d, context, colorEdgesInner, StrokeUtil.getDottedStroke(strokeThin.getLineWidth()), EdgeType.All, RelationType.Diagonal, true, drawDiagonalConnections, 0);
drawEdge(g2d, context, colorEdgesInner, StrokeUtil.getDashedStroke(strokeThin.getLineWidth()), EdgeType.All, RelationType.OffDiagonal, true, drawOffConnections, 0);
// Draw arrow heads.
if (context.metadata().graphics().showEdgeDirections())
for (final Edge edge : topology().edges())
drawArrowHeads(g2d, strokeThin, edge);
drawVertices(bridge, g2d, context, ((GraphStyle)boardStyle).baseVertexRadius());
drawSymbols(g2d, context);
if (context.game().isDeductionPuzzle() && context.game().metadata().graphics().showRegionOwner())
drawRegions(g2d, context, colorSymbol(), strokeThick, hintRegions);
drawGround(g2d, context, false);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
/**
* Draws a specified edge of the board/graph.
*/
protected void drawEdge
(
final Graphics2D g2d,
final Context context,
final Color defaultLineColour,
final Stroke defaultLineStroke,
final EdgeType edgeType,
final RelationType relationType,
final boolean connection,
final boolean alwaysDraw,
final double offsetY
)
{
// Check Metadata to see if any specific style or colour has been defined for this Edge/Relation type.
Color lineColour = defaultLineColour;
Stroke lineStroke = defaultLineStroke;
final EdgeInfoGUI edgeInfoGUI = context.game().metadata().graphics().drawEdge(edgeType, relationType, connection);
if (edgeInfoGUI != null)
{
if (edgeInfoGUI.getStyle().equals(LineStyle.Hidden))
return;
if (edgeInfoGUI.getColour() != null)
lineColour = edgeInfoGUI.getColour();
if (edgeInfoGUI.getStyle() != null)
lineStroke = StrokeUtil.getStrokeFromStyle(edgeInfoGUI.getStyle(), strokeThin, strokeThick());
}
if (alwaysDraw || edgeInfoGUI != null)
{
if (relationType.supersetOf(RelationType.Orthogonal))
{
if (connection)
{
drawOrthogonalConnections(g2d, context, lineColour, lineStroke, offsetY);
}
else
{
if (edgeType.supersetOf(EdgeType.Inner))
drawInnerCellEdges(g2d, context, lineColour, lineStroke, offsetY);
if (edgeType.supersetOf(EdgeType.Outer))
drawOuterCellEdges(g2d, context, lineColour, lineStroke, offsetY);
}
}
if (relationType.supersetOf(RelationType.Diagonal))
{
if (connection)
drawDiagonalConnections(g2d, context, lineColour, lineStroke, offsetY);
else
drawDiagonalEdges(g2d, context, lineColour, lineStroke, offsetY);
}
if (relationType.supersetOf(RelationType.OffDiagonal))
{
if (connection)
drawOffDiagonalConnections(g2d, context, lineColour, lineStroke, offsetY);
}
}
}
//-------------------------------------------------------------------------
/**
* Draws arrow heads on the edge if it is directional.
*/
protected void drawArrowHeads(final Graphics2D g2d, final BasicStroke stroke, final Edge edge)
{
final Point drawPosnA = screenPosn(edge.vA().centroid());
final Point drawPosnB = screenPosn(edge.vB().centroid());
if (Edge.toB())
drawArrowHead(g2d, new Line2D.Double(drawPosnA, drawPosnB), stroke);
if (Edge.toA())
drawArrowHead(g2d, new Line2D.Double(drawPosnB, drawPosnA), stroke);
}
//-------------------------------------------------------------------------
/**
* Draws an Arrow head on the line passed in.
*/
protected static void drawArrowHead(final Graphics2D g2d, final Line2D line, final BasicStroke stroke)
{
final int strokeWidth = (int)stroke.getLineWidth()*4;
final Polygon arrowHead = new Polygon();
arrowHead.addPoint(0, 0);
arrowHead.addPoint((int)(-strokeWidth/1.5), -strokeWidth);
arrowHead.addPoint((int)(strokeWidth/1.5),-strokeWidth);
final AffineTransform tx = new AffineTransform();
tx.setToIdentity();
final double angle = Math.atan2(line.getY2()-line.getY1(), line.getX2()-line.getX1());
tx.translate(line.getX2(), line.getY2());
tx.rotate(angle - Math.PI/2d);
final Graphics2D g = (Graphics2D) g2d.create();
g.setTransform(tx);
g.fill(arrowHead);
g.dispose();
}
}
| 9,042 | 35.317269 | 170 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/graph/PenAndPaperDesign.java
|
package view.container.aspects.designs.board.graph;
import bridge.Bridge;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class PenAndPaperDesign extends GraphDesign
{
public PenAndPaperDesign(final Bridge bridge, final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement, false, false);
bridge.settingsVC().setNoAnimation(true);
}
//-------------------------------------------------------------------------
}
| 526 | 26.736842 | 113 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/puzzle/FutoshikiDesign.java
|
package view.container.aspects.designs.board.puzzle;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import bridge.Bridge;
import game.types.board.SiteType;
import game.util.directions.CompassDirection;
import metadata.graphics.util.PuzzleHintLocationType;
import other.context.Context;
import other.topology.TopologyElement;
import other.topology.Vertex;
import view.container.aspects.designs.board.graph.GraphDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class FutoshikiDesign extends GraphDesign
{
public FutoshikiDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement, false, false);
hintLocationType = PuzzleHintLocationType.BetweenVertices;
}
//-------------------------------------------------------------------------
@Override
public void drawPuzzleHints(final Graphics2D g2d, final Context context)
{
if (hintValues == null)
detectHints(context);
for (final TopologyElement graphElement : topology().getAllGraphElements())
{
final SiteType type = graphElement.elementType();
final int site = graphElement.index();
final Point2D posn = graphElement.centroid();
final Point drawnPosn = screenPosn(posn);
for (int i = 0; i < hintValues.size(); i++)
{
if (locationValues.get(i).site() == site && locationValues.get(i).siteType() == type)
{
int maxHintvalue = 0;
for (int j = 0; j < hintValues.size(); j++)
{
if (hintValues.get(i) != null)
{
if (hintValues.get(i).intValue() > maxHintvalue)
{
maxHintvalue = hintValues.get(i).intValue();
}
}
}
Font valueFont = new Font("Arial", Font.BOLD, (boardStyle.cellRadiusPixels()));
g2d.setColor(Color.BLACK);
g2d.setFont(valueFont);
Rectangle2D rect = g2d.getFont().getStringBounds("^", g2d.getFontRenderContext());
if (hintDirections.get(i) == CompassDirection.W)
{
rect = g2d.getFont().getStringBounds("<", g2d.getFontRenderContext());
g2d.drawString("<", (int)(drawnPosn.x - rect.getWidth()/2), (int)(drawnPosn.y + rect.getHeight()/3));
}
else if (hintDirections.get(i) == CompassDirection.N)
{
rect = g2d.getFont().getStringBounds("^", g2d.getFontRenderContext());
g2d.drawString("^", (int)(drawnPosn.x - rect.getWidth()/2), (int)(drawnPosn.y + rect.getHeight()/2));
}
else if (hintDirections.get(i) == CompassDirection.E)
{
rect = g2d.getFont().getStringBounds(">", g2d.getFontRenderContext());
g2d.drawString(">", (int)(drawnPosn.x - rect.getWidth()/2), (int)(drawnPosn.y + rect.getHeight()/3));
}
else if (hintDirections.get(i) == CompassDirection.S)
{
valueFont = new Font("Arial", Font.BOLD, -(boardStyle.cellRadiusPixels()));
g2d.setFont(valueFont);
g2d.drawString("^", (int)(drawnPosn.x + rect.getWidth()/2), (int)(drawnPosn.y - rect.getHeight()/2));
}
}
}
}
}
//-------------------------------------------------------------------------
@Override
protected void drawVertices(final Bridge bridge, final Graphics2D g2d, final Context context, final double radius)
{
for (final Vertex vertex : topology().vertices())
{
final int squareSize = (int) (boardStyle.cellRadiusPixels() * 1.2);
g2d.setColor(colorEdgesOuter);
g2d.setStroke(new BasicStroke(strokeThick.getLineWidth(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER));
final Point pt = boardStyle.screenPosn(vertex.centroid());
g2d.drawRect(pt.x-squareSize/2, pt.y-squareSize/2, squareSize, squareSize);
}
}
//-------------------------------------------------------------------------
}
| 3,869 | 33.553571 | 115 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/puzzle/HashiDesign.java
|
package view.container.aspects.designs.board.puzzle;
import java.awt.Color;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import other.context.Context;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class HashiDesign extends PuzzleDesign
{
public HashiDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 3 / 1000.0f;
final float swThin = Math.max(1, (int) (swRatio * boardStyle.placement().width + 0.5));
final float swThick = 2 * swThin;
setStrokesAndColours
(
bridge,
context,
new Color(0, 0, 0),
null,
null,
null,
null,
null,
null,
null,
new Color(0, 0, 0),
swThin,
swThick
);
//boardStyle.detectHints(context);
final double cellDistance = boardStyle.cellRadius();
final double vertexRadius = 0.5 * boardStyle.placement().width * cellDistance;
drawVertices(bridge, g2d, context, vertexRadius);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
}
| 1,386 | 22.508475 | 90 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/puzzle/KakuroDesign.java
|
package view.container.aspects.designs.board.puzzle;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.List;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.types.board.SiteType;
import game.util.directions.CompassDirection;
import gnu.trove.list.array.TIntArrayList;
import other.context.Context;
import other.topology.Cell;
import other.topology.TopologyElement;
import other.topology.Vertex;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class KakuroDesign extends PuzzleDesign
{
public KakuroDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 5 / 1000.0f;
final float swThin = Math.max(1, (int) (swRatio * boardStyle.placement().width + 0.5));
final float swThick = 2 * swThin;
setStrokesAndColours
(
bridge,
context,
new Color(120, 190, 240),
null,
new Color(210, 230, 255),
null,
null,
null,
null,
null,
new Color(120, 190, 240),
swThin,
swThick
);
if (hintValues == null)
detectHints(context);
final TIntArrayList blackLocations = new TIntArrayList();
final TIntArrayList varsConstraints = context.game().constraintVariables();
for (final Cell c : context.board().topology().cells())
if (varsConstraints.contains(c.index()))
blackLocations.add(c.index());
fillCells(g2d, boardStyle.placement().width, colorFillPhase0, colorEdgesInner, strokeThin, blackLocations, Color.BLACK, true);
drawInnerCellEdges(g2d, context);
drawOuterCellEdges(bridge, g2d, context);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
@Override
public void drawPuzzleHints(final Graphics2D g2d, final Context context)
{
if (hintValues == null)
detectHints(context);
final Font valueFont = new Font("Arial", Font.BOLD, (boardStyle.cellRadiusPixels()));
g2d.setColor(Color.WHITE);
g2d.setFont(valueFont);
for (final TopologyElement graphElement : topology().getAllGraphElements())
{
final SiteType type = graphElement.elementType();
final int site = graphElement.index();
final Point2D posn = graphElement.centroid();
final Point drawnPosn = screenPosn(posn);
for (int i = 0; i < hintValues.size(); i++)
{
if (locationValues.get(i).site() == site && locationValues.get(i).siteType() == type)
{
int maxHintvalue = 0;
for (int j = 0; j < hintValues.size(); j++)
{
if (hintValues.get(i) != null)
{
if (hintValues.get(i).intValue() > maxHintvalue)
{
maxHintvalue = hintValues.get(i).intValue();
}
}
}
if (maxHintvalue > 9)
g2d.setFont(new Font("Arial", Font.BOLD, (int) (boardStyle.cellRadiusPixels()/1.5)));
final Rectangle2D rect = g2d.getFont().getStringBounds(Integer.toString(hintValues.get(i).intValue()), g2d.getFontRenderContext());
if (hintDirections.get(i) == CompassDirection.W)
g2d.drawString(hintValues.get(i).toString(), (int)(drawnPosn.x - rect.getWidth()/2 - cellRadiusPixels()*1.5), (int)(drawnPosn.y + rect.getHeight()/4 - cellRadiusPixels()*0.3));
else if (hintDirections.get(i) == CompassDirection.N)
g2d.drawString(hintValues.get(i).toString(), (int)(drawnPosn.x - rect.getWidth()/2 - cellRadiusPixels()*0.5), (int)(drawnPosn.y + rect.getHeight()/4 - cellRadiusPixels()*1.5));
}
}
}
}
//-------------------------------------------------------------------------
/**
* @param g2d
* @param pixels
* @param fillColor
* @param borderColor
* @param stroke
* @param validLocations - null if all locations are valid
* @param colorInvalid - color for the invalid cells
* @param addDiagonal - draws a diagonal if true
*/
protected void fillCells
(
final Graphics2D g2d, final int pixels,
final Color fillColor, final Color borderColor, final BasicStroke stroke,
final TIntArrayList validLocations,
final Color colorInvalid,
final boolean addDiagonal
)
{
final List<Cell> cells = topology().cells();
g2d.setStroke(stroke);
for (final Cell cell : cells)
{
final GeneralPath path = new GeneralPath();
g2d.setColor(fillColor);
for (int v = 0; v < cell.vertices().size(); v++)
{
if (path.getCurrentPoint() == null)
{
final Vertex prev = cell.vertices().get(cell.vertices().size() - 1);
final Point prevPosn = boardStyle.screenPosn(prev.centroid());
path.moveTo(prevPosn.x, prevPosn.y);
}
final Vertex corner = cell.vertices().get(v);
final Point cornerPosn = boardStyle.screenPosn(corner.centroid());
path.lineTo(cornerPosn.x, cornerPosn.y);
}
if (validLocations != null)
{
// if cell is not a valid region, then color it differently
if (!validLocations.contains(cell.index()))
{
g2d.setColor(colorInvalid);
}
}
g2d.fill(path);
if (addDiagonal && validLocations != null)
{
// add diagonal lines to invalid cells
if (!validLocations.contains(cell.index()))
{
g2d.setColor(borderColor);
final Point firstCorner = boardStyle.screenPosn(cell.vertices().get(1).centroid());
final Point secondCorner = boardStyle.screenPosn(cell.vertices().get(3).centroid());
path.moveTo(firstCorner.getX(), firstCorner.y);
path.lineTo(secondCorner.x, secondCorner.y);
g2d.draw(path);
}
}
}
}
}
| 5,903 | 28.818182 | 182 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/puzzle/PuzzleDesign.java
|
package view.container.aspects.designs.board.puzzle;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.types.board.SiteType;
import game.util.directions.CompassDirection;
import metadata.graphics.util.PuzzleDrawHintType;
import metadata.graphics.util.PuzzleHintLocationType;
import other.action.puzzle.ActionSet;
import other.context.Context;
import other.location.FullLocation;
import other.location.Location;
import other.move.Move;
import other.state.State;
import other.state.container.ContainerState;
import other.topology.Edge;
import other.topology.TopologyElement;
import util.ContainerUtil;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class PuzzleDesign extends BoardDesign
{
public PuzzleDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
}
//-------------------------------------------------------------------------
// Deduction puzzle variables
/** Hint values. */
protected ArrayList<Integer> hintValues = null;
/** Hint Directions (when applicable) */
protected ArrayList<CompassDirection> hintDirections = new ArrayList<>();
/** Locations for hints. */
protected ArrayList<Location> locationValues = new ArrayList<>();
/** Regions for hints. */
protected ArrayList<ArrayList<Location>> hintRegions = new ArrayList<>();
protected PuzzleDrawHintType drawHintType = PuzzleDrawHintType.Default;
protected PuzzleHintLocationType hintLocationType = PuzzleHintLocationType.Default;
//-------------------------------------------------------------------------
/**
* fill, draw internal grid lines, draw symbols, draw outer border on top.
* @return SVG as string.
*/
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
// Set all values
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final double boardLineThickness = boardStyle.cellRadiusPixels()/15.0;
checkeredBoard = context.game().metadata().graphics().checkeredBoard();
straightLines = context.game().metadata().graphics().straightRingLines();
final float swThin = (float) Math.max(1, boardLineThickness);
final float swThick = swThin;
setStrokesAndColours
(
bridge,
context,
new Color(120, 190, 240),
new Color(120, 190, 240),
new Color(210, 230, 255),
new Color(210, 0, 0),
new Color(0, 230, 0),
new Color(0, 0, 255),
null,
null,
new Color(0, 0, 0),
swThin,
swThick
);
drawGround(g2d, context, true);
fillCells(bridge, g2d, context);
drawInnerCellEdges(g2d, context);
drawOuterCellEdges(bridge, g2d, context);
drawSymbols(g2d, context);
if (context.game().metadata().graphics().showRegionOwner())
drawRegions(g2d, context, colorSymbol(), strokeThick, hintRegions);
drawGround(g2d, context, false);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
/**
* @param regionIndeces
* @param context
* @return
*/
protected Location findHintPosInRegion(final Integer[] regionIndeces, final SiteType siteType, final Context context)
{
if (regionIndeces.length == 1)
return new FullLocation(regionIndeces[0].intValue(),0,siteType);
double highestRow = -99999999;
double lowestIndex = 99999999;
Location bestLocationFound = null;
for (final Integer cellIndex : regionIndeces)
{
final Point2D posn = context.topology().getGraphElements(context.board().defaultSite()).get(cellIndex.intValue()).centroid();
final double cellX = posn.getX();
final double cellY = posn.getY();
if (hintLocationType == PuzzleHintLocationType.BetweenVertices)
{
final Point2D posnA = context.topology().getGraphElements(siteType).get(regionIndeces[0].intValue()).centroid();
final Point2D posnB = context.topology().getGraphElements(siteType).get(regionIndeces[1].intValue()).centroid();
final Point2D midPoint = new Point2D.Double((posnA.getX() + posnB.getX()) / 2, (posnA.getY() + posnB.getY()) / 2);
double lowestDistance = 99999999;
for (final Edge e : context.board().topology().edges())
{
final double edgeDistance = Math.hypot(midPoint.getX()-e.centroid().getX(), midPoint.getY()-e.centroid().getY());
if (edgeDistance < lowestDistance)
{
lowestDistance = edgeDistance;
bestLocationFound = new FullLocation(e.index(),0,SiteType.Edge);
}
}
if (Math.abs(posnA.getX() - posnB.getX()) < Math.abs(posnA.getY() - posnB.getY()))
{
if (posnA.getY() < posnB.getY())
hintDirections.add(CompassDirection.N);
else
hintDirections.add(CompassDirection.S);
}
else
{
if (posnA.getX() < posnB.getX())
hintDirections.add(CompassDirection.W);
else
hintDirections.add(CompassDirection.E);
}
}
else if
(
cellX <= lowestIndex && cellY >= highestRow
||
cellX < lowestIndex // cellY > highestRow.intValue() if top is preferred over left
)
{
highestRow = posn.getY();
lowestIndex = posn.getX();
bestLocationFound = new FullLocation(cellIndex.intValue(),0,siteType);
if (regionIndeces[0].equals(Integer.valueOf(regionIndeces[1].intValue() - 1)))
hintDirections.add(CompassDirection.W);
else
hintDirections.add(CompassDirection.N);
}
}
return bestLocationFound;
}
//-------------------------------------------------------------------------
protected void detectHints(final Context context)
{
if (!context.game().isDeductionPuzzle())
return;
hintValues = new ArrayList<>();
if (context.game().metadata().graphics().hintLocationType() != null)
hintLocationType = context.game().metadata().graphics().hintLocationType();
if (context.game().metadata().graphics().drawHintType() != null)
drawHintType = context.game().metadata().graphics().drawHintType();
// Cells
if (context.game().rules().phases()[0].play().moves().isConstraintsMoves() && context.game().equipment().cellHints() != null)
{
final int numHints = context.game().equipment().cellHints().length;
for (int i = 0; i < numHints; i++)
{
locationValues.add(findHintPosInRegion(context.game().equipment().cellsWithHints()[i], SiteType.Cell, context));
hintValues.add(context.game().equipment().cellHints()[i]);
final ArrayList<Location> hintRegion = new ArrayList<>();
for (final Integer index : context.game().equipment().cellsWithHints()[i])
hintRegion.add(new FullLocation(index.intValue(),0,SiteType.Cell));
hintRegions.add(hintRegion);
}
}
// Vertices
if (context.game().rules().phases()[0].play().moves().isConstraintsMoves() && context.game().equipment().vertexHints() != null)
{
final int numHints = context.game().equipment().vertexHints().length;
for (int i = 0; i < numHints; i++)
{
locationValues.add(findHintPosInRegion(context.game().equipment().verticesWithHints()[i], SiteType.Vertex, context));
hintValues.add(context.game().equipment().vertexHints()[i]);
}
}
// Edges
if (context.game().rules().phases()[0].play().moves().isConstraintsMoves() && context.game().equipment().edgeHints() != null)
{
final int numHints = context.game().equipment().edgeHints().length;
for (int i = 0; i < numHints; i++)
{
locationValues.add(findHintPosInRegion(context.game().equipment().edgesWithHints()[i], SiteType.Edge, context));
hintValues.add(context.game().equipment().edgeHints()[i]);
}
}
}
//-------------------------------------------------------------------------
@Override
public void drawPuzzleCandidates(final Graphics2D g2d, final Context context)
{
final Font oldFont = g2d.getFont();
final int minPuzzleValue = context.board().getRange(context.board().defaultSite()).min(context);
final int maxPuzzleValue = context.board().getRange(context.board().defaultSite()).max(context);
final int valueRange = maxPuzzleValue - minPuzzleValue + 1;
final int base = (int)Math.sqrt(Math.max(9, valueRange));
final int bigFontSize = (int)(0.75 * boardStyle.placement().getHeight() / Math.max(9, valueRange) + 0.5);
final int smallFontSize = (int)(0.25 * bigFontSize + 0.5);
final Font smallFont = new Font(oldFont.getFontName(), Font.PLAIN, smallFontSize);
// This game has a board
final State state = context.state();
final ContainerState cs = state.containerStates()[0];
final double u = boardStyle.cellRadius()* boardStyle.placement().getHeight();
final double off = 0.6 * u;
// Draw the candidate values, greyed out as appropriate
g2d.setFont(smallFont);
// Determine relative candidate positions within each cell
final Point2D.Double[] offsets = new Point2D.Double[valueRange];
for (int n = 0; n < valueRange; n++)
{
final int row = n / base;
final int col = n % base;
final double x = (col - 0.5 * (base - 1)) * off;
final double y = (row - 0.5 * (base - 1)) * off;
offsets[n] = new Point2D.Double(x, y);
}
for (int site = 0; site < topology().getGraphElements(context.board().defaultSite()).size(); site++)
{
final TopologyElement vertex = topology().cells().get(site);
final Point2D posn = vertex.centroid();
final int cx = (int) (posn.getX() * boardStyle.placement().width + 0.5);
final int cy = boardStyle.placement().height - (int) (posn.getY() * boardStyle.placement().height + 0.5);
if (cs.isResolved(site, context.board().defaultSite()))
continue;
for (int b = 0; b <= valueRange; b++)
{
other.action.puzzle.ActionSet a = null;
a = new ActionSet(context.board().defaultSite(), site, b + minPuzzleValue);
a.setDecision(true);
final Move m = new Move(a);
m.setFromNonDecision(site);
m.setToNonDecision(site);
m.setEdgeMove(site);
m.setDecision(true);
if (!context.moves(context).moves().contains(m) || !cs.bit(site, b+minPuzzleValue, context.board().defaultSite()))
continue;
final int tx = (int)(cx + offsets[b].getX() + 0.5) + boardStyle.placement().x;
final int ty = (int)(cy + offsets[b].getY() + 0.5) + boardStyle.placement().y;
final Point drawPosn = new Point(tx,ty);
boardStyle.drawPuzzleValue(b+minPuzzleValue, site, context, g2d, drawPosn, (int) (cellRadiusPixels() / base*1.5));
}
}
}
//-------------------------------------------------------------------------
@Override
public void drawPuzzleHints(final Graphics2D g2d, final Context context)
{
if (!context.game().isDeductionPuzzle())
return;
if (hintValues == null)
detectHints(context);
for (final TopologyElement graphElement : topology().getAllGraphElements())
{
final SiteType type = graphElement.elementType();
final int site = graphElement.index();
final Point2D posn = graphElement.centroid();
final Point drawnPosn = screenPosn(posn);
for (int i = 0; i < hintValues.size(); i++)
{
if (locationValues.get(i).site() == site && locationValues.get(i).siteType() == type)
{
int maxHintvalue = 0;
for (int j = 0; j < hintValues.size(); j++)
{
if (hintValues.get(i) != null)
{
if (hintValues.get(i).intValue() > maxHintvalue)
{
maxHintvalue = hintValues.get(i).intValue();
}
}
}
if (drawHintType == PuzzleDrawHintType.TopLeft)
{
final Font valueFont = new Font("Arial", Font.BOLD, (int) (boardStyle.cellRadiusPixels()/1.5));
g2d.setColor(Color.BLACK);
g2d.setFont(valueFont);
final Rectangle2D rect = g2d.getFont().getStringBounds(Integer.toString(hintValues.get(i).intValue()), g2d.getFontRenderContext());
g2d.drawString(hintValues.get(i).toString(), (int) (drawnPosn.x - boardStyle.cellRadiusPixels()/1.3), (int) (drawnPosn.y - rect.getHeight()/4));
}
else if (drawHintType == PuzzleDrawHintType.NextTo)
{
final Font valueFont = new Font("Arial", Font.BOLD, (boardStyle.cellRadiusPixels()));
g2d.setColor(Color.BLACK);
g2d.setFont(valueFont);
final Rectangle2D rect = g2d.getFont().getStringBounds(Integer.toString(hintValues.get(i).intValue()), g2d.getFontRenderContext());
if (hintDirections.get(i) == CompassDirection.N)
g2d.drawString(hintValues.get(i).toString(), (int)(drawnPosn.x - rect.getWidth()/2), (int)(drawnPosn.y + rect.getHeight()/4 - cellRadiusPixels()*2));
else if (hintDirections.get(i) == CompassDirection.W)
g2d.drawString(hintValues.get(i).toString(), (int)(drawnPosn.x - rect.getWidth()/2 - cellRadiusPixels()*2), (int)(drawnPosn.y + rect.getHeight()/4));
}
else
{
final Font valueFont = new Font("Arial", Font.BOLD, (boardStyle.cellRadiusPixels()));
g2d.setColor(Color.BLACK);
g2d.setFont(valueFont);
final Rectangle2D rect = g2d.getFont().getStringBounds(Integer.toString(hintValues.get(i).intValue()), g2d.getFontRenderContext());
g2d.drawString(hintValues.get(i).toString(), (int)(drawnPosn.x - rect.getWidth()/2), (int)(drawnPosn.y + rect.getHeight()/4));
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Draws the regions of the board.
*/
protected void drawRegions(final Graphics2D g2d, final Context context, final Color borderColor, final BasicStroke stroke, final ArrayList<ArrayList<Location>> regionList)
{
for (final ArrayList<Location> region : regionList)
drawEdges(g2d, context, borderColor, stroke, ContainerUtil.getOuterRegionEdges(region,topology()), 0);
}
//-------------------------------------------------------------------------
}
| 13,970 | 34.191436 | 173 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/designs/board/puzzle/SudokuDesign.java
|
package view.container.aspects.designs.board.puzzle;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import metadata.graphics.util.PuzzleDrawHintType;
import other.context.Context;
import other.topology.Cell;
import other.topology.Edge;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class SudokuDesign extends PuzzleDesign
{
public SudokuDesign(final BoardStyle boardStyle, final BoardPlacement boardPlacement)
{
super(boardStyle, boardPlacement);
drawHintType = PuzzleDrawHintType.TopLeft;
}
//-------------------------------------------------------------------------
@Override
public String createSVGImage(final Bridge bridge, final Context context)
{
final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues();
final float swRatio = 5 / 1000.0f;
final float swThin = Math.max(1, (int) (swRatio * boardStyle.placement().width + 0.5));
final float swThick = 2 * swThin;
setStrokesAndColours
(
bridge,
context,
new Color(120, 190, 240),
new Color(120, 190, 240),
new Color(210, 230, 255),
null,
null,
null,
null,
null,
new Color(200,50,200),
swThin,
swThick
);
detectHints(context);
fillCells(bridge, g2d, context);
drawInnerCellEdges(g2d, context);
drawOuterCellEdges(bridge, g2d, context);
drawGridEdges(g2d, colorEdgesOuter, strokeThick());
// draw inner sudoku regions (for killer sudoko)
final float dash1[] = {6.0f};
final BasicStroke dashed = new BasicStroke(strokeThin.getLineWidth(),BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER,5.0f, dash1, 0.0f);
drawRegions(g2d, context, colorSymbol(), dashed, hintRegions);
return g2d.getSVGDocument();
}
//-------------------------------------------------------------------------
/**
* Draws the edges of the board grid.
*/
protected void drawGridEdges(final Graphics2D g2d, final Color borderColor, final BasicStroke stroke)
{
final List<Cell> cells = topology().cells();
g2d.setColor(borderColor);
g2d.setStroke(stroke);
final List<Edge> sudokuEdges = new ArrayList<>();
final GeneralPath path = new GeneralPath();
final double boardDimension = Math.sqrt(cells.size());
final int lineInterval = (int) Math.sqrt(boardDimension);
for (final Cell cell : cells)
{
for (final Edge edge : cell.edges())
{
// vertical lines
final int columnValue = (cell.index()+1);
if ( (columnValue%lineInterval == 0) && (columnValue%boardDimension != 0) )
{
if (edge.vA().centroid().getX() > cell.centroid().getX() && edge.vB().centroid().getX() > cell.centroid().getX())
{
sudokuEdges.add(edge);
}
}
// horizontal lines
final int rowLength = (int) Math.sqrt(cells.size());
final int rowValue = ((cell.index())/rowLength);
if ( (rowValue%lineInterval == (lineInterval-1)) && (rowValue%(boardDimension-1) != 0) )
{
if (edge.vA().centroid().getY() > cell.centroid().getY() && edge.vB().centroid().getY() > cell.centroid().getY())
{
sudokuEdges.add(edge);
}
}
}
}
while (sudokuEdges.size() > 0)
{
Edge currentEdge = sudokuEdges.get(0);
boolean nextEdgeFound = true;
final Point2D va = currentEdge.vA().centroid();
Point2D vb = currentEdge.vB().centroid();
final Point vAPosn = screenPosn(va);
Point vBPosn = screenPosn(vb);
path.moveTo(vAPosn.x, vAPosn.y);
while (nextEdgeFound == true)
{
nextEdgeFound = false;
path.lineTo(vBPosn.x, vBPosn.y);
sudokuEdges.remove(currentEdge);
for (final Edge nextEdge : sudokuEdges)
{
if (Math.abs(vb.getX() - nextEdge.vA().centroid().getX()) < 0.0001 && Math.abs(vb.getY() - nextEdge.vA().centroid().getY()) < 0.0001)
{
nextEdgeFound = true;
currentEdge = nextEdge;
vb = currentEdge.vB().centroid();
vBPosn = screenPosn(vb);
break;
}
else if (Math.abs(vb.getX() - nextEdge.vB().centroid().getX()) < 0.0001 && Math.abs(vb.getY() - nextEdge.vB().centroid().getY()) < 0.0001)
{
nextEdgeFound = true;
currentEdge = nextEdge;
vb = currentEdge.vA().centroid();
vBPosn = screenPosn(vb);
break;
}
}
}
}
g2d.draw(path);
}
//-------------------------------------------------------------------------
}
| 4,557 | 26.624242 | 143 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/placement/BoardPlacement.java
|
package view.container.aspects.placement;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import bridge.Bridge;
import game.types.board.SiteType;
import other.context.Context;
import util.ContainerUtil;
import view.container.styles.BoardStyle;
public class BoardPlacement extends ContainerPlacement
{
protected BoardStyle boardStyle;
//-------------------------------------------------------------------------
/** Scale of the board relative to the original placement size (10% margins either side). */
protected double defaultBoardScale = 0.8;
//-------------------------------------------------------------------------
public BoardPlacement(final Bridge bridge, final BoardStyle containerStyle)
{
super(bridge, containerStyle);
containerScale = defaultBoardScale;
boardStyle = containerStyle;
}
//-------------------------------------------------------------------------
/**
* Customise graph element locations, if needed.
*/
public void customiseGraphElementLocations(final Context context)
{
// Note: Do not customise graph element locations based on their current
// locations, otherwise multiple calls will produce cumulative changes.
// Customise graph element locations here:
// ...
// Then call the following:
ContainerUtil.normaliseGraphElements(topology());
ContainerUtil.centerGraphElements(topology());
calculateCellRadius();
resetPlacement(context);
}
//-------------------------------------------------------------------------
/**
*
* @param placement
* @param boardCenter
* @param scale The scale of the board by default.
* @param context
*/
public void setCustomPlacement(final Context context, final Rectangle placement, final Point2D boardCenter, final double scale)
{
final Rectangle unscaledPlacement = new Rectangle(placement.x, placement.y, placement.width + placement.x, placement.height);
setUnscaledPlacement(unscaledPlacement);
containerScale = scale;
this.placement = new Rectangle(
(int)(placement.getX() + placement.getWidth() * (1.0-scale) * boardCenter.getX()),
(int)(placement.getY() + placement.getHeight() * (1.0-scale) * boardCenter.getY()),
(int)(placement.getWidth() * (scale)),
(int)(placement.getHeight() * (scale))
);
setCellRadiusPixels((int) (cellRadius() * this.placement.width));
}
@Override
public void setPlacement(final Context context, final Rectangle placement)
{
final Point2D.Double boardCenter = new Point2D.Double(0.5, 0.5);
if (context.board().defaultSite() == SiteType.Vertex)
containerScale = defaultBoardScale - cellRadius();
else
containerScale = defaultBoardScale;
if (context.game().metadata().graphics().boardPlacement() != null)
{
final Rectangle2D metadataPlacement = context.game().metadata().graphics().boardPlacement();
boardCenter.x += metadataPlacement.getX();
boardCenter.y += metadataPlacement.getY();
containerScale *= metadataPlacement.getWidth();
}
setCustomPlacement(context, placement, boardCenter, containerScale);
}
//-------------------------------------------------------------------------
/**
* Resets the placement of the container.
* Needs to be called if the position of any vertices in the graph are shifted.
*/
public void resetPlacement(final Context context)
{
setPlacement(context, unscaledPlacement());
}
//-------------------------------------------------------------------------
public void setDefaultBoardScale(final double scale)
{
defaultBoardScale = scale;
}
//-------------------------------------------------------------------------
}
| 3,712 | 30.735043 | 128 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/placement/ContainerPlacement.java
|
package view.container.aspects.placement;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.util.List;
import bridge.Bridge;
import game.equipment.container.Container;
import game.types.board.SiteType;
import main.math.MathRoutines;
import other.context.Context;
import other.topology.Cell;
import other.topology.Edge;
import other.topology.Topology;
import other.topology.Vertex;
import util.GraphUtil;
import view.container.BaseContainerStyle;
public class ContainerPlacement
{
protected BaseContainerStyle containerStyle;
//-------------------------------------------------------------------------
/** the scale of the container, relative to the size of the view it is placed on */
protected double containerScale = 1.0;
/** Average distance from cell centroid to edge midpoints, in range 0..1. */
protected double cellRadius = 0;
/** cell size in pixels */
private int cellRadiusPixels;
/** location and dimensions of this container (in pixels) */
protected Rectangle placement;
/** Size of the placement before board scaling (i.e. the size of the view placement). */
private Rectangle unscaledPlacement;
protected Bridge bridge;
//-------------------------------------------------------------------------
public ContainerPlacement(final Bridge bridge, final BaseContainerStyle containerStyle)
{
this.containerStyle = containerStyle;
this.bridge = bridge;
calculateCellRadius();
}
//-------------------------------------------------------------------------
public void setPlacement(final Context context, final Rectangle placement)
{
setUnscaledPlacement(placement);
}
//-------------------------------------------------------------------------
/**
* Calculates average distance from cell centroid to edge midpoints, in range 0..1.
*/
public void calculateCellRadius()
{
double min = 1.0;
if (container().defaultSite() == SiteType.Cell)
{
final List<Cell> cells = topology().cells();
if (cells.size() > 0)
{
for (final Cell cell : cells)
{
final double acc = GraphUtil.calculateCellRadius(cell);
if (acc < min)
min = acc;
}
}
}
else
{
final List<Vertex> vertices = topology().vertices();
if (vertices.size() > 0)
{
for (final Vertex vertex : vertices)
for (final Vertex v : vertex.neighbours())
{
final double dist = MathRoutines.distance(v.centroid(), vertex.centroid()) * 0.5;
if (dist > 0 && dist < min)
min = dist;
}
}
}
if (min > 0.0 && min < 1.0)
{
setCellRadius(min);
}
else // in that case the graph does not have any edges (e.g. Hounds and Jackals)
{
min = 1.0;
for (int i = 0; i < topology().vertices().size(); i++)
{
final Point2D.Double vi = new Point2D.Double(topology().vertices().get(i).centroid().getX(),
topology().vertices().get(i).centroid().getY());
for (int j = i + 1; j < topology().vertices().size(); j++)
{
final Point2D.Double vj = new Point2D.Double(topology().vertices().get(j).centroid().getX(),
topology().vertices().get(j).centroid().getY());
final double dx = vi.x - vj.x;
final double dy = vi.y - vj.y;
final double dist = Math.sqrt(dx * dx + dy * dy);
if (min > dist)
min = dist;
}
}
setCellRadius(min / 2);
}
}
//-------------------------------------------------------------------------
/**
* Convert a normalised position into the corresponding position (pixel) in the app view.
*/
public Point screenPosn(final Point2D posn)
{
try
{
final Point screenPosn = new Point();
screenPosn.x = (int) (placement.x + posn.getX()*placement.width);
screenPosn.y = (int) ((placement.getY()*2 + placement.height) - (placement.y + posn.getY()*placement.height));
return screenPosn;
}
catch (final Exception e)
{
return new Point((int)posn.getX(), (int)posn.getY());
}
}
//-------------------------------------------------------------------------
public double cellRadius()
{
return cellRadius;
}
public int cellRadiusPixels()
{
return cellRadiusPixels;
}
public final Rectangle placement()
{
return placement;
}
public void setCellRadius(final double cellRadius)
{
this.cellRadius = cellRadius;
}
public Rectangle unscaledPlacement()
{
return unscaledPlacement;
}
public void setUnscaledPlacement(final Rectangle unscaledPlacement)
{
this.unscaledPlacement = unscaledPlacement;
}
public final double containerScale()
{
return containerScale;
}
public Topology topology()
{
return containerStyle.topology();
}
public Container container()
{
return containerStyle.container();
}
public void setCellRadiusPixels(final int cellRadiusPixels) {
this.cellRadiusPixels = cellRadiusPixels;
}
@SuppressWarnings("static-method")
public double containerZoom()
{
return 1.0;
}
public List<Cell> drawnCells()
{
return topology().cells();
}
public List<Edge> drawnEdges()
{
return topology().edges();
}
public List<Vertex> drawnVertices()
{
return topology().vertices();
}
}
| 5,166 | 22.81106 | 113 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/placement/HandPlacement.java
|
package view.container.aspects.placement;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.util.List;
import bridge.Bridge;
import other.context.Context;
import other.topology.Cell;
import other.topology.Vertex;
import view.container.BaseContainerStyle;
public class HandPlacement extends ContainerPlacement
{
public HandPlacement(final Bridge bridge, final BaseContainerStyle containerStyle)
{
super(bridge, containerStyle);
}
//-------------------------------------------------------------------------
@Override
public void setPlacement(final Context context, final Rectangle placement)
{
Rectangle newPlacement = placement;
// Metadata can override the placement of the hands.
final Rectangle2D customPlacement = context.game().metadata().graphics().handPlacement(context, container().owner());
final boolean handVertical = context.game().metadata().graphics().handVertical(context, container().owner());
if (customPlacement != null)
{
final int boardViewWidth = (int) bridge.getContainerStyle(0).unscaledPlacement().getWidth();
final int boardViewHeight = (int) bridge.getContainerStyle(0).unscaledPlacement().getHeight();
final double x = customPlacement.getX();
final double y = customPlacement.getY() * (handVertical ? 1 : -1);
double width = customPlacement.getWidth();
double height = 1.0;
if (handVertical)
{
width = 1.0;
height = customPlacement.getHeight();
}
newPlacement = new Rectangle((int)(boardViewWidth * x), (int)(boardViewHeight * y), (int)(boardViewWidth * width), (int)(boardViewHeight * height));
}
this.placement = newPlacement;
// Longest and shortest sides are based on the orientation of the hand.
int longestSide = (int) newPlacement.getWidth();
int shortestSide = (int) newPlacement.getHeight();
if (handVertical)
{
longestSide = (int) newPlacement.getHeight();
shortestSide = (int) newPlacement.getWidth();
}
// Determine the cell radius of the hand.
setCellRadiusPixels((int)(0.6 * shortestSide) / 2);
setCellRadius((double)cellRadiusPixels() / longestSide);
if (cellRadiusPixels() > longestSide / container().numSites() / 2)
{
setCellRadiusPixels(longestSide / container().numSites() / 2);
setCellRadius(1.0 / container().numSites() / 2);
}
setHandLocations(context, customPlacement!=null, handVertical);
}
//-------------------------------------------------------------------------
/**
* Sets the sites for the hand container associated with this placement aspect.
*/
protected void setHandLocations(final Context context, final boolean customPlacement, final boolean verticalPlacement)
{
int persistentSiteCount = 0;
final List<Cell> sites = container().topology().cells();
double xBuffer = 0;
final double yBuffer = 0;
// if this is a shared hand, center the components in the container width
if (container().owner() > context.game().players().count() && !customPlacement)
{
final double totalContainerCellWidth = cellRadiusPixels() * 2.0 * sites.size();
final double difference = placement.getWidth() - totalContainerCellWidth;
xBuffer = (difference/2.0) / placement.getWidth();
}
// Check this site
for (int site = 0; site < sites.size(); site++)
{
double xPosn = cellRadius() * 2 * (persistentSiteCount + 0.5) + xBuffer;
double yPosn = 0;
// If the hand is vertically oriented.
if (verticalPlacement)
{
xPosn = 0;
yPosn = cellRadius() * 2 * (persistentSiteCount + 0.5) + yBuffer;
}
topology().cells().get(site).setCentroid(xPosn, yPosn, 0);
// Normalise all cell vertex positions.
double minX = 99999;
double minY = 99999;
double maxX = -99999;
double maxY = -99999;
for (final Vertex vertex : topology().cells().get(site).vertices())
{
if (vertex.centroid().getX() < minX)
minX = vertex.centroid().getX();
if (vertex.centroid().getX() > maxX)
maxX = vertex.centroid().getX();
if (vertex.centroid().getY() < minY)
minY = vertex.centroid().getY();
if (vertex.centroid().getY() > maxY)
maxY = vertex.centroid().getY();
}
for (final Vertex vertex : topology().cells().get(site).vertices())
{
final double normalisedVx = (vertex.centroid().getX() - minX) / (maxX - minX);
final double normalisedVy = (vertex.centroid().getY() - minY) / (maxY - minY);
vertex.setCentroid(normalisedVx, normalisedVy, 0);
}
final double widthToHeightRatio = cellRadius()*(placement.getWidth()/placement.getHeight());
for (final Vertex vertex : topology().cells().get(site).vertices())
{
final double vx = vertex.centroid().getX();
final double vy = vertex.centroid().getY();
vertex.setCentroid(xPosn - cellRadius() + vx * cellRadius() * 2,
yPosn + widthToHeightRatio - vy * widthToHeightRatio * 2, 0);
}
persistentSiteCount++;
}
}
//-------------------------------------------------------------------------
}
| 5,007 | 32.837838 | 151 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/placement/Board/BackgammonPlacement.java
|
package view.container.aspects.placement.Board;
import java.util.List;
import bridge.Bridge;
import other.context.Context;
import other.topology.Vertex;
import util.ContainerUtil;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class BackgammonPlacement extends BoardPlacement
{
/** The size of the home region of the board. */
private final int homeSize;
//-------------------------------------------------------------------------
public BackgammonPlacement(final Bridge bridge, final BoardStyle containerStyle)
{
super(bridge, containerStyle);
homeSize = topology().vertices().size() / 4;
}
//-------------------------------------------------------------------------
@Override
public void customiseGraphElementLocations(final Context context)
{
final int pixels = placement.width;
final int unitsX = 2 * homeSize() + 1 + 1; // 2 * runs + bar + border
final int unitsY = 2 * (homeSize() - 1) + 1 + 1; // 2 * stacks + space + border
final int mx = pixels / 2;
final int my = pixels / 2;
final int unit = pixels / (unitsX + 1) / 2 * 2; // even
final int border = unit / 2;
final int ax = mx - (int)(unitsX * unit / 2.0 + 0.5);
final int ay = my - (int)(unitsY * unit / 2.0 + 0.5);
final int cx = ax + border;
final int cy = ay + border;
// Nudge vertices into position
final List<Vertex> vertices = topology().vertices();
final int halfSize = vertices.size() / 2;
final int offset = (int)(0.08 * Math.abs(vertices.get(0).centroid().getX() * pixels - vertices.get(1).centroid().getX() * pixels));
for (int n = 0; n < vertices.size(); n++)
{
final Vertex vertex = vertices.get(n);
final int sign = (n < halfSize) ? -1 : 1;
final int x = cx + (n % halfSize) * unit + unit / 2;
final int y = cy + (n / halfSize * 10) * unit + unit / 2 + sign * offset;
vertex.setCentroid(x / (double) pixels, y / (double) pixels, 0);
}
ContainerUtil.normaliseGraphElements(topology());
ContainerUtil.centerGraphElements(topology());
calculateCellRadius();
resetPlacement(context);
}
//-------------------------------------------------------------------------
public int homeSize()
{
return homeSize;
}
//-------------------------------------------------------------------------
}
| 2,338 | 27.876543 | 133 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/placement/Board/BoardlessPlacement.java
|
package view.container.aspects.placement.Board;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import bridge.Bridge;
import game.equipment.component.Component;
import main.Constants;
import other.context.Context;
import other.state.State;
import other.topology.Cell;
import other.topology.Edge;
import other.topology.Vertex;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class BoardlessPlacement extends BoardPlacement
{
// Various variables representing visual information about the container.
private State currentState;
private long currentStateHash = -1;
private List<Cell> zoomedCells;
private List<Edge> zoomedEdges;
private List<Vertex> zoomedVertices;
protected double zoom = 1.0;
//-------------------------------------------------------------------------
public BoardlessPlacement(final Bridge bridge, final BoardStyle containerStyle)
{
super(bridge, containerStyle);
}
//-------------------------------------------------------------------------
@Override
public List<Cell> drawnCells()
{
final List<Cell> drawnCells = new ArrayList<Cell>();
for (final Cell vOri : topology().cells())
{
if (currentState.containerStates()[0].isPlayable(vOri.index()) || currentState.containerStates()[0].isOccupied(vOri.index()))
{
final Cell newCell = zoomedCells.get(vOri.index());
final ArrayList<Vertex> newVertices = new ArrayList<>();
for (final Vertex v : vOri.vertices())
{
newVertices.add(zoomedVertices.get(v.index()));
}
newCell.setVertices(newVertices);
drawnCells.add(newCell);
}
else
{
final Cell newCell = new Cell(vOri.index(), Constants.UNDEFINED, Constants.UNDEFINED,
Constants.UNDEFINED);
drawnCells.add(newCell);
}
}
return drawnCells;
}
//-------------------------------------------------------------------------
@Override
public List<Edge> drawnEdges()
{
final List<Edge> drawnEdges = new ArrayList<Edge>();
for (final Edge eOri : topology().edges())
{
for (final Cell c : eOri.cells())
{
if
(
currentState.containerStates()[0].isPlayable(c.index())
||
currentState.containerStates()[0].isOccupied(c.index())
)
{
final Edge e = zoomedEdges.get(eOri.index());
drawnEdges.add(e);
continue;
}
}
}
return drawnEdges;
}
//-------------------------------------------------------------------------
@Override
public List<Vertex> drawnVertices()
{
final List<Vertex> drawnVertices = new ArrayList<Vertex>();
for (final Vertex fOri : topology().vertices())
{
for (final Cell v : fOri.cells())
{
if
(
currentState.containerStates()[0].isPlayable(v.index())
||
currentState.containerStates()[0].isOccupied(v.index())
)
{
drawnVertices.add(zoomedVertices.get(fOri.index()));
break;
}
}
}
return drawnVertices;
}
//-------------------------------------------------------------------------
/**
* Apply zoomAmount onto a specified point, based on the provided center point.
*/
public static Point2D.Double applyZoomToPoint(final Point2D point, final double zoomAmount, final Point2D.Double centerPoint)
{
final Point2D.Double zoomedPoint = new Point2D.Double();
zoomedPoint.x = (0.5 + (point.getX() - centerPoint.x) * zoomAmount);
zoomedPoint.y = (0.5 + (point.getY() - centerPoint.y) * zoomAmount);
return zoomedPoint;
}
//-------------------------------------------------------------------------
/**
* Set the locations for the zoomedCells, zoomedEdges and zoomedVertices of the container graph.
*/
public double setZoomedLocations(final Context context)
{
int numberOccupiedCells = 0;
double minX = 99999;
double minY = 99999;
double maxX = -99999;
double maxY = -99999;
if (currentState != null)
{
for (final Cell vertex : topology().cells())
{
if (currentState.containerStates()[0].isPlayable(vertex.index()) || currentState.containerStates()[0].isOccupied(vertex.index()))
{
numberOccupiedCells++;
if (vertex.centroid().getX() < minX)
minX = vertex.centroid().getX();
if (vertex.centroid().getX() > maxX)
maxX = vertex.centroid().getX();
if (vertex.centroid().getY() < minY)
minY = vertex.centroid().getY();
if (vertex.centroid().getY() > maxY)
maxY = vertex.centroid().getY();
}
}
}
// Used to make sure there is some padding on either side of the board.
minX = minX - cellRadius();
minY = minY - cellRadius();
maxX = maxX + cellRadius();
maxY = maxY + cellRadius();
double newZoom = 1.0;
double centerPointX = 0.5;
double centerPointY = 0.5;
if (numberOccupiedCells > 0)
{
final double boardZoomX = 1.0 / (maxX - minX);
final double boardZoomY = 1.0 / (maxY - minY);
newZoom = Math.min(boardZoomX, boardZoomY);
centerPointX = (maxX + minX) /2.0;
centerPointY = (maxY + minY) /2.0;
}
int largestPieceWalk = 1;
for (final Component component : context.components())
{
if (component != null && component.isLargePiece())
{
final int stepsForward = component.maxStepsForward();
if (largestPieceWalk < stepsForward)
largestPieceWalk = stepsForward;
}
}
final double maxZoom = 10.0 / largestPieceWalk;
if (newZoom > maxZoom)
newZoom = maxZoom;
final List<Cell> graphCells = topology().cells();
final List<Edge> graphEdges = topology().edges();
final List<Vertex> graphVertices = topology().vertices();
if (zoomedVertices == null || zoomedEdges == null || zoomedCells == null)
{
zoomedCells = new ArrayList<>(topology().cells().size());
zoomedEdges = new ArrayList<>(topology().edges().size());
zoomedVertices = new ArrayList<>(topology().vertices().size());
}
else
{
zoomedCells.clear();
zoomedEdges.clear();
zoomedVertices.clear();
}
for (int i = 0; i < graphCells.size(); i++)
{
final Cell cell = graphCells.get(i);
final Point2D.Double zoomedPoint = applyZoomToPoint(cell.centroid(), newZoom, new Point2D.Double(centerPointX, centerPointY));
final Cell zoomedCell = new Cell(i, zoomedPoint.x, zoomedPoint.y, 0);
zoomedCell.setOrthogonal(cell.orthogonal());
zoomedCell.setDiagonal(cell.diagonal());
zoomedCell.setOff(cell.off());
zoomedCells.add(zoomedCell);
}
for (int i = 0; i < graphEdges.size(); i++)
{
final Edge edge = graphEdges.get(i);
final Point2D.Double zoomedPointA = applyZoomToPoint(edge.vA().centroid(), newZoom, new Point2D.Double(centerPointX, centerPointY));
final Point2D.Double zoomedPointB = applyZoomToPoint(edge.vB().centroid(), newZoom, new Point2D.Double(centerPointX, centerPointY));
final Edge zoomedEdge = new Edge(i, new Vertex(edge.vA().index(), zoomedPointA.x, zoomedPointA.y, 0),
new Vertex(edge.vB().index(), zoomedPointB.x, zoomedPointB.y, 0));
zoomedEdges.add(zoomedEdge);
}
for (int i = 0; i < graphVertices.size(); i++)
{
final Vertex vertex = graphVertices.get(i);
final Point2D.Double zoomedPoint = applyZoomToPoint(vertex.centroid(), newZoom, new Point2D.Double(centerPointX, centerPointY));
final Vertex zoomedVertex = new Vertex(i, zoomedPoint.x, zoomedPoint.y, 0);
zoomedVertices.add(zoomedVertex);
}
return newZoom;
}
//-------------------------------------------------------------------------
/**
* Calculate the zoom amount for the container.
*/
public void calculateZoom(final Context context)
{
currentState = context.state();
if (currentStateHash != currentState.stateHash())
{
currentStateHash = currentState.stateHash();
zoom = setZoomedLocations(context);
}
}
//-------------------------------------------------------------------------
/**
* Update the zoomed image of the game board.
*/
public void updateZoomImage(final Context context)
{
calculateZoom(context);
setCellRadiusPixels((int)(cellRadius() * placement().width * containerZoom()));
}
//-------------------------------------------------------------------------
@Override
public double containerZoom()
{
return zoom;
}
//-------------------------------------------------------------------------
}
| 8,280 | 27.653979 | 135 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/placement/Board/Connect4Placement.java
|
package view.container.aspects.placement.Board;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.util.List;
import bridge.Bridge;
import game.types.board.SiteType;
import other.context.Context;
import other.topology.Cell;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class Connect4Placement extends BoardPlacement
{
/** Number of rows in the connect-4 board. */
private final int connect4Rows = 6;
//-------------------------------------------------------------------------
public Connect4Placement(final Bridge bridge, final BoardStyle containerStyle)
{
super(bridge, containerStyle);
}
//-------------------------------------------------------------------------
@Override
public void setPlacement(final Context context, final Rectangle placement)
{
super.setCustomPlacement(context, placement, new Point2D.Double(0.5, 0.5), 1.0);
setCellLocations(placement.width, topology().cells());
}
//-------------------------------------------------------------------------
public void setCellLocations(final int pixels, final List<Cell> cells)
{
final int cols = topology().columns(SiteType.Cell).size();
final int rows = connect4Rows;
final int u = pixels / (cols + 1);
final int x0 = pixels / 2 - (int) (0.5 * cols * u + 0.5);
final int y0 = pixels / 2 - (int) (0.5 * rows * u + 0.5);
for (int n = 0; n < cols; n++)
{
final Cell cell = cells.get(n);
final int row = 0; // rows - 1;
final int col = n;
final int x = x0 + col * u + u / 2;
final int y = y0 + row * u + u / 2;
cell.setCentroid(x / (double) pixels, y / (double) pixels, 0);
topology().cells().get(cell.index()).setCentroid(x / (double) pixels, y / (double) pixels, 0);
}
}
//-------------------------------------------------------------------------
public int connect4Rows()
{
return connect4Rows;
}
}
| 1,929 | 26.571429 | 97 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/placement/Board/HoundsAndJackalsPlacement.java
|
package view.container.aspects.placement.Board;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import bridge.Bridge;
import other.context.Context;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class HoundsAndJackalsPlacement extends BoardPlacement
{
public HoundsAndJackalsPlacement(final Bridge bridge, final BoardStyle containerStyle)
{
super(bridge, containerStyle);
}
//-------------------------------------------------------------------------
@Override
public void setPlacement(final Context context, final Rectangle placement)
{
setCustomPlacement(context, placement, new Point2D.Double(0.5, 0.6), 0.7);
}
//-------------------------------------------------------------------------
}
| 782 | 26 | 88 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/placement/Board/PyramidalPlacement.java
|
package view.container.aspects.placement.Board;
import bridge.Bridge;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class PyramidalPlacement extends BoardPlacement
{
public PyramidalPlacement(final Bridge bridge, final BoardStyle containerStyle)
{
super(bridge, containerStyle);
}
//-------------------------------------------------------------------------
@Override
public void calculateCellRadius()
{
super.calculateCellRadius();
setCellRadius(cellRadius*1.4);
}
//-------------------------------------------------------------------------
// @Override
// public void calculateAverageCellRadius()
// {
// final List<Cell> groundVertices = new ArrayList<Cell>();
//
// for (final Cell cell : topology().cells())
// if (cell.layer() == 0)
// groundVertices.add(cell);
//
// double min = 1.0;
// for (int i = 0; i < groundVertices.size(); i++)
// {
// final Point2D.Double vi = new Point2D.Double(groundVertices.get(i).centroid().getX(),
// groundVertices.get(i).centroid().getY());
// for (int j = i + 1; j < groundVertices.size(); j++)
// {
// final Point2D.Double vj = new Point2D.Double(groundVertices.get(j).centroid().getX(),
// groundVertices.get(j).centroid().getY());
// final double dx = vi.x - vj.x;
// final double dy = vi.y - vj.y;
// final double dist = Math.sqrt(dx * dx + dy * dy);
// if (min > dist)
// min = dist;
// }
// }
// setCellRadius(min / 2);
// }
//-------------------------------------------------------------------------
}
| 1,587 | 27.357143 | 91 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/placement/Board/SurakartaPlacement.java
|
package view.container.aspects.placement.Board;
import java.awt.Rectangle;
import bridge.Bridge;
import game.types.board.SiteType;
import other.context.Context;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
public class SurakartaPlacement extends BoardPlacement
{
public SurakartaPlacement(final Bridge bridge, final BoardStyle containerStyle)
{
super(bridge, containerStyle);
}
//-------------------------------------------------------------------------
@Override
public void setPlacement(final Context context, final Rectangle placement)
{
final int rows = boardStyle.container().topology().rows(SiteType.Vertex).size() - 1;
final int cols = boardStyle.container().topology().columns(SiteType.Vertex).size() - 1;
final double maxDim = Math.max(rows, cols);
int extra = Math.min(rows, cols) / 2;
final int numLoops = container().tracks().size() / 2;
if (numLoops >= extra)
extra += 1;
final double fullDim = maxDim + extra * 2;
// Enlarge scale to reduce outer margin
switch (topology().graph().basis())
{
case Square: containerScale = 1.1 * (maxDim) / fullDim; break;
case Triangular: containerScale = 0.9 * (maxDim) / fullDim; break;
//$CASES-OMITTED$
default: System.out.println("** Board type " + topology().graph().basis() + " not supported for Surkarta.");
}
setUnscaledPlacement(placement);
this.placement = new Rectangle(
(int)(placement.getX() + placement.getWidth() * (1.0-containerScale)/2),
(int)(placement.getY() + placement.getHeight() * (1.0-containerScale)/2),
(int)(placement.getWidth() * (containerScale)),
(int)(placement.getHeight() * (containerScale))
);
setCellRadiusPixels((int) (cellRadius() * placement.width * containerScale));
}
//-------------------------------------------------------------------------
}
| 1,913 | 33.178571 | 110 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/placement/Board/TablePlacement.java
|
package view.container.aspects.placement.Board;
import java.util.List;
import bridge.Bridge;
import other.context.Context;
import other.topology.Vertex;
import util.ContainerUtil;
import view.container.aspects.placement.BoardPlacement;
import view.container.styles.BoardStyle;
/**
* The placement of the pieces in the Table board.
*
* @author Eric.Piette
*/
public class TablePlacement extends BoardPlacement
{
/** The size of the home region of the board. */
private final int homeSize;
//-------------------------------------------------------------------------
public TablePlacement(final Bridge bridge, final BoardStyle containerStyle)
{
super(bridge, containerStyle);
homeSize = topology().vertices().size() / 4;
}
//-------------------------------------------------------------------------
@Override
public void customiseGraphElementLocations(final Context context)
{
final int pixels = placement.width;
final int unitsX = 2 * homeSize() + 1 + 1; // 2 * homes + bar + border
final int unitsY = 2 * (homeSize() - 1) + 1 + 1; // 2 * stacks + space + border
final int mx = pixels / 2;
final int my = pixels / 2;
final int unit = pixels / unitsX / 2 * 2; // even
final int border = unit / 2;
final int ax = mx - (int) (unitsX * unit / 2.0 + 0.5);
final int ay = my - (int) (unitsY * unit / 2.0 + 0.5);
final int cx = ax + border;
final int cy = ay + border;
final List<Vertex> vertices = topology().vertices();
final int halfSize = vertices.size() / 2;
final int offset = (int) (0.08
* Math.abs(vertices.get(0).centroid().getX() * pixels - vertices.get(1).centroid().getX() * pixels));
for (int n = 0; n < vertices.size(); n++)
{
final Vertex vertex = vertices.get(n);
final int sign = (n < halfSize) ? -1 : 1;
// final int x = (int) (vertex.centroid().getX() * pixels);
final int x = cx + (n % halfSize) * unit + unit / 2 + (leftSide(halfSize / 2, n) ? 0 : unit);
final int y = cy + (n / halfSize * 10) * unit + unit / 2 + sign * offset;
vertex.setCentroid(x / (double) pixels, y / (double) pixels, 0);
}
ContainerUtil.normaliseGraphElements(topology());
ContainerUtil.centerGraphElements(topology());
calculateCellRadius();
resetPlacement(context);
}
//-------------------------------------------------------------------------
public int homeSize()
{
return homeSize;
}
//-------------------------------------------------------------------------
private static boolean leftSide(final int sideSize, final int index)
{
final int x = index / sideSize;
return x % 2 == 0;
}
//-------------------------------------------------------------------------
}
| 2,678 | 27.5 | 105 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/aspects/tracks/ContainerTrack.java
|
package view.container.aspects.tracks;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import bridge.Bridge;
import game.Game;
import game.equipment.container.board.Track;
import game.types.board.SiteType;
import main.Constants;
import other.context.Context;
import other.topology.TopologyElement;
import util.ArrowUtil;
import view.container.ContainerStyle;
public class ContainerTrack
{
/**
* Draw all tracks on the board, that the user has opted to show.
*/
public void drawTracks(final Bridge bridge, final Graphics2D g2d, final Context context, final ContainerStyle containerStyle)
{
for (int i = 0; i < bridge.settingsVC().trackNames().size(); i++)
if (bridge.settingsVC().trackShown().get(i).booleanValue())
drawTrackArrow(bridge, g2d, bridge.settingsVC().trackNames().get(i), context, containerStyle);
}
//-------------------------------------------------------------------------
/**
* Draw arrows representing a specific track on the board.
*/
@SuppressWarnings("static-method")
public void drawTrackArrow(final Bridge bridge, final Graphics2D g2d, final String trackName, final Context context, final ContainerStyle containerStyle)
{
final Game game = context.game();
final int cellRadiusPixels = containerStyle.cellRadiusPixels();
final Rectangle placement = containerStyle.placement();
final int totalTrackNumber = context.board().tracks().size();
final double shiftAmount = cellRadiusPixels / (totalTrackNumber+2) / 2.0;
int pushAmount = -(totalTrackNumber)+2;
boolean startFromHand = false;
boolean endToHand = false;
for (final Track track : context.board().tracks())
{
pushAmount++;
if (track.name().equals(trackName.substring(11)))
{
for (int e = 0; e < track.elems().length; e++)
{
int from = track.elems()[e].site;
int to = track.elems()[e].next;
if (to <= game.equipment().totalDefaultSites()
&& from <= game.equipment().totalDefaultSites() && to > -1 && from > -1)
{
final int fromContainerIdx = context.containerId()[from];
from -= context.sitesFrom()[fromContainerIdx];
final int toContainerIdx = context.containerId()[to];
to -= context.sitesFrom()[toContainerIdx];
List<? extends TopologyElement> fromCells = new ArrayList<>();
List<? extends TopologyElement> toCells = new ArrayList<>();
if (context.board().defaultSite() == SiteType.Vertex)
{
fromCells = game.equipment().containers()[fromContainerIdx].topology().vertices();
toCells = game.equipment().containers()[toContainerIdx].topology().vertices();
}
else if (context.board().defaultSite() == SiteType.Cell)
{
fromCells = game.equipment().containers()[fromContainerIdx].topology().cells();
toCells = game.equipment().containers()[toContainerIdx].topology().cells();
}
else
{
fromCells = game.equipment().containers()[fromContainerIdx].topology().edges();
toCells = game.equipment().containers()[toContainerIdx].topology().edges();
}
if (context.containers()[fromContainerIdx].isHand())
{
startFromHand = true;
}
if (context.containers()[toContainerIdx].isHand())
{
endToHand = true;
}
// don't display arrow if from or to hand
if (!context.containers()[fromContainerIdx].isHand()
&& !context.containers()[toContainerIdx].isHand())
{
final int maxRadius = cellRadiusPixels;
final int minRadius = maxRadius / 4;
int fromX = (int) (placement.x + fromCells.get(from).centroid().getX() * placement.width);
int fromY = (int) (placement.y + placement.height - (fromCells.get(from).centroid().getY() * placement.height));
int toX = (int) (placement.x + toCells.get(to).centroid().getX() * placement.width);
int toY = (int) (placement.y + placement.height - (toCells.get(to).centroid().getY() * placement.height));
int x1 = fromX;
int x2 = toX;
int y1 = fromY;
int y2 = toY;
double L = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
fromX = (int) (x1 + pushAmount * shiftAmount * (y2-y1) / L);
toX = (int) (x2 + pushAmount * shiftAmount * (y2-y1) / L);
fromY = (int) (y1 + pushAmount * shiftAmount * (x1-x2) / L);
toY = (int) (y2 + pushAmount * shiftAmount * (x1-x2) / L);
final Point2D.Double toPoint = new Point2D.Double(toX,toY);
final Point2D.Double fromPoint = new Point2D.Double(fromX,fromY);
final double arrowThicknessScale = 0.3;
final int arrowWidth = Math
.max((int) ((minRadius + arrowThicknessScale * (maxRadius - minRadius)) / 2.5), 1);
try
{
g2d.setColor(bridge.settingsColour().playerColour(context, track.owner()));
}
catch (final Exception E)
{
g2d.setColor(new Color(0, 0, 0));
}
if (track.owner() == 0)
{
g2d.setColor(new Color(0, 0, 0));
}
int fromNext = -1;
int toNext = -1;
int fromPrev = -1;
int toPrev = -1;
if ((e < track.elems().length - 1 && !endToHand) || e < track.elems().length - 2)
{
fromNext = track.elems()[e + 1].site;
toNext = track.elems()[e + 1].next;
if (toNext < context.board().topology().cells().size()
&& toNext > Constants.OFF)
{
final int fromContainerIdxNext = context.containerId()[fromNext];
fromNext -= context.sitesFrom()[fromContainerIdxNext];
final int toContainerIdxNext = context.containerId()[toNext];
toNext -= context.sitesFrom()[toContainerIdxNext];
}
}
if ((e > 0 && !startFromHand) || e > 1)
{
fromPrev = track.elems()[e - 1].site;
toPrev = track.elems()[e - 1].next;
if (toPrev < context.board().topology().cells().size()
&& toPrev > Constants.OFF)
{
final int fromContainerIdxPrev = context.containerId()[fromPrev];
fromPrev -= context.sitesFrom()[fromContainerIdxPrev];
final int toContainerIdxPrev = context.containerId()[toPrev];
toPrev -= context.sitesFrom()[toContainerIdxPrev];
}
}
Point2D.Double intersectionPointNext = new Point2D.Double();
Point2D.Double intersectionPointPrev = new Point2D.Double();
if (fromNext != -1 && toNext != -1)
{
try
{
int fromNextX = (int) (placement.x + fromCells.get(fromNext).centroid().getX() * placement.width);
int fromNextY = (int) (placement.y + placement.height - (fromCells.get(fromNext).centroid().getY() * placement.height));
int toNextX = (int) (placement.x + toCells.get(toNext).centroid().getX() * placement.width);
int toNextY = (int) (placement.y + placement.height - (toCells.get(toNext).centroid().getY() * placement.height));
x1 = fromNextX;
x2 = toNextX;
y1 = fromNextY;
y2 = toNextY;
L = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
fromNextX = (int) (x1 + pushAmount * shiftAmount * (y2-y1) / L);
toNextX = (int) (x2 + pushAmount * shiftAmount * (y2-y1) / L);
fromNextY = (int) (y1 + pushAmount * shiftAmount * (x1-x2) / L);
toNextY = (int) (y2 + pushAmount * shiftAmount * (x1-x2) / L);
final Point2D.Double toNextPoint = new Point2D.Double(toNextX,toNextY);
final Point2D.Double fromNextPoint = new Point2D.Double(fromNextX,fromNextY);
intersectionPointNext = lineLineIntersection(fromPoint,toPoint,fromNextPoint,toNextPoint);
if (intersectionPointNext != null)
{
toX = (int) intersectionPointNext.x;
toY = (int) intersectionPointNext.y;
}
}
catch (final Exception E)
{
//carry on
}
}
if (fromPrev != -1 && toPrev != -1)
{
try
{
int fromPrevX = (int) (placement.x + fromCells.get(fromPrev).centroid().getX() * placement.width);
int fromPrevY = (int) (placement.y + placement.height - (fromCells.get(fromPrev).centroid().getY() * placement.height));
int toPrevX = (int) (placement.x + toCells.get(toPrev).centroid().getX() * placement.width);
int toPrevY = (int) (placement.y + placement.height - (toCells.get(toPrev).centroid().getY() * placement.height));
x1 = fromPrevX;
x2 = toPrevX;
y1 = fromPrevY;
y2 = toPrevY;
L = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
fromPrevX = (int) (x1 + pushAmount * shiftAmount * (y2-y1) / L);
toPrevX = (int) (x2 + pushAmount * shiftAmount * (y2-y1) / L);
fromPrevY = (int) (y1 + pushAmount * shiftAmount * (x1-x2) / L);
toPrevY = (int) (y2 + pushAmount * shiftAmount * (x1-x2) / L);
final Point2D.Double toPrevPoint = new Point2D.Double(toPrevX,toPrevY);
final Point2D.Double fromPrevPoint = new Point2D.Double(fromPrevX,fromPrevY);
intersectionPointPrev = lineLineIntersection(fromPoint,toPoint,fromPrevPoint,toPrevPoint);
if (intersectionPointPrev != null)
{
fromX = (int) intersectionPointPrev.x;
fromY = (int) intersectionPointPrev.y;
}
}
catch (final Exception E)
{
//carry on
}
}
ArrowUtil.drawArrow(g2d, fromX, fromY, toX, toY, arrowWidth, (Math.max(arrowWidth, 3)),
(int) (1.75 * (Math.max(arrowWidth, 5))));
}
}
}
}
pushAmount++;
}
}
//-------------------------------------------------------------------------
/**
* Return the point where two lines intersect
*/
protected static Point2D.Double lineLineIntersection(final Point2D.Double A, final Point2D.Double B, final Point2D.Double C, final Point2D.Double D)
{
// Line AB represented as a1x + b1y = c1
final double a1 = B.y - A.y;
final double b1 = A.x - B.x;
final double c1 = a1*(A.x) + b1*(A.y);
// Line CD represented as a2x + b2y = c2
final double a2 = D.y - C.y;
final double b2 = C.x - D.x;
final double c2 = a2*(C.x)+ b2*(C.y);
final double determinant = a1*b2 - a2*b1;
if (determinant == 0)
{
// The lines are parallel.
return null;
}
else
{
final double x = (b2*c1 - b1*c2)/determinant;
final double y = (a1*c2 - a2*c1)/determinant;
return new Point2D.Double(x, y);
}
}
//-------------------------------------------------------------------------
}
| 10,999 | 34.947712 | 154 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/BoardStyle.java
|
package view.container.styles;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.BaseContainerStyle;
import view.container.aspects.axes.BoardAxis;
import view.container.aspects.designs.BoardDesign;
import view.container.aspects.placement.BoardPlacement;
/**
* @author Matthew.Stephenson and cambolbro
*/
public class BoardStyle extends BaseContainerStyle
{
protected BoardPlacement boardPlacement;
//-------------------------------------------------------------------------
/**
* Constructor
* @param container
*/
public BoardStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
boardPlacement = new BoardPlacement(bridge, this);
containerPlacement = boardPlacement;
containerAxis = new BoardAxis(this);
containerDesign = new BoardDesign(this, boardPlacement);
}
@Override
public void setDefaultBoardScale(final double scale)
{
boardPlacement.setDefaultBoardScale(scale);
}
//-------------------------------------------------------------------------
}
| 1,060 | 24.878049 | 76 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/HandStyle.java
|
package view.container.styles;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.BaseContainerStyle;
import view.container.aspects.placement.HandPlacement;
/**
* Implementation of hand container style.
* @author matthew.stephenson
*/
public class HandStyle extends BaseContainerStyle
{
public HandStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
containerPlacement = new HandPlacement(bridge, this);
}
@Override
public void setDefaultBoardScale(final double scale)
{
// do nothing
}
//-------------------------------------------------------------------------
}
| 656 | 21.655172 | 76 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/BackgammonStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.components.board.BackgammonComponents;
import view.container.aspects.designs.board.BackgammonDesign;
import view.container.aspects.placement.Board.BackgammonPlacement;
import view.container.styles.BoardStyle;
/**
* Custom style for Backgammon boards.
* @author cambolbro
*/
public class BackgammonStyle extends BoardStyle
{
public BackgammonStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
final BackgammonPlacement backgammonPlacement = new BackgammonPlacement(bridge, this);
containerPlacement = backgammonPlacement;
containerDesign = new BackgammonDesign(this, backgammonPlacement);
containerComponents = new BackgammonComponents(bridge, this);
}
}
| 836 | 32.48 | 88 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/BoardlessStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.BoardlessDesign;
import view.container.aspects.placement.Board.BoardlessPlacement;
import view.container.styles.BoardStyle;
public class BoardlessStyle extends BoardStyle
{
public BoardlessStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
final BoardlessPlacement boardlessPlacement = new BoardlessPlacement(bridge, this);
containerPlacement = boardlessPlacement;
containerDesign = new BoardlessDesign(this, boardlessPlacement);
}
//-------------------------------------------------------------------------
}
| 705 | 31.090909 | 85 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/ChessStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import other.context.Context;
import view.container.aspects.designs.board.ChessDesign;
import view.container.styles.board.puzzle.PuzzleStyle;
public class ChessStyle extends PuzzleStyle
{
public ChessStyle(final Bridge bridge, final Container container, final Context context)
{
super(bridge, container, context);
containerDesign = new ChessDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 567 | 27.4 | 90 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/Connect4Style.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.components.board.Connect4Components;
import view.container.aspects.designs.board.Connect4Design;
import view.container.aspects.placement.Board.Connect4Placement;
import view.container.styles.BoardStyle;
public class Connect4Style extends BoardStyle
{
public Connect4Style(final Bridge bridge, final Container container)
{
super(bridge, container);
final Connect4Placement connect4Placement = new Connect4Placement(bridge, this);
containerPlacement = connect4Placement;
containerDesign = new Connect4Design(this, connect4Placement);
containerComponents = new Connect4Components(bridge, this, connect4Placement);
}
//-------------------------------------------------------------------------
}
| 844 | 32.8 | 82 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/ConnectiveGoalStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.ConnectiveGoalDesign;
import view.container.styles.BoardStyle;
public class ConnectiveGoalStyle extends BoardStyle
{
public ConnectiveGoalStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
containerDesign = new ConnectiveGoalDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 527 | 26.789474 | 76 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/GoStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.GoDesign;
import view.container.styles.BoardStyle;
public class GoStyle extends BoardStyle
{
public GoStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
containerDesign = new GoDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 478 | 24.210526 | 76 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/HoundsAndJackalsStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.HoundsAndJackalsDesign;
import view.container.aspects.placement.Board.HoundsAndJackalsPlacement;
import view.container.styles.BoardStyle;
/**
* Hounds and Jackals (i.e. 58 Holes) board style.
* @author cambolbro
*/
public class HoundsAndJackalsStyle extends BoardStyle
{
public HoundsAndJackalsStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
final HoundsAndJackalsPlacement houndsAndJackalsPlacement = new HoundsAndJackalsPlacement(bridge, this);
containerPlacement = houndsAndJackalsPlacement;
containerDesign = new HoundsAndJackalsDesign(this, houndsAndJackalsPlacement);
}
//-------------------------------------------------------------------------
}
| 857 | 32 | 106 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/IsometricStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.IsometricDesign;
import view.container.styles.BoardStyle;
public class IsometricStyle extends BoardStyle
{
public IsometricStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
containerDesign = new IsometricDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 507 | 25.736842 | 76 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/JanggiStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.JanggiDesign;
import view.container.styles.BoardStyle;
public class JanggiStyle extends BoardStyle
{
public JanggiStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
containerDesign = new JanggiDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 494 | 25.052632 | 76 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/LascaStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.LascaDesign;
import view.container.styles.BoardStyle;
public class LascaStyle extends BoardStyle
{
public LascaStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
containerDesign = new LascaDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 489 | 24.789474 | 76 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/MancalaStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.components.board.MancalaComponents;
import view.container.aspects.designs.board.MancalaDesign;
import view.container.styles.BoardStyle;
/**
* Basic style for generic Mancala boards.
*
* @author cambolbro
*/
public class MancalaStyle extends BoardStyle
{
public MancalaStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
containerDesign = new MancalaDesign(this);
containerComponents = new MancalaComponents(bridge, this);
}
//-------------------------------------------------------------------------
}
| 684 | 25.346154 | 76 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/ShibumiStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.ShibumiDesign;
import view.container.aspects.placement.Board.PyramidalPlacement;
import view.container.styles.BoardStyle;
public class ShibumiStyle extends BoardStyle
{
public ShibumiStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
final PyramidalPlacement pyramidalPlacement = new PyramidalPlacement(bridge, this);
containerPlacement = pyramidalPlacement;
containerDesign = new ShibumiDesign(this, pyramidalPlacement);
}
//-------------------------------------------------------------------------
}
| 697 | 30.727273 | 85 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/ShogiStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.ShogiDesign;
import view.container.styles.BoardStyle;
public class ShogiStyle extends BoardStyle
{
public ShogiStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
containerDesign = new ShogiDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 490 | 24.842105 | 76 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/SnakesAndLaddersStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.SnakesAndLaddersDesign;
import view.container.styles.BoardStyle;
public class SnakesAndLaddersStyle extends BoardStyle
{
public SnakesAndLaddersStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
containerDesign = new SnakesAndLaddersDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 534 | 27.157895 | 78 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/SpiralStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.SpiralDesign;
import view.container.styles.BoardStyle;
/**
* Spiral board style that draws cells based on centroid position, e.g. for Mehen.
*
* @author cambolbro
*/
public class SpiralStyle extends BoardStyle
{
public SpiralStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
containerDesign = new SpiralDesign(this);
}
//-------------------------------------------------------------------------
}
| 595 | 23.833333 | 83 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/SurakartaStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.SurakartaDesign;
import view.container.aspects.placement.Board.SurakartaPlacement;
import view.container.styles.BoardStyle;
/**
* Graphic style for Surakarta boards.
*
* @author cambolbro
*/
public class SurakartaStyle extends BoardStyle
{
public SurakartaStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
final SurakartaPlacement surakartaPlacement = new SurakartaPlacement(bridge, this);
containerPlacement = surakartaPlacement;
containerDesign = new SurakartaDesign(this, surakartaPlacement);
}
//-------------------------------------------------------------------------
}
| 776 | 27.777778 | 85 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/TableStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.components.board.TableComponents;
import view.container.aspects.designs.board.TableDesign;
import view.container.aspects.placement.Board.TablePlacement;
import view.container.styles.BoardStyle;
/**
* Custom style for Table boards.
*
* @author Eric.Piette
*/
public class TableStyle extends BoardStyle
{
public TableStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
final TablePlacement backgammonPlacement = new TablePlacement(bridge, this);
containerPlacement = backgammonPlacement;
containerDesign = new TableDesign(this, backgammonPlacement);
containerComponents = new TableComponents(bridge, this);
}
}
| 791 | 29.461538 | 78 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/TaflStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.TaflDesign;
import view.container.styles.BoardStyle;
public class TaflStyle extends BoardStyle
{
public TaflStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
containerDesign = new TaflDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 486 | 24.631579 | 76 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/UltimateTicTacToeStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.UltimateTicTacToeDesign;
import view.container.styles.BoardStyle;
/**
* Graphic style for Surakarta boards.
*
* @author cambolbro
*/
public class UltimateTicTacToeStyle extends BoardStyle
{
public UltimateTicTacToeStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
containerDesign = new UltimateTicTacToeDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 608 | 24.375 | 78 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/XiangqiStyle.java
|
package view.container.styles.board;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.aspects.designs.board.XiangqiDesign;
import view.container.styles.BoardStyle;
public class XiangqiStyle extends BoardStyle
{
public XiangqiStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
containerDesign = new XiangqiDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 497 | 25.210526 | 76 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/graph/GraphStyle.java
|
package view.container.styles.board.graph;
import java.awt.Color;
import bridge.Bridge;
import game.equipment.container.Container;
import other.context.Context;
import view.container.aspects.designs.board.graph.GraphDesign;
import view.container.styles.board.puzzle.PuzzleStyle;
public class GraphStyle extends PuzzleStyle
{
protected final Color baseGraphColour = new Color(200, 200, 200);
protected double baseVertexRadius = 6;
protected double baseLineWidth = 0.5 * baseVertexRadius;
//-------------------------------------------------------------------------
/**
* @param container The container to draw (typically the board).
*/
public GraphStyle(final Bridge bridge, final Container container, final Context context)
{
super(bridge, container, context);
containerDesign = new GraphDesign(this, boardPlacement, true, true);
}
//-------------------------------------------------------------------------
public Color baseGraphColour()
{
return baseGraphColour;
}
//-------------------------------------------------------------------------
public double baseVertexRadius()
{
return baseVertexRadius;
}
public void setBaseVertexRadius(final double vr)
{
baseVertexRadius = vr;
}
public double baseLineWidth()
{
return baseLineWidth;
}
public void setBaseLineWidth(final double lw)
{
baseLineWidth = lw;
}
//-------------------------------------------------------------------------
}
| 1,457 | 22.901639 | 90 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/graph/PenAndPaperStyle.java
|
package view.container.styles.board.graph;
import bridge.Bridge;
import game.equipment.container.Container;
import other.context.Context;
import view.container.aspects.components.board.PenAndPaperComponents;
import view.container.aspects.designs.board.graph.PenAndPaperDesign;
public class PenAndPaperStyle extends GraphStyle
{
public PenAndPaperStyle(final Bridge bridge, final Container container, final Context context)
{
super(bridge, container, context);
final PenAndPaperDesign boardDesign = new PenAndPaperDesign(bridge, this, boardPlacement);
containerDesign = boardDesign;
containerComponents = new PenAndPaperComponents(bridge, this, boardDesign);
}
//-------------------------------------------------------------------------
}
| 755 | 33.363636 | 96 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/puzzle/FutoshikiStyle.java
|
package view.container.styles.board.puzzle;
import bridge.Bridge;
import game.equipment.container.Container;
import other.context.Context;
import view.container.aspects.designs.board.puzzle.FutoshikiDesign;
import view.container.styles.board.graph.GraphStyle;
public class FutoshikiStyle extends GraphStyle
{
public FutoshikiStyle(final Bridge bridge, final Container container, final Context context)
{
super(bridge, container, context);
containerDesign = new FutoshikiDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 593 | 28.7 | 94 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/puzzle/HashiStyle.java
|
package view.container.styles.board.puzzle;
import bridge.Bridge;
import game.equipment.container.Container;
import other.context.Context;
import view.container.aspects.designs.board.puzzle.HashiDesign;
public class HashiStyle extends PuzzleStyle
{
public HashiStyle(final Bridge bridge, final Container container, final Context context)
{
super(bridge, container, context);
containerDesign = new HashiDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
// @Override
// protected void drawVertices(final Graphics2D g2d, final Context context, final double vertexRadius)
// {
// final double innerCircleScale = 0.9;
// for (final Cell v : topology().cells())
// {
// if (locationValuesVertex.contains(Integer.valueOf(v.index())))
// {
// final int x = (int) (v.centroid().getX() * placement.width + 0.5);
// final int y = placement.width - (int) (v.centroid().getY() * placement.width + 0.5);
//
// g2d.setColor(colorOuter);
// final java.awt.Shape ellipseO = new Ellipse2D.Double(x - vertexRadius, y - vertexRadius, 2 * vertexRadius, 2 * vertexRadius);
// g2d.fill(ellipseO);
//
// g2d.setColor(Color.WHITE);
// final java.awt.Shape ellipseI = new Ellipse2D.Double(x - vertexRadius * innerCircleScale, y - vertexRadius * innerCircleScale, 2 * vertexRadius * innerCircleScale, 2 * vertexRadius * innerCircleScale);
// g2d.fill(ellipseI);
// }
// }
// }
//-------------------------------------------------------------------------
// @Override
// protected void drawComponents(final Graphics2D g2d, final Context context)
// {
// final int pixels = placement.width;
//
// final int swThin = Math.max(1, (int) (0.0025 * pixels + 0.5));
// final int swThick = 25;
// strokeThin = new BasicStroke(swThin, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
// GeneralPath path = new GeneralPath();
//
// // Sizes used for drawing pieces and vertex when edge victory conditions
// final double cellDistance = cellRadius;
// final double rO = 0.025 * pixels * cellDistance * swThick;
// final double rI = 0.022 * pixels * cellDistance * swThick;
//
// final ContainerState ps = (ContainerState) context.trial().state().containerStates()[0];
//
// // draw edges
// for (int edgeIndex = 0; edgeIndex < topology().edges().size(); edgeIndex++)
// {
// final Edge e = topology().edges().get(edgeIndex);
// final int num_edges = ps.numberEdge(edgeIndex);
// if (locationValuesVertex.contains(Integer.valueOf(e.vA().index())) && locationValuesVertex.contains(Integer.valueOf(e.vB().index())))
// {
// g2d.setColor(colorInner);
// path = new GeneralPath();
//
// final Point2D.Double va = e.vA().centroid();
// final Point2D.Double vb = e.vB().centroid();
//
// double ax = 0;
// double ay = 0;
// double bx = 0;
// double by = 0;
//
// if (!ps.resolvedEdges(edgeIndex))
// {
// // draw nothing
// }
// else if (num_edges == 0)
// {
// ax = va.x * pixels;
// ay = pixels - 1 - va.y * pixels;
//
// bx = vb.x * pixels;
// by = pixels - 1 - vb.y * pixels;
//
// final double midpointX = (ax + bx) / 2.0;
// final double midpointY = (ay + by) / 2.0;
//
// final Font oldFont = g2d.getFont();
// final Font font = new Font(oldFont.getFontName(), Font.BOLD, (int) (0.45 * cellRadius * pixels)); // * Global.fontScale));
// g2d.setFont(font);
// final Rectangle2D bounds = font.getStringBounds("X", g2d.getFontRenderContext());
// g2d.drawString("X", (int) (midpointX - bounds.getWidth()/2.0), (int) (midpointY + bounds.getHeight()/3.0));
//
// }
// else
// {
// // draw the certain lines (or lack thereof)
// final double lineSpacing = pixels * cellDistance * 0.3;
// g2d.setStroke(strokeThin);
//
// if (Math.abs(va.x - vb.x) < Math.abs(va.y - vb.y))
// {
// // extra lines need to be shifted horizontally
// for (int i = 0; i < num_edges; i++)
// {
// ax = va.x * pixels + (i * lineSpacing) - ((num_edges-1)/2.0*lineSpacing) + placement.x;
// ay = pixels - 1 - va.y * pixels + placement.y;
//
// bx = vb.x * pixels + (i * lineSpacing) - ((num_edges-1)/2.0*lineSpacing) + placement.x;
// by = pixels - 1 - vb.y * pixels + placement.y;
//
// if (ax < bx - 0.001) // line goes right
// {
// ax = ax + rO - (rO-rI)/2;
// bx = bx - rO + (rO-rI)/2;
// }
// if (ax > bx + 0.001) // line goes left
// {
// ax = ax - rO + (rO-rI)/2;
// bx = bx + rO - (rO-rI)/2;
// }
// if (ay < by - 0.001) // line goes down
// {
// ay = ay + rO - (rO-rI)/2;
// by = by - rO + (rO-rI)/2;
// }
// if (ay > by + 0.001) // line goes up
// {
// ay = ay - rO + (rO-rI)/2;
// by = by + rO - (rO-rI)/2;
// }
//
// path.moveTo(ax, ay);
// path.lineTo(bx, by);
// g2d.draw(path);
// }
// }
// else
// {
// // extra lines need to be shifted vertically
// for (int i = 0; i < num_edges; i++)
// {
// ax = va.x * pixels + placement.x;
// ay = pixels - 1 - va.y * pixels + (i * lineSpacing) - ((num_edges-1)/2.0*lineSpacing) + placement.y;
//
// bx = vb.x * pixels + placement.x;
// by = pixels - 1 - vb.y * pixels + (i * lineSpacing) - ((num_edges-1)/2.0*lineSpacing) + placement.y;
//
// if (ax < bx - 0.001) // line goes right
// {
// ax = ax + rO - (rO-rI)/2;
// bx = bx - rO + (rO-rI)/2;
// }
// if (ax > bx + 0.001) // line goes left
// {
// ax = ax - rO + (rO-rI)/2;
// bx = bx + rO - (rO-rI)/2;
// }
// if (ay < by - 0.001) // line goes down
// {
// ay = ay + rO - (rO-rI)/2;
// by = by - rO + (rO-rI)/2;
// }
// if (ay > by + 0.001) // line goes up
// {
// ay = ay - rO + (rO-rI)/2;
// by = by + rO - (rO-rI)/2;
// }
//
// path.moveTo(ax, ay);
// path.lineTo(bx, by);
// g2d.draw(path);
// }
// }
// }
// }
// }
// drawPuzzleHints(g2d, context);
// //createImage(context,pixels, cells);
// }
}
| 6,210 | 32.213904 | 207 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/puzzle/KakuroStyle.java
|
package view.container.styles.board.puzzle;
import bridge.Bridge;
import game.equipment.container.Container;
import other.context.Context;
import view.container.aspects.designs.board.puzzle.KakuroDesign;
public class KakuroStyle extends PuzzleStyle
{
public KakuroStyle(final Bridge bridge, final Container container, final Context context)
{
super(bridge, container, context);
containerDesign = new KakuroDesign(this, boardPlacement);
}
//-------------------------------------------------------------------------
}
| 530 | 26.947368 | 91 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/puzzle/PuzzleStyle.java
|
package view.container.styles.board.puzzle;
import bridge.Bridge;
import game.equipment.container.Container;
import other.context.Context;
import view.container.aspects.components.board.PuzzleComponents;
import view.container.aspects.designs.board.puzzle.PuzzleDesign;
import view.container.styles.BoardStyle;
public class PuzzleStyle extends BoardStyle
{
public PuzzleStyle(final Bridge bridge, final Container container, final Context context)
{
super(bridge, container);
final PuzzleDesign puzzleDesign = new PuzzleDesign(this, boardPlacement);
containerDesign = puzzleDesign;
if (context.game().isDeductionPuzzle())
containerComponents = new PuzzleComponents(bridge, this, puzzleDesign);
}
//-------------------------------------------------------------------------
}
| 800 | 29.807692 | 91 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/board/puzzle/SudokuStyle.java
|
package view.container.styles.board.puzzle;
import bridge.Bridge;
import game.equipment.container.Container;
import other.context.Context;
import view.container.aspects.designs.board.puzzle.SudokuDesign;
public class SudokuStyle extends PuzzleStyle
{
public SudokuStyle(final Bridge bridge, final Container container, final Context context)
{
super(bridge, container, context);
final SudokuDesign sudokuDesign = new SudokuDesign(this, boardPlacement);
containerDesign = sudokuDesign;
}
//-------------------------------------------------------------------------
}
| 583 | 26.809524 | 91 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/hand/DeckStyle.java
|
package view.container.styles.hand;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.styles.HandStyle;
/**
* @author Matthew.Stephenson
*/
public class DeckStyle extends HandStyle
{
public DeckStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
}
//-------------------------------------------------------------------------
}
| 407 | 19.4 | 76 |
java
|
Ludii
|
Ludii-master/ViewController/src/view/container/styles/hand/DiceStyle.java
|
package view.container.styles.hand;
import bridge.Bridge;
import game.equipment.container.Container;
import view.container.styles.HandStyle;
/**
*
* @author Matthew.Stephenson
*/
public class DiceStyle extends HandStyle
{
public DiceStyle(final Bridge bridge, final Container container)
{
super(bridge, container);
}
//-------------------------------------------------------------------------
}
| 411 | 18.619048 | 76 |
java
|
DeepSpeech
|
DeepSpeech-master/native_client/java/app/src/androidTest/java/org/deepspeech/ExampleInstrumentedTest.java
|
package org.deepspeech;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("org.deepspeech", appContext.getPackageName());
}
}
| 712 | 25.407407 | 78 |
java
|
DeepSpeech
|
DeepSpeech-master/native_client/java/app/src/main/java/org/deepspeech/DeepSpeechActivity.java
|
package org.deepspeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.media.MediaPlayer;
import java.io.RandomAccessFile;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
import org.deepspeech.libdeepspeech.DeepSpeechModel;
public class DeepSpeechActivity extends AppCompatActivity {
DeepSpeechModel _m = null;
EditText _tfliteModel;
EditText _audioFile;
TextView _decodedString;
TextView _tfliteStatus;
Button _startInference;
final int BEAM_WIDTH = 50;
private char readLEChar(RandomAccessFile f) throws IOException {
byte b1 = f.readByte();
byte b2 = f.readByte();
return (char)((b2 << 8) | b1);
}
private int readLEInt(RandomAccessFile f) throws IOException {
byte b1 = f.readByte();
byte b2 = f.readByte();
byte b3 = f.readByte();
byte b4 = f.readByte();
return (int)((b1 & 0xFF) | (b2 & 0xFF) << 8 | (b3 & 0xFF) << 16 | (b4 & 0xFF) << 24);
}
private void newModel(String tfliteModel) {
this._tfliteStatus.setText("Creating model");
if (this._m == null) {
// sphinx-doc: java_ref_model_start
this._m = new DeepSpeechModel(tfliteModel);
this._m.setBeamWidth(BEAM_WIDTH);
// sphinx-doc: java_ref_model_stop
}
}
private void doInference(String audioFile) {
long inferenceExecTime = 0;
this._startInference.setEnabled(false);
this.newModel(this._tfliteModel.getText().toString());
this._tfliteStatus.setText("Extracting audio features ...");
try {
RandomAccessFile wave = new RandomAccessFile(audioFile, "r");
wave.seek(20); char audioFormat = this.readLEChar(wave);
assert (audioFormat == 1); // 1 is PCM
// tv_audioFormat.setText("audioFormat=" + (audioFormat == 1 ? "PCM" : "!PCM"));
wave.seek(22); char numChannels = this.readLEChar(wave);
assert (numChannels == 1); // MONO
// tv_numChannels.setText("numChannels=" + (numChannels == 1 ? "MONO" : "!MONO"));
wave.seek(24); int sampleRate = this.readLEInt(wave);
assert (sampleRate == this._m.sampleRate()); // desired sample rate
// tv_sampleRate.setText("sampleRate=" + (sampleRate == 16000 ? "16kHz" : "!16kHz"));
wave.seek(34); char bitsPerSample = this.readLEChar(wave);
assert (bitsPerSample == 16); // 16 bits per sample
// tv_bitsPerSample.setText("bitsPerSample=" + (bitsPerSample == 16 ? "16-bits" : "!16-bits" ));
wave.seek(40); int bufferSize = this.readLEInt(wave);
assert (bufferSize > 0);
// tv_bufferSize.setText("bufferSize=" + bufferSize);
wave.seek(44);
byte[] bytes = new byte[bufferSize];
wave.readFully(bytes);
short[] shorts = new short[bytes.length/2];
// to turn bytes to shorts as either big endian or little endian.
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);
this._tfliteStatus.setText("Running inference ...");
long inferenceStartTime = System.currentTimeMillis();
// sphinx-doc: java_ref_inference_start
String decoded = this._m.stt(shorts, shorts.length);
// sphinx-doc: java_ref_inference_stop
inferenceExecTime = System.currentTimeMillis() - inferenceStartTime;
this._decodedString.setText(decoded);
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
} finally {
}
this._tfliteStatus.setText("Finished! Took " + inferenceExecTime + "ms");
this._startInference.setEnabled(true);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deep_speech);
this._decodedString = (TextView) findViewById(R.id.decodedString);
this._tfliteStatus = (TextView) findViewById(R.id.tfliteStatus);
this._tfliteModel = (EditText) findViewById(R.id.tfliteModel);
this._audioFile = (EditText) findViewById(R.id.audioFile);
this._tfliteModel.setText("/sdcard/deepspeech/output_graph.tflite");
this._tfliteStatus.setText("Ready, waiting ...");
this._audioFile.setText("/sdcard/deepspeech/audio.wav");
this._startInference = (Button) findViewById(R.id.btnStartInference);
}
public void onClick_inference_handler(View v) {
this.playAudioFile();
this.doInference(this._audioFile.getText().toString());
}
public void playAudioFile() {
try {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(this._audioFile.getText().toString());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException ex) {
}
}
public void onClick_audio_handler(View v) {
this.playAudioFile();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (this._m != null) {
this._m.freeModel();
}
}
}
| 5,476 | 30.843023 | 108 |
java
|
DeepSpeech
|
DeepSpeech-master/native_client/java/app/src/test/java/org/deepspeech/ExampleUnitTest.java
|
package org.deepspeech;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
| 375 | 21.117647 | 81 |
java
|
DeepSpeech
|
DeepSpeech-master/native_client/java/libdeepspeech/src/androidTest/java/org/deepspeech/libdeepspeech/test/BasicTest.java
|
package org.deepspeech.libdeepspeech.test;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import static org.junit.Assert.*;
import org.deepspeech.libdeepspeech.DeepSpeechModel;
import org.deepspeech.libdeepspeech.CandidateTranscript;
import java.io.RandomAccessFile;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class BasicTest {
public static final String modelFile = "/data/local/tmp/test/output_graph.tflite";
public static final String scorerFile = "/data/local/tmp/test/kenlm.scorer";
public static final String wavFile = "/data/local/tmp/test/LDC93S1.wav";
public static final String[] word = {"friend", "enemy", "family"};
public static final float[] boost = {1.5f, 0f, -20.4f};
private char readLEChar(RandomAccessFile f) throws IOException {
byte b1 = f.readByte();
byte b2 = f.readByte();
return (char)((b2 << 8) | b1);
}
private int readLEInt(RandomAccessFile f) throws IOException {
byte b1 = f.readByte();
byte b2 = f.readByte();
byte b3 = f.readByte();
byte b4 = f.readByte();
return (int)((b1 & 0xFF) | (b2 & 0xFF) << 8 | (b3 & 0xFF) << 16 | (b4 & 0xFF) << 24);
}
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("org.deepspeech.libdeepspeech.test", appContext.getPackageName());
}
@Test
public void loadDeepSpeech_basic() {
DeepSpeechModel m = new DeepSpeechModel(modelFile);
m.freeModel();
}
private String candidateTranscriptToString(CandidateTranscript t) {
String retval = "";
for (int i = 0; i < t.getNumTokens(); ++i) {
retval += t.getToken(i).getText();
}
return retval;
}
private String doSTT(DeepSpeechModel m, boolean extendedMetadata) {
try {
RandomAccessFile wave = new RandomAccessFile(wavFile, "r");
wave.seek(20); char audioFormat = this.readLEChar(wave);
assert (audioFormat == 1); // 1 is PCM
wave.seek(22); char numChannels = this.readLEChar(wave);
assert (numChannels == 1); // MONO
wave.seek(24); int sampleRate = this.readLEInt(wave);
assert (sampleRate == 16000); // 16000 Hz
wave.seek(34); char bitsPerSample = this.readLEChar(wave);
assert (bitsPerSample == 16); // 16 bits per sample
wave.seek(40); int bufferSize = this.readLEInt(wave);
assert (bufferSize > 0);
wave.seek(44);
byte[] bytes = new byte[bufferSize];
wave.readFully(bytes);
short[] shorts = new short[bytes.length/2];
// to turn bytes to shorts as either big endian or little endian.
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);
if (extendedMetadata) {
return candidateTranscriptToString(m.sttWithMetadata(shorts, shorts.length, 1).getTranscript(0));
} else {
return m.stt(shorts, shorts.length);
}
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
} finally {
}
return "";
}
@Test
public void loadDeepSpeech_stt_noLM() {
DeepSpeechModel m = new DeepSpeechModel(modelFile);
String decoded = doSTT(m, false);
assertEquals("she had your dark suit in greasy wash water all year", decoded);
m.freeModel();
}
@Test
public void loadDeepSpeech_stt_withLM() {
DeepSpeechModel m = new DeepSpeechModel(modelFile);
m.enableExternalScorer(scorerFile);
String decoded = doSTT(m, false);
assertEquals("she had your dark suit in greasy wash water all year", decoded);
m.freeModel();
}
@Test
public void loadDeepSpeech_sttWithMetadata_noLM() {
DeepSpeechModel m = new DeepSpeechModel(modelFile);
String decoded = doSTT(m, true);
assertEquals("she had your dark suit in greasy wash water all year", decoded);
m.freeModel();
}
@Test
public void loadDeepSpeech_sttWithMetadata_withLM() {
DeepSpeechModel m = new DeepSpeechModel(modelFile);
m.enableExternalScorer(scorerFile);
String decoded = doSTT(m, true);
assertEquals("she had your dark suit in greasy wash water all year", decoded);
m.freeModel();
}
@Test
public void loadDeepSpeech_HotWord_withLM() {
DeepSpeechModel m = new DeepSpeechModel(modelFile);
m.enableExternalScorer(scorerFile);
for(int i = 0; i < word.length; i++) {
m.addHotWord(word[i], boost[i]);
String decoded = doSTT(m, false);
assertEquals("she had your dark suit in greasy wash water all year", decoded);
m.eraseHotWord(word[i]);
}
m.freeModel();
}
@Test
public void loadDeepSpeech_HotWord_noLM() {
DeepSpeechModel m = new DeepSpeechModel(modelFile);
try {
m.addHotWord(word[0], boost[0]);
assert(false);
}
catch(Exception e) {
assertEquals("Error: External scorer is not enabled. (0x2004).", e.getMessage());
}
finally {
m.freeModel();
assert(true);
}
}
}
| 5,972 | 31.112903 | 113 |
java
|
DeepSpeech
|
DeepSpeech-master/native_client/java/libdeepspeech/src/main/java/org/deepspeech/libdeepspeech/DeepSpeechModel.java
|
package org.deepspeech.libdeepspeech;
/**
* @brief Exposes a DeepSpeech model in Java
**/
public class DeepSpeechModel {
static {
System.loadLibrary("deepspeech-jni");
System.loadLibrary("deepspeech");
}
// FIXME: We should have something better than those SWIGTYPE_*
private SWIGTYPE_p_p_ModelState _mspp;
private SWIGTYPE_p_ModelState _msp;
private void evaluateErrorCode(int errorCode) {
DeepSpeech_Error_Codes code = DeepSpeech_Error_Codes.swigToEnum(errorCode);
if (code != DeepSpeech_Error_Codes.ERR_OK) {
throw new RuntimeException("Error: " + impl.ErrorCodeToErrorMessage(errorCode) + " (0x" + Integer.toHexString(errorCode) + ").");
}
}
/**
* @brief An object providing an interface to a trained DeepSpeech model.
*
* @constructor
*
* @param modelPath The path to the frozen model graph.
*
* @throws RuntimeException on failure.
*/
public DeepSpeechModel(String modelPath) {
this._mspp = impl.new_modelstatep();
evaluateErrorCode(impl.CreateModel(modelPath, this._mspp));
this._msp = impl.modelstatep_value(this._mspp);
}
/**
* @brief Get beam width value used by the model. If setModelBeamWidth was not
* called before, will return the default value loaded from the model file.
*
* @return Beam width value used by the model.
*/
public long beamWidth() {
return impl.GetModelBeamWidth(this._msp);
}
/**
* @brief Set beam width value used by the model.
*
* @param aBeamWidth The beam width used by the model. A larger beam width value
* generates better results at the cost of decoding time.
*
* @throws RuntimeException on failure.
*/
public void setBeamWidth(long beamWidth) {
evaluateErrorCode(impl.SetModelBeamWidth(this._msp, beamWidth));
}
/**
* @brief Return the sample rate expected by the model.
*
* @return Sample rate.
*/
public int sampleRate() {
return impl.GetModelSampleRate(this._msp);
}
/**
* @brief Frees associated resources and destroys model object.
*/
public void freeModel() {
impl.FreeModel(this._msp);
}
/**
* @brief Enable decoding using an external scorer.
*
* @param scorer The path to the external scorer file.
*
* @throws RuntimeException on failure.
*/
public void enableExternalScorer(String scorer) {
evaluateErrorCode(impl.EnableExternalScorer(this._msp, scorer));
}
/**
* @brief Disable decoding using an external scorer.
*
* @throws RuntimeException on failure.
*/
public void disableExternalScorer() {
evaluateErrorCode(impl.DisableExternalScorer(this._msp));
}
/**
* @brief Enable decoding using beam scoring with a KenLM language model.
*
* @param alpha The alpha hyperparameter of the decoder. Language model weight.
* @param beta The beta hyperparameter of the decoder. Word insertion weight.
*
* @throws RuntimeException on failure.
*/
public void setScorerAlphaBeta(float alpha, float beta) {
evaluateErrorCode(impl.SetScorerAlphaBeta(this._msp, alpha, beta));
}
/*
* @brief Use the DeepSpeech model to perform Speech-To-Text.
*
* @param buffer A 16-bit, mono raw audio signal at the appropriate
* sample rate (matching what the model was trained on).
* @param buffer_size The number of samples in the audio signal.
*
* @return The STT result.
*/
public String stt(short[] buffer, int buffer_size) {
return impl.SpeechToText(this._msp, buffer, buffer_size);
}
/**
* @brief Use the DeepSpeech model to perform Speech-To-Text and output metadata
* about the results.
*
* @param buffer A 16-bit, mono raw audio signal at the appropriate
* sample rate (matching what the model was trained on).
* @param buffer_size The number of samples in the audio signal.
* @param num_results Maximum number of candidate transcripts to return. Returned list might be smaller than this.
*
* @return Metadata struct containing multiple candidate transcripts. Each transcript
* has per-token metadata including timing information.
*/
public Metadata sttWithMetadata(short[] buffer, int buffer_size, int num_results) {
return impl.SpeechToTextWithMetadata(this._msp, buffer, buffer_size, num_results);
}
/**
* @brief Create a new streaming inference state. The streaming state returned
* by this function can then be passed to feedAudioContent()
* and finishStream().
*
* @return An opaque object that represents the streaming state.
*
* @throws RuntimeException on failure.
*/
public DeepSpeechStreamingState createStream() {
SWIGTYPE_p_p_StreamingState ssp = impl.new_streamingstatep();
evaluateErrorCode(impl.CreateStream(this._msp, ssp));
return new DeepSpeechStreamingState(impl.streamingstatep_value(ssp));
}
/**
* @brief Feed audio samples to an ongoing streaming inference.
*
* @param cctx A streaming state pointer returned by createStream().
* @param buffer An array of 16-bit, mono raw audio samples at the
* appropriate sample rate (matching what the model was trained on).
* @param buffer_size The number of samples in @p buffer.
*/
public void feedAudioContent(DeepSpeechStreamingState ctx, short[] buffer, int buffer_size) {
impl.FeedAudioContent(ctx.get(), buffer, buffer_size);
}
/**
* @brief Compute the intermediate decoding of an ongoing streaming inference.
*
* @param ctx A streaming state pointer returned by createStream().
*
* @return The STT intermediate result.
*/
public String intermediateDecode(DeepSpeechStreamingState ctx) {
return impl.IntermediateDecode(ctx.get());
}
/**
* @brief Compute the intermediate decoding of an ongoing streaming inference.
*
* @param ctx A streaming state pointer returned by createStream().
* @param num_results Maximum number of candidate transcripts to return. Returned list might be smaller than this.
*
* @return The STT intermediate result.
*/
public Metadata intermediateDecodeWithMetadata(DeepSpeechStreamingState ctx, int num_results) {
return impl.IntermediateDecodeWithMetadata(ctx.get(), num_results);
}
/**
* @brief Compute the final decoding of an ongoing streaming inference and return
* the result. Signals the end of an ongoing streaming inference.
*
* @param ctx A streaming state pointer returned by createStream().
*
* @return The STT result.
*
* @note This method will free the state pointer (@p ctx).
*/
public String finishStream(DeepSpeechStreamingState ctx) {
return impl.FinishStream(ctx.get());
}
/**
* @brief Compute the final decoding of an ongoing streaming inference and return
* the results including metadata. Signals the end of an ongoing streaming
* inference.
*
* @param ctx A streaming state pointer returned by createStream().
* @param num_results Maximum number of candidate transcripts to return. Returned list might be smaller than this.
*
* @return Metadata struct containing multiple candidate transcripts. Each transcript
* has per-token metadata including timing information.
*
* @note This method will free the state pointer (@p ctx).
*/
public Metadata finishStreamWithMetadata(DeepSpeechStreamingState ctx, int num_results) {
return impl.FinishStreamWithMetadata(ctx.get(), num_results);
}
/**
* @brief Add a hot-word.
*
* Words that don't occur in the scorer (e.g. proper nouns) or strings that contain spaces won't be taken into account.
*
* @param word
* @param boost Positive value increases and negative reduces chance of a word occuring in a transcription. Excessive positive boost might lead to splitting up of letters of the word following the hot-word.
*
* @throws RuntimeException on failure.
*
*/
public void addHotWord(String word, float boost) {
evaluateErrorCode(impl.AddHotWord(this._msp, word, boost));
}
/**
* @brief Erase a hot-word.
*
* @param word
*
* @throws RuntimeException on failure.
*
*/
public void eraseHotWord(String word) {
evaluateErrorCode(impl.EraseHotWord(this._msp, word));
}
/**
* @brief Clear all hot-words.
*
* @throws RuntimeException on failure.
*
*/
public void clearHotWords() {
evaluateErrorCode(impl.ClearHotWords(this._msp));
}
}
| 8,900 | 34.181818 | 210 |
java
|
DeepSpeech
|
DeepSpeech-master/native_client/java/libdeepspeech/src/main/java/org/deepspeech/libdeepspeech/DeepSpeechStreamingState.java
|
package org.deepspeech.libdeepspeech;
public final class DeepSpeechStreamingState {
private SWIGTYPE_p_StreamingState _sp;
public DeepSpeechStreamingState(SWIGTYPE_p_StreamingState sp) {
this._sp = sp;
}
public SWIGTYPE_p_StreamingState get() {
return this._sp;
}
}
| 305 | 20.857143 | 67 |
java
|
DeepSpeech
|
DeepSpeech-master/native_client/java/libdeepspeech/src/main/java/org/deepspeech/libdeepspeech_doc/CandidateTranscript.java
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 4.0.1
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.deepspeech.libdeepspeech;
/**
* A single transcript computed by the model, including a confidence<br>
* value and the metadata for its constituent tokens.
*/
public class CandidateTranscript {
private transient long swigCPtr;
protected transient boolean swigCMemOwn;
protected CandidateTranscript(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(CandidateTranscript obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
throw new UnsupportedOperationException("C++ destructor does not have public access");
}
swigCPtr = 0;
}
}
/**
* Size of the tokens array
*/
public long getNumTokens() {
return implJNI.CandidateTranscript_NumTokens_get(swigCPtr, this);
}
/**
* Approximated confidence value for this transcript. This is roughly the<br>
* sum of the acoustic model logit values for each timestep/character that<br>
* contributed to the creation of this transcript.
*/
public double getConfidence() {
return implJNI.CandidateTranscript_Confidence_get(swigCPtr, this);
}
/**
* Retrieve one TokenMetadata element<br>
* <br>
* @param i Array index of the TokenMetadata to get<br>
* <br>
* @return The TokenMetadata requested or null
*/
public TokenMetadata getToken(int i) {
return new TokenMetadata(implJNI.CandidateTranscript_getToken(swigCPtr, this, i), false);
}
}
| 1,960 | 28.712121 | 94 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.