⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 c4canvas.java

📁 这是在网上的一个关于手机编程书籍中网络编程源代码,
💻 JAVA
字号:
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
import java.io.*;
import javax.microedition.media.*;
import javax.microedition.io.*;

public class C4Canvas extends GameCanvas implements Runnable {
  private Display  display;
  private boolean  sleeping;
  private long     frameDelay;
  private Image[]  piece = new Image[2];
  private Sprite   arrowSprite;
  private Player   legalPlayer;
  private Player   illegalPlayer;
  private Player   winPlayer;
  private Player   losePlayer;
  private C4State  gameState;
  private C4Client client;
  private C4Server server;
  private boolean  isServer;
  private String   status = "";
  private boolean  gameOver;
  private boolean  myMove;
  private int      curSlot;

  public C4Canvas(Display d, String peerType) {
    super(true);
    display = d;

    // Set the frame rate (10 fps)
    frameDelay = 100;

    // Remember the peer type
    isServer = peerType.equals("Server");
  }

  public void start() {
    // Set the canvas as the current screen
    display.setCurrent(this);

    // Initialize the piece images
    try {
      piece[0] = Image.createImage("/RedPiece.png");
      piece[1] = Image.createImage("/BluePiece.png");
    }
    catch (IOException e) {
      System.err.println("Failed loading images!");
    }

    // Initialize the arrow sprite
    try {
      // Create the arrow sprite
      arrowSprite = new Sprite(Image.createImage("/Arrow.png"), 18, 16);
      arrowSprite.setFrame(isServer ? 0 : 1);
    }
    catch (IOException e) {
      System.err.println("Failed loading images!");
    }

    // Initialize the wave players
    try {
      InputStream is = getClass().getResourceAsStream("Legal.wav");
      legalPlayer = Manager.createPlayer(is, "audio/X-wav");
      legalPlayer.prefetch();
      is = getClass().getResourceAsStream("Illegal.wav");
      illegalPlayer = Manager.createPlayer(is, "audio/X-wav");
      illegalPlayer.prefetch();
      is = getClass().getResourceAsStream("Win.wav");
      winPlayer = Manager.createPlayer(is, "audio/X-wav");
      winPlayer.prefetch();
      is = getClass().getResourceAsStream("Lose.wav");
      losePlayer = Manager.createPlayer(is, "audio/X-wav");
      losePlayer.prefetch();
    }
    catch (IOException ioe) {
    }
    catch (MediaException me) {
    }

    // Initialize the game variables
    gameOver = true;
    myMove = !isServer;  // client always goes first
    curSlot = 0;
    gameState = new C4State();

    // Start the networking service
    if (isServer) {
      server = new C4Server(this);
      server.start();
    }
    else {
      client = new C4Client(this);
      client.start();
    }

    // Start the animation thread
    sleeping = false;
    Thread t = new Thread(this);
    t.start();
  }
  
  public void stop() {
    // Close the wave players
    legalPlayer.close();
    illegalPlayer.close();
    winPlayer.close();
    losePlayer.close();

    // Stop the animation
    sleeping = true;
  }
  
  public void run() {
    Graphics g = getGraphics();
    
    // The main game loop
    while (!sleeping) {
      update();
      draw(g);
      try {
        Thread.sleep(frameDelay);
      }
      catch (InterruptedException ie) {}
    }
  }

  private void update() {
    // Check to see whether the game is being restarted
    if (gameOver) {
      int keyState = getKeyStates();
      if ((keyState & FIRE_PRESSED) != 0) {
        // Start a new game
        newGame();

        // Send a new game message to the other player
        if (isServer)
          server.sendMessage("NewGame");
        else
          client.sendMessage("NewGame");
      }

      // The game is over, so don't update anything
      return;
    }

    // Handle the left/right directional keys and the fire key
    if (!gameOver && myMove) {
      // Process user input to move the arrow and drop piece
      int keyState = getKeyStates();
      if ((keyState & LEFT_PRESSED) != 0) {
        if (--curSlot < 0)
          curSlot = 0;
      }
      else if ((keyState & RIGHT_PRESSED) != 0) {
        if (++curSlot > 6)
          curSlot = 6;
      }
      else if ((keyState & FIRE_PRESSED) != 0) {
        if (makeMove(isServer ? 0 : 1, curSlot)) {
          myMove = false;

          // Send the move message to the other player
          if (isServer)
            server.sendMessage(Integer.toString(curSlot));
          else
            client.sendMessage(Integer.toString(curSlot));
        }
      }

      // Update the arrow position
      arrowSprite.setPosition(
        getWidth() * (curSlot + 1) / 8 - arrowSprite.getWidth() / 2, 21);
    }
  }

  private void draw(Graphics g) {
    // Fill the background
    g.setColor(128, 128, 128); // gray
    g.fillRect(0, 0, getWidth(), getHeight());

    // Draw the status message
    g.setColor(0, 0, 0); // black
    g.setFont(Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM));
    g.drawString(status, getWidth() / 2, 2, Graphics.TOP | Graphics.HCENTER);

    if (!gameOver && myMove) {
      // Draw the arrow sprite
      arrowSprite.paint(g);
    }

    // Draw the pieces
    for (int i = 0; i < 7; i++)
      for (int j = 0; j < 6; j++)
      switch(gameState.board[i][j]) {
      case 0:
        g.drawImage(piece[0],
          (getWidth() * (i + 1)) / 8 - (piece[0].getWidth() / 2),
          ((getHeight() - 33) * (6 - j)) / 7 - (piece[0].getHeight() / 2) + 33,
          Graphics.TOP | Graphics.LEFT);
        break;

      case 1:
        g.drawImage(piece[1],
          (getWidth() * (i + 1)) / 8 - (piece[0].getWidth() / 2),
          ((getHeight() - 33) * (6 - j)) / 7 - (piece[1].getHeight() / 2) + 33,
          Graphics.TOP | Graphics.LEFT);
        break;

      default:
        g.setColor(255, 255, 255); // white
        g.fillArc((getWidth() * (i + 1)) / 8 - (piece[0].getWidth() / 2),
          ((getHeight() - 33) * (6 - j)) / 7 - (piece[0].getHeight() / 2) + 33,
          piece[0].getWidth(), piece[0].getHeight(), 0, 360);
        break;
      }

    // Flush the offscreen graphics buffer
    flushGraphics();
  }

  public void newGame() {
    // Initialize the game variables
    gameOver = false;
    curSlot = 0;
    gameState = new C4State();

    // Update the status message
    status = myMove ? "Your turn." : "Waiting for player's move...";
  }

  public void setStatus(String s) {
    // Set the status message
    status = s;
  }

  public void receiveMessage(String message) {
    if (gameOver) {
      // Check for a new game message
      if (message.equals("NewGame"))
        newGame();
    }
    else {
      if (!myMove) {
        // Attempt to receive a numeric move
        try {
          // Carry out the other player's move
          int slot = Integer.parseInt(message);
          if (slot >= 0 && slot <= 6) {
            if (makeMove(isServer ? 1 : 0, slot))
              myMove = true;
          }
        }
        catch (NumberFormatException nfe) {
        }
      }
    }
  }

  private boolean makeMove(int player, int slot) {
    // Drop the piece
    if (gameState.dropPiece(player, slot) == -1) {
      // Play a wave sound for an illegal move
      try {
        illegalPlayer.start();
      }
      catch (MediaException me) {
      }

      return false;
    }

    // Play a wave sound for a legal move
    try {
      legalPlayer.start();
    }
    catch (MediaException me) {
    }

    // See whether the game is over
    if (gameState.isWinner(player)) {
      if ((isServer && (player == 0)) || (!isServer && (player == 1))) {
        // Play a wave sound for winning the game
        try {
          winPlayer.start();
        }
        catch (MediaException me) {
        }

        status = "You won!";
      }
      else {
        // Play a wave sound for losing the game
        try {
          losePlayer.start();
        }
        catch (MediaException me) {
        }

        status = "You lost!";
      }

      gameOver = true;
    }
    else if (gameState.isTie()) {
      // Play a wave sound for tying the game
      try {
        losePlayer.start();
      }
      catch (MediaException me) {
      }

      status = "The game ended in a tie!";
      gameOver = true;
    }
    else {
      // Update the status message
      status = myMove ? "Waiting for other player..." : "Your turn.";
    }

    return true;
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -