55import java .util .HashMap ;
66import java .util .List ;
77import java .util .Set ;
8+ import java .lang .Class ;
9+ import java .lang .reflect .Method ;
10+ import java .lang .reflect .InvocationTargetException ;
11+ import org .slf4j .Logger ;
12+ import org .slf4j .LoggerFactory ;
813
914public class MoveFactory {
15+ private static final Logger logger = LoggerFactory .getLogger ("scorekeep.MoveFactory" );
1016 private SecureRandom random = new SecureRandom ();
1117 private final HashMap <String , Move > allMoves = new HashMap <String , Move >(1 );
1218 private MoveModel moveModel = new MoveModel ();
@@ -18,10 +24,11 @@ public class MoveFactory {
1824 public MoveFactory (){
1925 }
2026
21- public Move newMove (String sessionId , String gameId , String userId , String moveText ) throws SessionNotFoundException , GameNotFoundException , StateNotFoundException {
27+ public Move newMove (String sessionId , String gameId , String userId , String moveText ) throws SessionNotFoundException , GameNotFoundException , StateNotFoundException , RulesException {
2228 String moveId = new BigInteger (40 , random ).toString (32 ).toUpperCase ();
2329 String stateId = new BigInteger (40 , random ).toString (32 ).toUpperCase ();
2430 Move move = new Move (moveId , sessionId , gameId , userId , moveText );
31+ String newStateText = "" ;
2532 // load game state
2633 Game game = gameController .getGame (sessionId , gameId );
2734 List <String > states = game .getStates ();
@@ -37,7 +44,15 @@ public Move newMove(String sessionId, String gameId, String userId, String moveT
3744 if (newTurn .size () != 1 ) {
3845 newTurn .remove (userId );
3946 }
40- String newStateText = TicTacToe .move (oldState .getState (), moveText );
47+ String rulesName = game .getRules ();
48+ if ( !rulesName .matches ("[a-zA-Z]{1,16}" ) ) {
49+ throw new RulesException (rulesName );
50+ }
51+ try {
52+ Class <?> rules = Class .forName ("scorekeep." + rulesName );
53+ Method moveMethod = rules .getMethod ("move" , String .class , String .class );
54+ newStateText = (String ) moveMethod .invoke (null , oldState .getState (), moveText );
55+ } catch ( ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e ) { throw new RulesException (rulesName ); }
4156 // save new game state
4257 State newState = new State (stateId , sessionId , gameId , newStateText , newTurn );
4358 // register state and move id to game
0 commit comments