Guest User

Untitled

a guest
Jul 17th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.65 KB | None | 0 0
  1. import java.awt.BasicStroke;
  2. import java.awt.Color;
  3. import java.awt.Dimension;
  4. import java.awt.Font;
  5. import java.awt.Graphics;
  6. import java.awt.Graphics2D;
  7. import java.awt.RenderingHints;
  8. import java.awt.Toolkit;
  9. import java.awt.event.MouseEvent;
  10. import java.awt.event.MouseListener;
  11. import java.awt.image.BufferedImage;
  12. import java.io.DataInputStream;
  13. import java.io.DataOutputStream;
  14. import java.io.IOException;
  15. import java.net.InetAddress;
  16. import java.net.ServerSocket;
  17. import java.net.Socket;
  18. import java.util.Scanner;
  19.  
  20. import javax.imageio.ImageIO;
  21. import javax.swing.JFrame;
  22. import javax.swing.JPanel;
  23.  
  24. public class TicTacToe implements Runnable {
  25.  
  26. private String ip = "localhost";
  27. private int port = 22222;
  28. private Scanner scanner = new Scanner(System.in);
  29. private JFrame frame;
  30. private final int WIDTH = 506;
  31. private final int HEIGHT = 527;
  32. private Thread thread;
  33.  
  34. private Painter painter;
  35. private Socket socket;
  36. private DataOutputStream dos;
  37. private DataInputStream dis;
  38.  
  39. private ServerSocket serverSocket;
  40.  
  41. private BufferedImage board;
  42. private BufferedImage redX;
  43. private BufferedImage blueX;
  44. private BufferedImage redCircle;
  45. private BufferedImage blueCircle;
  46.  
  47. private String[] spaces = new String[9];
  48.  
  49. private boolean yourTurn = false;
  50. private boolean circle = true;
  51. private boolean accepted = false;
  52. private boolean unableToCommunicateWithOpponent = false;
  53. private boolean won = false;
  54. private boolean enemyWon = false;
  55. private boolean tie = false;
  56.  
  57. private int lengthOfSpace = 160;
  58. private int errors = 0;
  59. private int firstSpot = -1;
  60. private int secondSpot = -1;
  61.  
  62. private Font font = new Font("Verdana", Font.BOLD, 32);
  63. private Font smallerFont = new Font("Verdana", Font.BOLD, 20);
  64. private Font largerFont = new Font("Verdana", Font.BOLD, 50);
  65.  
  66. private String waitingString = "Waiting for another player";
  67. private String unableToCommunicateWithOpponentString = "Unable to communicate with opponent.";
  68. private String wonString = "You won!";
  69. private String enemyWonString = "Opponent won!";
  70. private String tieString = "Game ended in a tie.";
  71.  
  72. private int[][] wins = new int[][] { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };
  73.  
  74. /**
  75. * <pre>
  76. * 0, 1, 2
  77. * 3, 4, 5
  78. * 6, 7, 8
  79. * </pre>
  80. */
  81.  
  82. public TicTacToe() {
  83. System.out.println("Please input the IP: ");
  84. ip = scanner.nextLine();
  85. System.out.println("Please input the port: ");
  86. port = scanner.nextInt();
  87. while (port < 1 || port > 65535) {
  88. System.out.println("The port you entered was invalid, please input another port: ");
  89. port = scanner.nextInt();
  90. }
  91.  
  92. loadImages();
  93.  
  94. painter = new Painter();
  95. painter.setPreferredSize(new Dimension(WIDTH, HEIGHT));
  96.  
  97. if (!connect()) initializeServer();
  98.  
  99. frame = new JFrame();
  100. frame.setTitle("Tic-Tac-Toe");
  101. frame.setContentPane(painter);
  102. frame.setSize(WIDTH, HEIGHT);
  103. frame.setLocationRelativeTo(null);
  104. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  105. frame.setResizable(false);
  106. frame.setVisible(true);
  107.  
  108. thread = new Thread(this, "TicTacToe");
  109. thread.start();
  110. }
  111.  
  112. public void run() {
  113. while (true) {
  114. tick();
  115. painter.repaint();
  116.  
  117. if (!circle && !accepted) {
  118. listenForServerRequest();
  119. }
  120.  
  121. }
  122. }
  123.  
  124. private void render(Graphics g) {
  125. g.drawImage(board, 0, 0, null);
  126. if (unableToCommunicateWithOpponent) {
  127. g.setColor(Color.RED);
  128. g.setFont(smallerFont);
  129. Graphics2D g2 = (Graphics2D) g;
  130. g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
  131. int stringWidth = g2.getFontMetrics().stringWidth(unableToCommunicateWithOpponentString);
  132. g.drawString(unableToCommunicateWithOpponentString, WIDTH / 2 - stringWidth / 2, HEIGHT / 2);
  133. return;
  134. }
  135.  
  136. if (accepted) {
  137. for (int i = 0; i < spaces.length; i++) {
  138. if (spaces[i] != null) {
  139. if (spaces[i].equals("X")) {
  140. if (circle) {
  141. g.drawImage(redX, (i % 3) * lengthOfSpace + 10 * (i % 3), (int) (i / 3) * lengthOfSpace + 10 * (int) (i / 3), null);
  142. } else {
  143. g.drawImage(blueX, (i % 3) * lengthOfSpace + 10 * (i % 3), (int) (i / 3) * lengthOfSpace + 10 * (int) (i / 3), null);
  144. }
  145. } else if (spaces[i].equals("O")) {
  146. if (circle) {
  147. g.drawImage(blueCircle, (i % 3) * lengthOfSpace + 10 * (i % 3), (int) (i / 3) * lengthOfSpace + 10 * (int) (i / 3), null);
  148. } else {
  149. g.drawImage(redCircle, (i % 3) * lengthOfSpace + 10 * (i % 3), (int) (i / 3) * lengthOfSpace + 10 * (int) (i / 3), null);
  150. }
  151. }
  152. }
  153. }
  154. if (won || enemyWon) {
  155. Graphics2D g2 = (Graphics2D) g;
  156. g2.setStroke(new BasicStroke(10));
  157. g.setColor(Color.BLACK);
  158. g.drawLine(firstSpot % 3 * lengthOfSpace + 10 * firstSpot % 3 + lengthOfSpace / 2, (int) (firstSpot / 3) * lengthOfSpace + 10 * (int) (firstSpot / 3) + lengthOfSpace / 2, secondSpot % 3 * lengthOfSpace + 10 * secondSpot % 3 + lengthOfSpace / 2, (int) (secondSpot / 3) * lengthOfSpace + 10 * (int) (secondSpot / 3) + lengthOfSpace / 2);
  159.  
  160. g.setColor(Color.RED);
  161. g.setFont(largerFont);
  162. if (won) {
  163. int stringWidth = g2.getFontMetrics().stringWidth(wonString);
  164. g.drawString(wonString, WIDTH / 2 - stringWidth / 2, HEIGHT / 2);
  165. } else if (enemyWon) {
  166. int stringWidth = g2.getFontMetrics().stringWidth(enemyWonString);
  167. g.drawString(enemyWonString, WIDTH / 2 - stringWidth / 2, HEIGHT / 2);
  168. }
  169. }
  170. if (tie) {
  171. Graphics2D g2 = (Graphics2D) g;
  172. g.setColor(Color.BLACK);
  173. g.setFont(largerFont);
  174. int stringWidth = g2.getFontMetrics().stringWidth(tieString);
  175. g.drawString(tieString, WIDTH / 2 - stringWidth / 2, HEIGHT / 2);
  176. }
  177. } else {
  178. g.setColor(Color.RED);
  179. g.setFont(font);
  180. Graphics2D g2 = (Graphics2D) g;
  181. g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
  182. int stringWidth = g2.getFontMetrics().stringWidth(waitingString);
  183. g.drawString(waitingString, WIDTH / 2 - stringWidth / 2, HEIGHT / 2);
  184. }
  185.  
  186. }
  187.  
  188. private void tick() {
  189. if (errors >= 10) unableToCommunicateWithOpponent = true;
  190.  
  191. if (!yourTurn && !unableToCommunicateWithOpponent) {
  192. try {
  193. int space = dis.readInt();
  194. if (circle) spaces[space] = "X";
  195. else spaces[space] = "O";
  196. checkForEnemyWin();
  197. checkForTie();
  198. yourTurn = true;
  199. } catch (IOException e) {
  200. e.printStackTrace();
  201. errors++;
  202. }
  203. }
  204. }
  205.  
  206. private void checkForWin() {
  207. for (int i = 0; i < wins.length; i++) {
  208. if (circle) {
  209. if (spaces[wins[i][0]] == "O" && spaces[wins[i][1]] == "O" && spaces[wins[i][2]] == "O") {
  210. firstSpot = wins[i][0];
  211. secondSpot = wins[i][2];
  212. won = true;
  213. }
  214. } else {
  215. if (spaces[wins[i][0]] == "X" && spaces[wins[i][1]] == "X" && spaces[wins[i][2]] == "X") {
  216. firstSpot = wins[i][0];
  217. secondSpot = wins[i][2];
  218. won = true;
  219. }
  220. }
  221. }
  222. }
  223.  
  224. private void checkForEnemyWin() {
  225. for (int i = 0; i < wins.length; i++) {
  226. if (circle) {
  227. if (spaces[wins[i][0]] == "X" && spaces[wins[i][1]] == "X" && spaces[wins[i][2]] == "X") {
  228. firstSpot = wins[i][0];
  229. secondSpot = wins[i][2];
  230. enemyWon = true;
  231. }
  232. } else {
  233. if (spaces[wins[i][0]] == "O" && spaces[wins[i][1]] == "O" && spaces[wins[i][2]] == "O") {
  234. firstSpot = wins[i][0];
  235. secondSpot = wins[i][2];
  236. enemyWon = true;
  237. }
  238. }
  239. }
  240. }
  241.  
  242. private void checkForTie() {
  243. for (int i = 0; i < spaces.length; i++) {
  244. if (spaces[i] == null) {
  245. return;
  246. }
  247. }
  248. tie = true;
  249. }
  250.  
  251. private void listenForServerRequest() {
  252. Socket socket = null;
  253. try {
  254. socket = serverSocket.accept();
  255. dos = new DataOutputStream(socket.getOutputStream());
  256. dis = new DataInputStream(socket.getInputStream());
  257. accepted = true;
  258. System.out.println("CLIENT HAS REQUESTED TO JOIN, AND WE HAVE ACCEPTED");
  259. } catch (IOException e) {
  260. e.printStackTrace();
  261. }
  262. }
  263.  
  264. private boolean connect() {
  265. try {
  266. socket = new Socket(ip, port);
  267. dos = new DataOutputStream(socket.getOutputStream());
  268. dis = new DataInputStream(socket.getInputStream());
  269. accepted = true;
  270. } catch (IOException e) {
  271. System.out.println("Unable to connect to the address: " + ip + ":" + port + " | Starting a server");
  272. return false;
  273. }
  274. System.out.println("Successfully connected to the server.");
  275. return true;
  276. }
  277.  
  278. private void initializeServer() {
  279. try {
  280. serverSocket = new ServerSocket(port, 8, InetAddress.getByName(ip));
  281. } catch (Exception e) {
  282. e.printStackTrace();
  283. }
  284. yourTurn = true;
  285. circle = false;
  286. }
  287.  
  288. private void loadImages() {
  289. try {
  290. board = ImageIO.read(getClass().getResourceAsStream("board.png"));
  291. redX = ImageIO.read(getClass().getResourceAsStream("redX.png"));
  292. redCircle = ImageIO.read(getClass().getResourceAsStream("redCircle.png"));
  293. blueX = ImageIO.read(getClass().getResourceAsStream("blueX.png"));
  294. blueCircle = ImageIO.read(getClass().getResourceAsStream("blueCircle.png"));
  295. } catch (IOException e) {
  296. e.printStackTrace();
  297. }
  298. }
  299.  
  300. @SuppressWarnings("unused")
  301. public static void main(String[] args) {
  302. TicTacToe ticTacToe = new TicTacToe();
  303. }
  304.  
  305. private class Painter extends JPanel implements MouseListener {
  306. private static final long serialVersionUID = 1L;
  307.  
  308. public Painter() {
  309. setFocusable(true);
  310. requestFocus();
  311. setBackground(Color.WHITE);
  312. addMouseListener(this);
  313. }
  314.  
  315. @Override
  316. public void paintComponent(Graphics g) {
  317. super.paintComponent(g);
  318. render(g);
  319. }
  320.  
  321. @Override
  322. public void mouseClicked(MouseEvent e) {
  323. if (accepted) {
  324. if (yourTurn && !unableToCommunicateWithOpponent && !won && !enemyWon) {
  325. int x = e.getX() / lengthOfSpace;
  326. int y = e.getY() / lengthOfSpace;
  327. y *= 3;
  328. int position = x + y;
  329.  
  330. if (spaces[position] == null) {
  331. if (!circle) spaces[position] = "X";
  332. else spaces[position] = "O";
  333. yourTurn = false;
  334. repaint();
  335. Toolkit.getDefaultToolkit().sync();
  336.  
  337. try {
  338. dos.writeInt(position);
  339. dos.flush();
  340. } catch (IOException e1) {
  341. errors++;
  342. e1.printStackTrace();
  343. }
  344.  
  345. System.out.println("DATA WAS SENT");
  346. checkForWin();
  347. checkForTie();
  348.  
  349. }
  350. }
  351. }
  352. }
  353.  
  354. @Override
  355. public void mousePressed(MouseEvent e) {
  356.  
  357. }
  358.  
  359. @Override
  360. public void mouseReleased(MouseEvent e) {
  361.  
  362. }
  363.  
  364. @Override
  365. public void mouseEntered(MouseEvent e) {
  366.  
  367. }
  368.  
  369. @Override
  370. public void mouseExited(MouseEvent e) {
  371.  
  372. }
  373.  
  374. }
  375.  
  376. }
Add Comment
Please, Sign In to add comment