Package game.impl

Source Code of game.impl.SimpleGameController

package game.impl;

import game.ClientRemovedEvent;
import game.GameObject;
import game.GameObjectLocation;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class SimpleGameController extends AbstractGameController {

   public static final int STEP_DELAY = 100;

   public void run() {
      List<GameObjectLocation> movedObjects = new ArrayList<GameObjectLocation>();
      while (true) {
         try {
            Thread.sleep(STEP_DELAY);
         } catch (InterruptedException e) {
            break;
         }

         movedObjects.clear();
         final Set<String> ids = gameObjects.keySet();
         synchronized (gameObjects) {
            for(String id : ids) {
               final GameObject gameObject = gameObjects.get(id);
               if (!gameObject.alive()) {
                  gameObjects.remove(gameObject);
                  notifyClientRemoved(new ClientRemovedEvent(null, gameObject.getId()));
                  continue;
               }
               synchronized (gameObject) {
                  final GameObjectLocation oldLocation = gameObject.getLocation();

                  // move to new location
                  gameObject.doMove(STEP_DELAY);

                  detectWallCollisions(gameObject);

                  final GameObjectLocation newLocation = gameObject.getLocation();
                  if (!newLocation.equals(oldLocation)) {
                     movedObjects.add(newLocation);
                  }
               }
            }
         }

         if (!movedObjects.isEmpty()) {
            notifyObjectMove(movedObjects);
         }
      }
   }

   private void detectWallCollisions(GameObject gameObject) {
      if (gameObject.getX() < 0) gameObject.setSpeed(0);
      if (gameObject.getX() > boardX) gameObject.setSpeed(0);

      if (gameObject.getY() < 0) gameObject.setSpeed(0);
      if (gameObject.getY() > boardY) gameObject.setSpeed(0);
   }

}
TOP

Related Classes of game.impl.SimpleGameController

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.