2023年12月14日 星期四

week13 UC

 期中作品製作

int boardSize = 15; 
int cellSize;       
int[][] board;      
int currentPlayer = 1; 
boolean gameStarted = false;

void setup() {
  size(600, 600);
  cellSize = width / boardSize;
  board = new int[boardSize][boardSize];
  drawStartScreen();
}

void draw() {
  background(255);
  if (gameStarted) {
    drawBoard();
    drawStones();
    if (checkWin()) {
      textSize(60);
      fill(0);
      textAlign(CENTER, CENTER);
      text("player " + currentPlayer + " win!", width / 2, height / 2);
    }
  } else {
    drawStartScreen();
  }
}

void drawStartScreen() {
  textAlign(CENTER, CENTER);
  textSize(32);
  fill(0);
  text("Game", width / 2, height / 2 - 50);
  textSize(20);
  text(" 'backgammon' ", width / 2, height / 2 + 50);

 
  rectMode(CENTER);
  fill(150);
  rect(width / 2, height / 2 + 100, 150, 50);
  fill(0);
  textSize(16);
  text("START", width / 2, height / 2 + 100);
}

void drawBoard() {
  for (int i = 0; i < boardSize; i++) {
    for (int j = 0; j < boardSize; j++) {
      fill(220, 180, 120); 
      stroke(0);
      rect(i * cellSize, j * cellSize, cellSize, cellSize);
    }
  }
}

void drawStones() {
  for (int i = 0; i < boardSize; i++) {
    for (int j = 0; j < boardSize; j++) {
      if (board[i][j] == 1) {
        fill(0); 
        ellipse(i * cellSize + cellSize / 2, j * cellSize + cellSize / 2, cellSize, cellSize);
      } else if (board[i][j] == 2) {
        fill(255);
        ellipse(i * cellSize + cellSize / 2, j * cellSize + cellSize / 2, cellSize, cellSize);
      }
    }
  }
}

void mousePressed() {
  if (!gameStarted && mouseX > width / 2 - 75 && mouseX < width / 2 + 75 && mouseY > height / 2 + 75 && mouseY < height / 2 + 125) {
    gameStarted = true;
  } else if (gameStarted) {
    int i = mouseX / cellSize;
    int j = mouseY / cellSize;

    if (isValidMove(i, j)) {
      board[i][j] = currentPlayer;
      if (checkWin()) {
        
        gameStarted = false;
      } else {
        currentPlayer = 3 - currentPlayer; 
      }
    }
  }
}

boolean isValidMove(int i, int j) {
 
  if (board[i][j] == 0) {
    return true;
  } else {
    return false;
  }
}

boolean checkWin() {
 
  for (int i = 0; i < boardSize; i++) {
    for (int j = 0; j < boardSize; j++) {
      if (board[i][j] != 0) {
        
        if (checkLine(i, j, 1, 0)) return true;
        if (checkLine(i, j, 0, 1)) return true;
        if (checkLine(i, j, 1, 1)) return true;
        if (checkLine(i, j, -1, 1)) return true;
      }
    }
  }
  return false;
}

boolean checkLine(int x, int y, int dx, int dy) {
  int count = 0;
  int player = board[x][y];
  for (int i = 0; i < 5; i++) {
    int newX = x + i * dx;
    int newY = y + i * dy;
    if (newX >= 0 && newX < boardSize && newY >= 0 && newY < boardSize && board[newX][newY] == player) {
      count++;
    }
  }
  return count == 5;
}

沒有留言:

張貼留言