我有一个任务,写一个简单的游戏,模拟两个玩家一个接一个地玩1-3场比赛,直到堆不见了。我设法为计算机选择随机匹配的值,但现在我想进一步让人类玩这个游戏。这是我已经有:http://paste.pocoo.org/show/201761/控制线程流
类播放器是一个电脑播放器,和PlayerMan应该是人类。问题是,PlayerMan的这个线程应该等到合适的匹配值给出,但我不能使它以这种方式工作。逻辑如下:线程运行,直到匹配等于零。如果在调用函数pickMatches()时玩家号码正确。在减少表上的匹配数之后,线程应该等待,并且应该通知另一个线程。我知道我必须使用wait()和notify(),但是我不能把它们放在正确的位置。 类共享保持当前玩家的价值,以及比赛的数量。
public void suspendThread() {
suspended = true;
}
public void resumeThread() {
suspended = false;
}
@Override
public void run(){
int matches=1;
int which = 0;
int tmp=0;
Shared data = this.selectData();
String name = this.returnName();
int number = this.getNumber();
while(data.getMatches() != 0){
while(!suspended){
try{
which = data.getCurrent();
if(number == which){
matches = pickMatches();
tmp = data.getMatches() - matches;
data.setMatches(tmp, number);
if(data.getMatches() == 0){
System.out.println(" "+
name+" takes "+matches+" matches.");
System.out.println("Winner is player: "+name);
stop();
}
System.out.println(" "+
name+" takes "+matches+" matches.");
if(number != 0){
data.setCurrent(0);
}
else{
data.setCurrent(1);
}
}
this.suspendThread();
notifyAll();
wait();
}catch(InterruptedException exc) {}
}
}
}
@Override
synchronized public int pickMatches(){
Scanner scanner = new Scanner(System.in);
int n = 0;
Shared data = this.selectData();
System.out.println("Choose amount of matches (from 1 to 3): ");
if(data.getMatches() == 1){
System.out.println("There's only 1 match left !");
while(n != 1){
n = scanner.nextInt();
}
}
else{
do{
n = scanner.nextInt();
}
while(n <= 1 && n >= 3);
}
return n;
}
}
@owca太多的代码!尝试使其更符合Short Self-Contained Compilable Example(sscce):http://mindprod.com/jgloss/sscce.html – Kiril 2010-04-14 14:19:43