Loading...
Two players, 9 squares, turn-based. Every move is a tx. Who needs a server?
playerX (deployer) and playerO (first to call join)uint8[9]: 0=empty, 1=X, 2=Oturn counter: even = X's turn, odd = O's turnplace(uint8 pos) — only the current player can call, cell must be emptysoliditycontract TicTacToe { address public playerX; address public playerO; uint8[9] public board; uint256 public turn; uint8 public winner; // 0=none, 1=X, 2=O, 3=draw event Move(address indexed player, uint8 position, uint256 turn); event GameOver(uint8 winner); constructor() { playerX = msg.sender; } function join() external { require(playerO == address(0), "game full"); require(msg.sender != playerX, "can't play yourself"); playerO = msg.sender; } function place(uint8 pos) external { require(winner == 0, "game over"); require(pos < 9 && board[pos] == 0, "bad position"); address expected = turn % 2 == 0 ? playerX : playerO; require(msg.sender == expected, "not your turn"); board[pos] = turn % 2 == 0 ? 1 : 2; emit Move(msg.sender, pos, turn); turn++; // check winner… } }
Eight lines: 3 rows, 3 columns, 2 diagonals. Each line is an array of 3 positions. If all three have the same non-zero value → that player wins.
Write the place function, and implement checkWin() which sets the winner state if there's a 3-in-a-row.