Commit 1527763c authored by Ari Trachtenberg's avatar Ari Trachtenberg
Browse files

Stops when game is over.

parent 9101d344
Loading
Loading
Loading
Loading
+13 −16
Original line number Diff line number Diff line
@@ -12,9 +12,8 @@
    <option name="autoReloadType" value="SELECTIVE" />
  </component>
  <component name="ChangeListManager">
    <list default="true" id="78671b20-6a1e-42c8-be28-50b7f38fa7ff" name="Default Changelist" comment="Working on concurrency issues.">
    <list default="true" id="78671b20-6a1e-42c8-be28-50b7f38fa7ff" name="Default Changelist" comment="">
      <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/src/edu/bu/ec504/spr24/brain/Brain.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/edu/bu/ec504/spr24/brain/Brain.java" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/src/edu/bu/ec504/spr24/sameGameTris/SameGameTris.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/edu/bu/ec504/spr24/sameGameTris/SameGameTris.java" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/src/edu/bu/ec504/spr24/sameGameTris/SelfAwareCircle.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/edu/bu/ec504/spr24/sameGameTris/SelfAwareCircle.java" afterDir="false" />
    </list>
@@ -113,7 +112,7 @@
      <workItem from="1706057188033" duration="218000" />
      <workItem from="1706070762735" duration="2123000" />
      <workItem from="1706112889389" duration="6798000" />
      <workItem from="1706139932552" duration="5472000" />
      <workItem from="1706139932552" duration="8790000" />
    </task>
    <task id="LOCAL-00001" summary="Apparently working version.">
      <created>1580084914114</created>
@@ -176,7 +175,15 @@
      <option name="project" value="LOCAL" />
      <updated>1706114342829</updated>
    </task>
    <option name="localTasksCounter" value="9" />
    <task id="LOCAL-00009" summary="Fixed concurrency issue.">
      <option name="closed" value="true" />
      <created>1706152811353</created>
      <option name="number" value="00009" />
      <option name="presentableId" value="LOCAL-00009" />
      <option name="project" value="LOCAL" />
      <updated>1706152811353</updated>
    </task>
    <option name="localTasksCounter" value="10" />
    <servers />
  </component>
  <component name="TypeScriptGeneratedFilesManager">
@@ -190,17 +197,7 @@
    <MESSAGE value="Working version ..." />
    <MESSAGE value="Nice and clean ..." />
    <MESSAGE value="Working on concurrency issues." />
    <option name="LAST_COMMIT_MESSAGE" value="Working on concurrency issues." />
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager>
      <breakpoints>
        <line-breakpoint enabled="true" type="java-line">
          <url>file://$PROJECT_DIR$/src/edu/bu/ec504/spr24/sameGameTris/SameGameTris.java</url>
          <line>615</line>
          <option name="timeStamp" value="9" />
        </line-breakpoint>
      </breakpoints>
    </breakpoint-manager>
    <MESSAGE value="Fixed concurrency issue." />
    <option name="LAST_COMMIT_MESSAGE" value="Fixed concurrency issue." />
  </component>
</project>
 No newline at end of file
+78 −50
Original line number Diff line number Diff line
@@ -60,6 +60,12 @@ public class SameGameTris extends GUI implements ActionListener, ItemListener {
   * The number of microseconds between Brain moves
   */
  private static final long BRAIN_WAIT_US = 1000000;

  /**
   * The amount of time to wait between games, to allow for existing elements to settle.
   */
  private static final long TIME_BETWEEN_GAMES_MS = 1000;

  /**
   * The number of empty rows on the top of the game.
   */
@@ -105,7 +111,16 @@ public class SameGameTris extends GUI implements ActionListener, ItemListener {
  private SelfAwareCircle[][] circles;
  private String highScoreName = null;              // the name to use for the high score
  static final Random randGen = new Random();       // package-private random number generator used for the entire package (i.e., repeatedly seeding with the same value produces the same randomness).
  static private int numClicks = 1;                        // Must be a positive integer; counts the number of clicks on circles since the last time the board was reset.
  /**
   * Counts the number of clicks on circles since the last time the board was reset.
   * @requires must be a positive integer; c
   */
  static private int numClicks = 1;

  /**
   * true iff the game is over (i.e., not running)
   */
  boolean gameOver = false;
  /**
   * An instance of the SGE GUI.
   */
@@ -254,6 +269,9 @@ public class SameGameTris extends GUI implements ActionListener, ItemListener {
   * (i.e. every circle is surrounded by cleared circles or circles of a different color)
   */
  public boolean gameOverQ() {
    if (gameOver)
      return true;

    for (int xx = 0; xx < width; xx++)
      for (int yy = 0; yy < height; yy++) {
        if (!circles[xx][yy].isCleared()) {
@@ -275,7 +293,6 @@ public class SameGameTris extends GUI implements ActionListener, ItemListener {
   */
  @Override
  public void makeMove(int xx, int yy) {
    System.out.println(new Date()+": Moving to "+xx+", "+yy);
    circles[xx][yy].mouseEntered(null);  // pretend the mouse was pressed at location (xx,yy)
    Timer t = new Timer();
    TimerTask tt = new TimerTask() {
@@ -452,7 +469,6 @@ public class SameGameTris extends GUI implements ActionListener, ItemListener {
   * As {@link #numClicks} gets larger, circles come more often and drop faster.
   */
  public void restartTetrising() {
    System.out.println("Restarting tetrising: ");
    // cancel the old schedules
    cancelTetrisingSchedules();

@@ -492,6 +508,9 @@ public class SameGameTris extends GUI implements ActionListener, ItemListener {
    // cancel tetrising schedules
    numClicks = 1;  // reset the number of circle clicks in the system
    cancelTetrisingSchedules();

    // reset gameOver
    gameOver = false;
  }

  /*
@@ -519,11 +538,9 @@ public class SameGameTris extends GUI implements ActionListener, ItemListener {
  /*
   * Called to request a reshifting of the board (as necessary).
   *    This should happen if some circles are rendered "clear"ed
   * @return true iff the shift succeeded without the game ending,
   *     and false if the game ended as a result of the shift.
   */

  final boolean shiftCircles() {
  final void shiftCircles() {
    /* start at the bottom and move up ... all cleared circles are
     *    removed, with upper circles falling into their positions;
     *    if a column is totally empty, then its rightmost columns
@@ -533,40 +550,40 @@ public class SameGameTris extends GUI implements ActionListener, ItemListener {
    GUIlock.lock(); // acquire a lock

    try {
      // 1.  SHIFT VERTICALLY
      for (int xx = 0; xx < width; xx++) {
        int firstClr = height - 1;  // the lowest cleared entry in the column
        int firstFull =
            height - 1; // the lowest uncleared entry in the column that has not yet been processed
        boolean moveOn = false;      // set to true in order to move on to the next column
        while (!moveOn) {
          // find the lowest clear entry in the column (if it exists)
          try {
            while (!circles[xx][firstClr].isCleared())
              firstClr--;
          } catch (ArrayIndexOutOfBoundsException e) {
            moveOn = true;
            continue;  // i.e. no cleared circle found in this column --- go to the next column
          }

          if (firstFull > firstClr)
            firstFull = firstClr; // only move items "down" the column

          // find the lowest non-cleared entry in the column (if it exists)
          try {
            while (circles[xx][firstFull].isCleared())
              firstFull--;
          } catch (ArrayIndexOutOfBoundsException e) {
            moveOn = true;
            continue;  // i.e. the whole column is clear --- for now, go to the next column
          }

          moveCircle(circles[xx][firstFull], circles[xx][firstClr]);

          firstFull--;
          firstClr--; // iterate
        }
      }
//      // 1.  SHIFT VERTICALLY
//      for (int xx = 0; xx < width; xx++) {
//        int firstClr = height - 1;  // the lowest cleared entry in the column
//        int firstFull =
//            height - 1; // the lowest uncleared entry in the column that has not yet been processed
//        boolean moveOn = false;      // set to true in order to move on to the next column
//        while (!moveOn) {
//          // find the lowest clear entry in the column (if it exists)
//          try {
//            while (!circles[xx][firstClr].isCleared())
//              firstClr--;
//          } catch (ArrayIndexOutOfBoundsException e) {
//            moveOn = true;
//            continue;  // i.e. no cleared circle found in this column --- go to the next column
//          }
//
//          if (firstFull > firstClr)
//            firstFull = firstClr; // only move items "down" the column
//
//          // find the lowest non-cleared entry in the column (if it exists)
//          try {
//            while (circles[xx][firstFull].isCleared())
//              firstFull--;
//          } catch (ArrayIndexOutOfBoundsException e) {
//            moveOn = true;
//            continue;  // i.e. the whole column is clear --- for now, go to the next column
//          }
//
//          moveCircle(circles[xx][firstFull], circles[xx][firstClr]);
//
//          firstFull--;
//          firstClr--; // iterate
//        }
//      }

      // 2.  SHIFT HORIZONTALLY
      // Check to see if any column is now empty
@@ -595,13 +612,10 @@ public class SameGameTris extends GUI implements ActionListener, ItemListener {
      // This happens if every circle is surrounded by cleared circles or circles of a different color
      if (gameOverQ()) {
        doGameOver("exhausted all circles"); // all done
        return false;
      }
    } finally {
      GUIlock.unlock(); // release the circles for other processes
    }

    return true;
  }

  /**
@@ -610,10 +624,10 @@ public class SameGameTris extends GUI implements ActionListener, ItemListener {
   * @param feedback Some string to present to the user; typically the reason that the game is over.
   */
  private void doGameOver(String feedback) {
    // close out other threads
    // close out other threads and variables
    gameOver = true;
    cancelTetrisingSchedules(); // cancel Tetrising threads
    stopBrain();                // stop the thinking Brain
    System.out.println("Game over, man!");

    // check the high score
    int score = Integer.parseInt(totalPoints.getText());
@@ -642,9 +656,22 @@ public class SameGameTris extends GUI implements ActionListener, ItemListener {
    }
    _showMessage(null, "Current high scores:\n" + hs.display());

    // i.e. time for a new game
    cleanUp();
    setupGUI();
//    // cleanup
//    cleanUp();
//    setupGUI();

    // "that's all folks"
    System.exit(0);
  }

  /**
   * Do a task in the future.
   * @param task The task to complete.
   * @param whenMS How many milliseconds in the future to do the task.
   */
  private void _doInFuture(TimerTask task, long whenMS) {
    Timer timer = new Timer();
    timer.schedule(task, whenMS);
  }

  /**
@@ -727,10 +754,11 @@ public class SameGameTris extends GUI implements ActionListener, ItemListener {
   * Stops the Brain that makes move.
   */
  private void stopBrain() {
    if (theBrain != null)
    if (theBrain != null) {
      theBrain.allDone();
      brainFuture.cancel(true);
    }
  }

  /**
   *   Handles the menu checkBox
+167 −167
Original line number Diff line number Diff line
@@ -51,7 +51,8 @@ class SelfAwareCircle extends Component implements MouseListener, SelfAwareListe
		/*
		 * the circle is cleared (i.e. background color)
		 */
		clear}
		clear
	}

	// CONSTRUCTORS

@@ -144,7 +145,8 @@ class SelfAwareCircle extends Component implements MouseListener, SelfAwareListe
	}

	// ... Mouse methods
		public void mouseClicked(MouseEvent e) {}
	public void mouseClicked(MouseEvent e) {
	}

	/*
	 * Highlights the button by changing its icon and firing off an event
@@ -199,7 +201,6 @@ class SelfAwareCircle extends Component implements MouseListener, SelfAwareListe
	 * The mouse button was released.
	 */
	public void mouseReleased(MouseEvent e) {
		System.out.println("Released mouse:"+Thread.currentThread().getName());
		_highlightButton(Visibility.clear);

		// register the score
@@ -208,15 +209,14 @@ class SelfAwareCircle extends Component implements MouseListener, SelfAwareListe
						sameGameTrisGUI.score(SelfAwareCircle.getRegionLength(), getColor())));

		// request that the board be shifted appropriately
			if (sameGameTrisGUI.shiftCircles()) { // if shifting concluded without ending the game
		sameGameTrisGUI.shiftCircles();

		// update Tetrising
		sameGameTrisGUI.updateNumClicks();
				if (!sameGameTrisGUI.isTetrisingQ())
		if (!sameGameTrisGUI.gameOverQ())
			sameGameTrisGUI.restartTetrising();
	}

		}

	// ... event methods
	public synchronized void addSelfAwareListener(SelfAwareListener l) {
		_listeners.add(l);