1 package erland.game.tetris;
2 /*
3 * Copyright (C) 2003 Erland Isaksson (erland_i@hotmail.com)
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 *
19 */
20
21 import java.util.Vector;
22
23 public class BlockFactory {
24 private static BlockFactory me = null;
25 private Object[] players;
26 private int[] playerBlockIndex;
27 private Vector blocks;
28
29 public static BlockFactory getInstance() {
30 if(me==null) {
31 me = new BlockFactory();
32 }
33 return me;
34 }
35
36 public BlockFactory() {
37 reset();
38 }
39
40 private int getPlayerIndex(Object player) {
41 for(int i=0;i<players.length;i++) {
42 if(player == players[i]) {
43 return i;
44 }
45 }
46 return addPlayer(player);
47 }
48 private int addPlayer(Object player) {
49 System.out.println("BlockFactory.addPlayer");
50 for(int i=0;i<players.length;i++) {
51 if(players[i] == null) {
52 players[i] = player;
53 playerBlockIndex[i]=0;
54 return i;
55 }
56 }
57 return -1;
58 }
59
60 /***
61 * Creates a new random block
62 * @return A new Block object
63 */
64 protected Block newBlock()
65 {
66 Block block;
67 switch((int)(Math.random()*7+1.0)) {
68 case 1:
69 block = new Block1();
70 break;
71 case 2:
72 block = new Block2();
73 break;
74 case 3:
75 block = new Block3();
76 break;
77 case 4:
78 block = new Block4();
79 break;
80 case 5:
81 block = new Block5();
82 break;
83 case 6:
84 block = new Block6();
85 break;
86 case 7:
87 default:
88 block = new Block7();
89 break;
90 }
91 return block;
92 }
93
94 public Block nextBlock(Object player) {
95 int i = getPlayerIndex(player);
96 if(i>=0) {
97 if(playerBlockIndex[i]>=blocks.size()) {
98 blocks.addElement(newBlock());
99 }
100 Block b = (Block) ((Block) blocks.elementAt(playerBlockIndex[i])).clone();
101 playerBlockIndex[i]++;
102 //System.out.println("player = " + i + ", block = " + (playerBlockIndex[i]-1) + ", block = " +b);
103 return b;
104 }else {
105 return null;
106 }
107 }
108 public void reset() {
109 System.out.println("BlockFactory.reset");
110 players = new Object[2];
111 playerBlockIndex = new int[2];
112 blocks = new Vector();
113 }
114 }