| 1 | // Copyright 2004-2007 Jean-Francois Poilpret |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package net.sourceforge.hiveboard.util; |
| 16 | |
| 17 | import java.util.Set; |
| 18 | |
| 19 | import net.sourceforge.hiveboard.Board; |
| 20 | |
| 21 | public abstract class AbstractTokenStrategy implements TokenStrategy |
| 22 | { |
| 23 | // Returns -1 if no change occurred in board writer, else returns the new |
| 24 | // writer (or 0 for no writer at all) |
| 25 | public int updateWriter(Board board) |
| 26 | { |
| 27 | int current = board.getWriter(); |
| 28 | int writer = current; |
| 29 | switch (board.getPresents().size()) |
| 30 | { |
| 31 | case 0: |
| 32 | writer = 0; |
| 33 | break; |
| 34 | |
| 35 | case 1: |
| 36 | int present = board.getPresents().iterator().next(); |
| 37 | if (writer != present) |
| 38 | { |
| 39 | writer = updateWriterOnePresent(present); |
| 40 | } |
| 41 | break; |
| 42 | |
| 43 | default: |
| 44 | // If no writer left, need to set a new writer |
| 45 | Set<Integer> presents = board.getPresents(); |
| 46 | if (!presents.contains(writer)) |
| 47 | { |
| 48 | writer = updateWriterSeveralPresents(board.getInitiator(), board.getPresents()); |
| 49 | } |
| 50 | break; |
| 51 | } |
| 52 | board.setWriter(writer); |
| 53 | return (writer == current ? -1 : writer); |
| 54 | } |
| 55 | |
| 56 | abstract protected int updateWriterOnePresent(int present); |
| 57 | abstract protected int updateWriterSeveralPresents(int initiator, Set<Integer> presents); |
| 58 | |
| 59 | public String canGiveToken(Board board, int who) |
| 60 | { |
| 61 | if (canGiveToken(board.getWriter(), board.getInitiator(), who)) |
| 62 | { |
| 63 | return null; |
| 64 | } |
| 65 | else |
| 66 | { |
| 67 | return getGiveTokenError(); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | abstract protected boolean canGiveToken(int current, int initiator, int who); |
| 72 | abstract protected String getGiveTokenError(); |
| 73 | } |