我的任务是编写一个简单的游戏,模拟两名玩家接连进行 1-3 场比赛,直到牌堆消失。我设法让计算机选择随机匹配的值,但现在我想更进一步,让人类玩游戏。这是我已经拥有的:http: //paste.pocoo.org/show/201761/
类 Player 是一个电脑玩家,而 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;
}
}