├── .gitignore ├── Code-Game ├── client.py ├── server.py └── tic_tac_toe.py ├── Docs └── TicTacToe CN - Abstract.pdf ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ -------------------------------------------------------------------------------- /Code-Game/client.py: -------------------------------------------------------------------------------- 1 | import socket # for networking 2 | import pickle # for sending/receiving objects 3 | 4 | # import the game 5 | from tic_tac_toe import TicTacToe 6 | 7 | HOST = '127.0.0.1' # the server's IP address 8 | PORT = 12783 # the port we're connecting to 9 | 10 | # connect to the host 11 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 12 | s.connect((HOST, PORT)) 13 | print(f"\nConnected to {s.getsockname()}!") 14 | 15 | # set up the game 16 | player_o = TicTacToe("O") 17 | 18 | # allow the player to suggest playing again 19 | rematch = True 20 | 21 | while rematch == True: 22 | # a header for an intense tic-tac-toe match! 23 | print(f"\n\n T I C - T A C - T O E ") 24 | 25 | # draw the grid 26 | player_o.draw_grid() 27 | 28 | # host goes first, client receives first 29 | print(f"\nWaiting for other player...") 30 | x_symbol_list = s.recv(1024) 31 | x_symbol_list = pickle.loads(x_symbol_list) 32 | player_o.update_symbol_list(x_symbol_list) 33 | 34 | # the rest is in a loop; if either player has won, it exits 35 | while player_o.did_win("O") == False and player_o.did_win("X") == False and player_o.is_draw() == False: 36 | # draw grid, ask for coordinate 37 | print(f"\n Your turn!") 38 | player_o.draw_grid() 39 | player_coord = input(f"Enter coordinate: ") 40 | player_o.edit_square(player_coord) 41 | 42 | # draw grid again 43 | player_o.draw_grid() 44 | 45 | # pickle the symbol list and send it 46 | o_symbol_list = pickle.dumps(player_o.symbol_list) 47 | s.send(o_symbol_list) 48 | 49 | # if the player won with the last move or it's a draw, exit the loop 50 | if player_o.did_win("O") == True or player_o.is_draw() == True: 51 | break 52 | 53 | # wait to receive the symbol list and update it 54 | print(f"\nWaiting for other player...") 55 | x_symbol_list = s.recv(1024) 56 | x_symbol_list = pickle.loads(x_symbol_list) 57 | player_o.update_symbol_list(x_symbol_list) 58 | 59 | # end game messages 60 | if player_o.did_win("O") == True: 61 | print(f"Congrats, you won!") 62 | elif player_o.is_draw() == True: 63 | print(f"It's a draw!") 64 | else: 65 | print(f"Sorry, the host won.") 66 | 67 | # host is being asked for a rematch, awaiting response 68 | print(f"\nWaiting for host...") 69 | host_response = s.recv(1024) 70 | host_response = pickle.loads(host_response) 71 | client_response = "N" 72 | 73 | # if the host wants a rematch, then the client is asked 74 | if host_response == "Y": 75 | print(f"\nThe host would like a rematch!") 76 | client_response = input("Rematch? (Y/N): ") 77 | client_response = client_response.capitalize() 78 | temp_client_resp = client_response 79 | 80 | # let the host know what the client decided 81 | client_response = pickle.dumps(client_response) 82 | s.send(client_response) 83 | 84 | # if the client wants a rematch, restart the game 85 | if temp_client_resp == "Y": 86 | player_o.restart() 87 | 88 | # if the client said no, then no rematch 89 | else: 90 | rematch = False 91 | 92 | # if the host said no, then no rematch 93 | else: 94 | print(f"\nThe host does not want a rematch.") 95 | rematch = False 96 | 97 | spacer = input(f"\nThank you for playing!\nPress enter to quit...\n") 98 | 99 | s.close() -------------------------------------------------------------------------------- /Code-Game/server.py: -------------------------------------------------------------------------------- 1 | import socket # for networking 2 | import pickle # for sending/receiving objects 3 | 4 | # import the game 5 | from tic_tac_toe import TicTacToe 6 | 7 | HOST = '127.0.0.1' # this address is the "local host" 8 | PORT = 12783 # port to listen on for clients 9 | 10 | # set up the server 11 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 12 | s.bind((HOST, PORT)) 13 | s.listen(5) 14 | 15 | # accept a connection from the client 16 | client_socket, client_address = s.accept() 17 | print(f"\nConnnected to {client_address}!") 18 | 19 | # set up the game 20 | player_x = TicTacToe("X") 21 | 22 | # allow the player to suggest playing again 23 | rematch = True 24 | 25 | while rematch == True: 26 | # a header for an intense tic-tac-toe match! 27 | print(f"\n\n T I C - T A C - T O E ") 28 | 29 | # the rest is in a loop; if either player has won, it exits 30 | while player_x.did_win("X") == False and player_x.did_win("O") == False and player_x.is_draw() == False: 31 | # draw grid, ask for coordinate 32 | print(f"\n Your turn!") 33 | player_x.draw_grid() 34 | player_coord = input(f"Enter coordinate: ") 35 | player_x.edit_square(player_coord) 36 | 37 | # draw the grid again 38 | player_x.draw_grid() 39 | 40 | # pickle the symbol list and send it 41 | x_symbol_list = pickle.dumps(player_x.symbol_list) 42 | client_socket.send(x_symbol_list) 43 | 44 | # if the player won with the last move or it's a draw, exit the loop 45 | if player_x.did_win("X") == True or player_x.is_draw() == True: 46 | break 47 | 48 | # wait to receive the symbol list and update it 49 | print(f"\nWaiting for other player...") 50 | o_symbol_list = client_socket.recv(1024) 51 | o_symbol_list = pickle.loads(o_symbol_list) 52 | player_x.update_symbol_list(o_symbol_list) 53 | 54 | # end game messages 55 | if player_x.did_win("X") == True: 56 | print(f"Congrats, you won!") 57 | elif player_x.is_draw() == True: 58 | print(f"It's a draw!") 59 | else: 60 | print(f"Sorry, the client won.") 61 | 62 | # ask for a rematch 63 | host_response = input(f"\nRematch? (Y/N): ") 64 | host_response = host_response.capitalize() 65 | temp_host_resp = host_response 66 | client_response = "" 67 | 68 | # pickle response and send it to the client 69 | host_response = pickle.dumps(host_response) 70 | client_socket.send(host_response) 71 | 72 | # if the host doesn't want a rematch, we're done here 73 | if temp_host_resp == "N": 74 | rematch = False 75 | 76 | # if the host does want a rematch, we ask the client for their opinion 77 | else: 78 | # receive client's response 79 | print(f"Waiting for client response...") 80 | client_response = client_socket.recv(1024) 81 | client_response = pickle.loads(client_response) 82 | 83 | # if the client doesn't want a rematch, exit the loop 84 | if client_response == "N": 85 | print(f"\nThe client does not want a rematch.") 86 | rematch = False 87 | 88 | # if both the host and client want a rematch, restart the game 89 | else: 90 | player_x.restart() 91 | 92 | spacer = input(f"\nThank you for playing!\nPress enter to quit...\n") 93 | 94 | client_socket.close() -------------------------------------------------------------------------------- /Code-Game/tic_tac_toe.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tic Tac Toe 3 | """ 4 | 5 | class TicTacToe(): 6 | 7 | def __init__(self, player_symbol): 8 | # initialize the list of symbols 9 | self.symbol_list = [] 10 | 11 | # defines all nine symbols; all start off as blank 12 | for i in range(9): 13 | self.symbol_list.append(" ") 14 | 15 | # initializes the player symbol 16 | self.player_symbol = player_symbol 17 | 18 | 19 | def restart(self): 20 | # clears the grid 21 | for i in range(9): 22 | self.symbol_list[i] = " " 23 | 24 | 25 | def draw_grid(self): 26 | # display the column headers 27 | print("\n A B C\n") 28 | 29 | # display first row 30 | row_one = " 1 " + self.symbol_list[0] 31 | row_one += " ║ " + self.symbol_list[1] 32 | row_one += " ║ " + self.symbol_list[2] 33 | print(row_one) 34 | 35 | # display divider 36 | print(" ═══╬═══╬═══") 37 | 38 | # display second row 39 | row_two = " 2 " + self.symbol_list[3] 40 | row_two += " ║ " + self.symbol_list[4] 41 | row_two += " ║ " + self.symbol_list[5] 42 | print(row_two) 43 | 44 | # display divider 45 | print(" ═══╬═══╬═══") 46 | 47 | # display third and last row 48 | row_three = " 3 " + self.symbol_list[6] 49 | row_three += " ║ " + self.symbol_list[7] 50 | row_three += " ║ " + self.symbol_list[8] 51 | print(row_three, "\n") 52 | 53 | 54 | def edit_square(self, grid_coord): 55 | # swamps coordinates such as "1A" to "A1" 56 | if grid_coord[0].isdigit(): 57 | grid_coord = grid_coord[1] + grid_coord[0] 58 | 59 | # divides the coordinate 60 | col = grid_coord[0].capitalize() 61 | row = grid_coord[1] 62 | 63 | # converts "A1" to 0, "C3" to 8, and so forth 64 | grid_index = 0 65 | 66 | if row == "1": 67 | if col == "A": 68 | grid_index = 0 69 | elif col == "B": 70 | grid_index = 1 71 | elif col == "C": 72 | grid_index = 2 73 | elif row == "2": 74 | if col == "A": 75 | grid_index = 3 76 | elif col == "B": 77 | grid_index = 4 78 | elif col == "C": 79 | grid_index = 5 80 | elif row == "3": 81 | if col == "A": 82 | grid_index = 6 83 | elif col == "B": 84 | grid_index = 7 85 | elif col == "C": 86 | grid_index = 8 87 | 88 | if self.symbol_list[grid_index] == " ": 89 | self.symbol_list[grid_index] = self.player_symbol 90 | 91 | 92 | def update_symbol_list(self, new_symbol_list): 93 | for i in range(9): 94 | self.symbol_list[i] = new_symbol_list[i] 95 | 96 | 97 | def did_win(self, player_symbol): 98 | # local variable to replace unweildy self.symbol_list 99 | g = [] 100 | for i in range(9): 101 | g.append(self.symbol_list[i]) 102 | 103 | # likewise to replace self.player_symbol 104 | sym = player_symbol 105 | 106 | # check top row 107 | if g[0] == sym and g[1] == sym and g[2] == sym: 108 | return True 109 | 110 | # check middle row 111 | elif g[3] == sym and g[4] == sym and g[5] == sym: 112 | return True 113 | 114 | # check bottom row 115 | elif g[6] == sym and g[7] == sym and g[8] == sym: 116 | return True 117 | 118 | # check left column 119 | elif g[0] == sym and g[3] == sym and g[6] == sym: 120 | return True 121 | 122 | # check middle column 123 | elif g[1] == sym and g[4] == sym and g[7] == sym: 124 | return True 125 | 126 | # check right column 127 | elif g[2] == sym and g[5] == sym and g[8] == sym: 128 | return True 129 | 130 | # check top-right to bottom-left 131 | elif g[2] == sym and g[4] == sym and g[6] == sym: 132 | return True 133 | 134 | # check top-left to bottom-right 135 | elif g[0] == sym and g[4] == sym and g[8] == sym: 136 | return True 137 | 138 | # didn't win... yet! 139 | return False 140 | 141 | 142 | def is_draw(self): 143 | # see if all the spaces are used up 144 | num_blanks = 0 145 | for i in range(9): 146 | if self.symbol_list[i] == " ": 147 | num_blanks += 1 148 | 149 | # if the player didn't win and no spaces are left, it's a draw 150 | if self.did_win(self.player_symbol) == False and num_blanks == 0: 151 | return True 152 | else: 153 | return False 154 | -------------------------------------------------------------------------------- /Docs/TicTacToe CN - Abstract.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Suvoo/TicTacToe-Using-Socket-Server/af21a5f5696f06798b2bbe10ba1fa012d39271fd/Docs/TicTacToe CN - Abstract.pdf -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TicTacToe using Socket Server 2 | This is a project for the class : 18CSC302J - Computer Networks by Dr. S.Babu 3 | 4 | #### Contributors 5 | * Suvodeep Sinha RA1911003010108 6 | * Vedant Singh RA1911003010097 7 | * Harshit Singh RA1911003010096 8 | 9 | 10 | ## Overview 11 | 12 | This is a simple game of tic-tac-toe developed in Python. It allows two players to play with one another on different command lines through networking. The server starts the game by *first* running `server.py`, waiting for the client to connect by *then* running `client.py`. Once their connected, the game itself starts. 13 | 14 | The server starts as "X" and goes first, and the client is "O." The players choose the square they would like to use with coordinates; both "A1" and "1A" would be accepted, for example. The game proceeds, with the players taking turns, until one wins or the game is a draw. The host, then the client, is asked whether they'd like a rematch. If both agree, the game starts anew. 15 | 16 | Example of a turn: 17 | 18 | ``` 19 | Your turn! 20 | 21 | A B C 22 | 23 | 1 ║ ║ X 24 | ═══╬═══╬═══ 25 | 2 ║ O ║ 26 | ═══╬═══╬═══ 27 | 3 ║ ║ 28 | 29 | Enter coordinate: 30 | ``` 31 | ## Network Communication 32 | 33 | We used a server/client network architecture for this project using TCP (Transmission Control Protocol), and we used port 12783. The messages were sent back and forth between the server and the client thanks to the pickle module, which converts any object (in this case, a string list storing the nine squares of a tic-tac-toe grid) into a byte stream to be sent and back into an object to be read. 34 | ## Demo 35 | ![image](https://user-images.githubusercontent.com/52796258/136496822-268fc91a-4826-4abb-9a13-9076117c3063.png) 36 | 37 | ## Development Environment 38 | 39 | * Visual Studio Code 40 | * Python (3.9.4) 64-bit 41 | * Git / GitHub 42 | * Python: Socket and Pickle modules 43 | 44 | --------------------------------------------------------------------------------