package com.tictactoe.client;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
import com.tictactoe.constants.TicTacToeConstants;
public class TicTacToeClient extends JApplet implements Runnable, TicTacToeConstants{
//Indicate whether the player has the turn
private boolean myTurn = false;
//Indicate the token for the player
private char myToken = ' ';
//Indicate the token for the other player
private char otherToken = ' ';
//Create and initialize cells
private Cell [][] cell = new Cell[3][3];
//Create and initialize a title label
private JLabel jlblTitle = new JLabel();
//Create and initialize a status label
private JLabel jlblStatus = new JLabel();
//Indicate selected row and column by the current move
private int rowSelected;
private int columnSelected;
//Input and output streams from/to server
private DataInputStream fromServer;
private DataOutputStream toServer;
//Continue to play?
private boolean continueToPlay = true;
//Wait for the player to mark a cell
private boolean waiting = true;
//Indicate if it runs as application
private boolean isStandAlone = true;
//Host name or ip
private String host = "localhost";
/**Initialize UI*/
public void init(){
//Panel p to hold cells
JPanel p = new JPanel();
p.setLayout(new GridLayout(3,3,0,0));
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
p.add(cell[i][j] = new Cell(i, j));
//Set properties for labels and borders for labels and panel
p.setBorder(new LineBorder(Color.black, 1));
jlblTitle.setHorizontalAlignment(JLabel.CENTER);
jlblTitle.setFont(new Font("SansSerif", Font.BOLD, 16));
jlblTitle.setBorder(new LineBorder(Color.black, 1));
jlblStatus.setBorder(new LineBorder(Color.black, 1));
//Place the panel and the labels to the applet
add(jlblTitle, BorderLayout.NORTH);
add(p, BorderLayout.CENTER);
add(jlblStatus, BorderLayout.SOUTH);
//Connect to the server
connectToServer();
}
private void connectToServer(){
try {
//Create a socket to connect to the server
Socket socket;
if(isStandAlone)
socket = new Socket(host, 8000);
else
socket = new Socket(getCodeBase().getHost(), 8000);
//Create an input stream to receive data from the server
fromServer = new DataInputStream(socket.getInputStream());
//Create an output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Control the game on a separate thread
Thread thread = new Thread(this);
thread.start();
}
@Override
public void run() {
try {
//Get notification from the server
int player = fromServer.readInt();
//Am I player 1 or 2?
if(player == PLAYER1){
myToken = 'X';
otherToken = 'O';
jlblTitle.setText("Player1 with token 'X'");
jlblStatus.setText("Waiting for player2 to join");
//Receive startup notification from the server
fromServer.readInt(); // Whatever read is ignored
//The other player has joined
jlblStatus.setText("Player2 has joined. I start first");
//It is my turn
myTurn = true;
}else if(player == PLAYER2){
myToken = 'O';
otherToken = 'X';
jlblTitle.setText("Player 2 with token 'O'");
jlblStatus.setText("Waiting for player1 to move");
}
//Continue to play
while(continueToPlay){
if(player == PLAYER1){
waitForPlayerAction(); //Wait for player 1 to move
sendMove(); //Send the move to the server
receiveInfoFromServer(); //Receive info from the server
}else if(player == PLAYER2){
receiveInfoFromServer(); //Receive info from the server
waitForPlayerAction(); //Wait for player 2 to move
sendMove(); //Send the player2's move to the server
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**Wait for the player to mark a cell*/
private void waitForPlayerAction() throws InterruptedException{
while(waiting){
Thread.sleep(100);
}
waiting = true;
}
/**Send this player's move to the server*/
private void sendMove() throws IOException{
toServer.writeInt(rowSelected); //Send the selected row
toServer.writeInt(columnSelected); //Send the selected column
}
/**Receive info from the server*/
private void receiveInfoFromServer() throws IOException{
//Receive game status
int status = fromServer.readInt();
if(status == PLAYER1_WON){
//Player1 won, stop playing
continueToPlay = false;
if(myToken == 'X'){
jlblStatus.setText("I won!(X)");
}else if(myToken == 'O'){
jlblStatus.setText("Player1 (X) has won!");
receiveMove();
}
}else if(status == PLAYER2_WON){
//Player2 won, stop playing
continueToPlay = false;
if(myToken == 'O'){
jlblStatus.setText("I won!(O)");
}else if(myToken == 'X'){
jlblStatus.setText("Player2 (O) has won!");
receiveMove();
}
}else if(status == DRAW){
//No winner, game is over
continueToPlay = false;
jlblStatus.setText("Game is over, no winner!");
if(myToken == 'O'){
receiveMove();
}
}else{
receiveMove();
jlblStatus.setText("My turn");
myTurn = true; // It is my turn
}
}
private void receiveMove() throws IOException{
//Get the other player's move
int row = fromServer.readInt();
int column = fromServer.readInt();
cell[row][column].setToken(otherToken);
}
//An inner class for a cell
public class Cell extends JPanel{
//Indicate the row and column of this cell in the board
private int row;
private int column;
//Token used for this cell
private char token = ' ';
public Cell(int row, int column){
this.row = row;
this.column = column;
setBorder(new LineBorder(Color.black, 1)); //Set cell's border
addMouseListener(new ClickListener()); //Register listener
}
/**Return token*/
public char getToken(){
return token;
}
/**Set a new token*/
public void setToken(char c){
token = c;
repaint();
}
/**Paint the cell*/
protected void paintComponent(Graphics g){
super.paintComponent(g);
if(token == 'X'){
g.drawLine(10, 10, getWidth() - 10, getHeight() - 10);
g.drawLine(getWidth() - 10, 10, 10, getHeight() - 10);
}else if(token == 'O'){
g.drawOval(10, 10, getWidth() - 20, getHeight() - 20);
}
}
private class ClickListener extends MouseAdapter{
public void mouseClicked(MouseEvent e){
//If cell is not occupied and the player has the turn
if((token == ' ') && myTurn){
setToken(myToken); //Set the player's token in the cell
myTurn = false;
rowSelected = row;
columnSelected = column;
jlblStatus.setText("Waiting for the other player to move");
waiting = false; //Just completed a successful move
}
}
}
}
}
分布式井字游戏(java后端和用于测试的java客户端).zip
版权申诉
95 浏览量
2023-07-19
09:57:39
上传
评论
收藏 8KB ZIP 举报
白话机器学习
- 粉丝: 8762
- 资源: 7682
最新资源
- 基于图像的三维模型重建C++源代码+文档说明(高分课程设计)
- 基于聚焦法的工件立体测量方案,根据数据进行三维重建 使用HALCON处理图像,MATLAB拟合数据+源代码+数据集+效果图
- 锄战三国村 修改:货币使用不减 v1.10(2) 原创 (中文).apk
- 基于python实现的单目双目视觉三维重建+源代码+图像图片(高分课程设计)
- 基于C+++OPENCV的全景图像拼接源码(课程设计)
- 基于Python+OpenCV对多张图片进行全景图像拼接,消除鬼影,消除裂缝+源代码+文档说明+界面截图(高分课程设计)
- 基于C++实现的全景图像拼接源码(课程设计)
- 基于SIFT特征点提取和RASIC算法实现全景图像拼接python源码+文档说明+界面截图+详细注释(95分以上课程大作业)
- 基于matlab实现眼部判别的疲劳检测系统+源代码+全部数据+文档说明+详细注释+使用说明+截图(高分课程设计)
- 基于Matlab的异常姿势识别系统+源代码+全部数据+文档说明+详细注释+使用说明+截图(高分课程设计)
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈