8. วัตถุสิ่งของ

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 8-25  คลาส MemoryGame ไว้เล่นเกมจับคู่ทดสอบความจำ
import jlab.graphics.DWindow;
public class MemoryGame {
  private DWindow window;
  private Card[][] cards;
   
  public MemoryGame(int row, int col) {
    if ((row * col) % 2 != 0) throw new IllegalArgumentException();
    window = new DWindow(Card.WIDTH * col, Card.HEIGHT * row);
    cards = new Card[row][col];
    int[] numberPairs = new int[row * col];
    for (int i = 0; i < numberPairs.length; i++) // 1,1,2,2,3,3,...
      numberPairs[i] = 1 + i / 2;
    for (int i = 0; i < numberPairs.length / 2; i++) // สุ่มสลับ 
      swap(numberPairs, i, random(i+1, numberPairs.length-1));
    for (int i = 0, k = 0; i < row; i++) { //สร้างบัตรเก็บตามตำแหน่งต่างๆ 
      for (int j = 0; j < col; j++) {
        cards[i][j] = new Card(window, i, j, numberPairs[k++]);
        cards[i][j].hide();
      }
    }
  }
  public void begin() {
    int numUnmatched = cards.length * cards[0].length / 2;
    long startTime = System.currentTimeMillis();
    while (numUnmatched > 0) {
      Card c1 = waitForCardClicked(null); c1.show();
      Card c2 = waitForCardClicked(c1);   c2.show();
      window.sleep(500);
      if (c1.number() == c2.number()) {
        c1.matched(); c2.matched();
        numUnmatched--;
      } else {
        c1.hide(); c2.hide(); // ไม่ตรงกัน รีบซ่อนหมายเลข 
      }
    }
    window.clearBackground();
    long time = (System.currentTimeMillis() - startTime)/1000;
    window.drawString("คุณทำได้ใน  " + time+ "  วินาที",14,5,5);
  }
©2009 S.Prasitjutrakul