Skip to content

atandritC/Net-Tic-Tac-Toe

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 

Repository files navigation

Net-Tic-Tac-Toe

Networked Tic-Tac-Toe via TCP/IP
A Java-based client-server application that enables two players to compete in classic Tic-Tac-Toe over any TCP/IP network — featuring real-time move synchronization, server-side game validation, and turn-based gameplay, all through a clean console interface.

Java TCP/IP Sockets Console UI License

🛠 Tech Stack

Core Language & Runtime

  • Java (JDK 8+) — Platform-independent, object-oriented implementation with robust networking libraries
  • java.net package — Native ServerSocket and Socket classes for reliable TCP communication

Networking Architecture

  • TCP/IP Sockets — Connection-oriented protocol ensuring ordered, error-checked delivery of moves
  • Blocking I/O model — Simple synchronous read/write flow ideal for turn-based game logic
  • Plain-text protocol — Human-readable move format (row,col) for easy debugging and extensibility

Game Logic & Validation

  • Server-authoritative design — All move validation, win detection, and state management handled server-side
  • 3×3 board representation — 2D char array with atomic updates and thread-safe access per client session
  • Win/draw detection — Efficient row/column/diagonal checks after each move with O(1) early termination

User Interface

  • Console-based CLI — Cross-platform terminal interface with clear board rendering and move prompts
  • Real-time feedback — Instant display of opponent moves, game status, and win/loss results

✨ Key Features

  • True Network Multiplayer — Play against anyone on your LAN or over the internet via IP address
  • Server-Authoritative Gameplay — All moves validated server-side to prevent cheating or invalid inputs
  • Real-Time Synchronization — Instant move propagation with turn enforcement and state consistency
  • Classic Rules Engine — Full implementation of traditional Tic-Tac-Toe win conditions (3-in-a-row)
  • Clean Console UI — Intuitive board display, move prompts, and game status updates in any terminal
  • Graceful Connection Handling — Detects client disconnects and notifies remaining player appropriately
  • Zero External Dependencies — Pure Java standard library; no third-party jars or build tools required

📸 Demo

Tic-Tac-Toe

🏗 Architecture

  • Client-Server ModelServer.java hosts the game lobby and logic; Client.java handles user input and display
  • Connection Flow — Server binds to port → waits for two clients → assigns X/O → alternates turns → broadcasts moves
  • Move Protocol — Clients send row,col strings; server parses, validates, updates board, then relays to opponent
  • State Management — Server maintains authoritative char[3][3] board; clients receive full board state after each move
  • Turn Enforcement — Server tracks active player; ignores input from non-active client until turn cycles
  • Resource Cleanup — Proper socket.close() and stream flushing on game end or disconnect to prevent resource leaks

⚙️ How to Run Locally

No build tools, no dependencies — just Java and a terminal.

# Clone the repository
git clone https://github.com/atandritC/Net-Tic-Tac-Toe.git
cd Net-Tic-Tac-Toe

# Terminal 1: Start the server
javac Server.java
java Server
# Server listens on port 12345 by default

# Terminal 2: Start Player 1 (Client X)
javac Client.java
java Client
# When prompted, enter server IP (use 'localhost' for same machine)

# Terminal 3: Start Player 2 (Client O) on another machine or tab
javac Client.java
java Client
# Enter the same server IP to join the game

💡 Testing Locally: Run both clients on the same machine using localhost as the server address. For network play, use the server's LAN IP (e.g., 192.168.1.100) or configure port forwarding for internet play.

🔒 Firewall Note: Ensure port 12345 (or your chosen port) is allowed through your firewall for incoming connections.

🧠 Challenges Faced & Solutions

Challenge Solution
Synchronizing moves between two independent clients Implemented server-as-referee pattern: all moves route through server, which broadcasts validated state to both clients
Preventing players from making moves out of turn Added server-side currentTurn flag; ignored input from non-active client with silent discard + optional warning
Handling abrupt client disconnects mid-game Wrapped socket I/O in try-catch; on IOException, server notifies remaining player and cleans up resources
Avoiding race conditions in board updates Used single-threaded server logic per game session; no concurrency needed for 2-player turn-based flow
Parsing and validating user input robustly Added input sanitization: checked bounds (0-2), format (row,col), and cell occupancy before accepting moves
Clear board rendering across different terminal sizes Used fixed-width ASCII board layout with consistent spacing for reliable display on any console

📈 What I Learned

  • Designing robust TCP socket communication patterns in Java with ServerSocket and Socket
  • Implementing server-authoritative game logic to ensure fairness and prevent client-side cheating
  • Managing state synchronization in distributed turn-based systems with minimal protocol overhead
  • Handling network edge cases: disconnects, timeouts, and malformed input with graceful degradation
  • Building clean console UIs that provide clear feedback without graphical dependencies
  • Keeping network protocols simple and human-readable for easier debugging and future extension

🤝 Contributing

Contributions are welcome! To get started:

  1. Fork the repo and create your feature branch:
    git checkout -b feature/AmazingFeature
  2. Commit your changes:
    git commit -am 'Add some AmazingFeature'
  3. Push to the branch:
    git push origin feature/AmazingFeature
  4. Open a Pull Request with a clear description of your changes

Guidelines:

  • Follow Java naming conventions and include Javadoc for new methods
  • Test network scenarios: disconnects, invalid moves, rapid inputs
  • Preserve backward compatibility with the existing row,col move protocol
  • Document any changes to the client-server message format

About

Implementing a Tic-Tac-Toe game using TCP/IP client-server communication in Java.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages