Download Extending Java for High-Level Web Service Construction
Transcript
·
50
Christensen, Møller, and Schwartzbach
public class Game extends Session {
public void main() {
// ask for number of cards
int howmany;
do {
show wrap <[ body = welcome <[ atmost = images.length ]]);
howmany = Integer.parseInt(receive howmany );
} while (howmany < 1 || howmany > images.length);
// generate random permutation of cards
Card[] cards = new Card[howmany*2];
Random random = new Random();
for (int i = 0 ; i < howmany ; i++) {
for (int c = 0 ; c < 2 ; c++) {
int index;
do {
index = random.nextInt(howmany*2);
} while (cards[index] != null);
cards[index] = new Card(i);
}
}
// play the game
int pairsleft = howmany;
int moves = 0;
show makeCardTable(cards);
while (pairsleft > 0) {
// first card picked
int firstcard = Integer.parseInt(receive submit );
cards[firstcard].status = 1;
show makeCardTable(cards);
// second card picked
int secondcard = Integer.parseInt(receive submit );
cards[secondcard].status = 1;
moves++;
// check match
if (cards[firstcard].value == cards[secondcard].value) {
cards[firstcard].status = 2;
cards[secondcard].status = 2;
if (--pairsleft > 0)
show makeCardTable(cards);
} else {
show makeCardTable(cards);
cards[firstcard].status = 0;
cards[secondcard].status = 0;
}
}
// done, show result
exit farewell <[ howmany = howmany, moves = moves ];
}
}
Fig. 14.
The main session of the Memory Game.