Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              * {
  box-sizing: border-box;
  font-family: 'Baloo', cursive;
}

html, body {
  min-height: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  font-family: 'Baloo', cursive;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
}

button {
  cursor: pointer;
  border: 1px solid black;
  padding: 5px 10px;
}

button:hover {
  background-color: white;
}

[disabled] {
  pointer-events: none;
}

.menu {
  background-color: rgba(200, 200, 200, 0.8);
  border-radius: 4px;
  padding: 24px;
  border: 1px solid  black;
}

.menu h1 {
  margin: 0;
  margin-bottom: 10px;
}

.menu-buttons {
  display: flex;
  justify-content: center;
}

.menu-buttons button {
  font-weight: bold;
  font-size: 1.2em;
}

.menu-buttons button:first-child {
  margin-right: 10px;
}

.board {
  display: flex;
  flex-wrap: wrap;
  width: 300px;
}

.reset-button {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  margin-top: 10px;
  padding: 5px 10px;
  font-size: 1.2em;
}

.field {
  position: relative;
  background-color: #ccc;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  text-align: center;
  line-height: 100px;
  font-size: 2em;
  font-weight: bold;
}

.field:not([disabled]):hover::after {
  content: " ";
  background-color: rgba(255, 255, 255, 0.3);
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  cursor: pointer;
}

.endModalOverlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 50;
}

.endModal {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(200, 200, 200, 0.9);
  padding: 30px;
  line-height: 40px;
  border-radius: 4px;
  border: 1px solid black;
  z-index: 100;
}

.endModal .modal-buttons {
  display: flex;
  justify-content: center;
}

.endModal .modal-buttons button {
  outline: none;
  width: 200px;
  font-size: 1.2em;
}

.endModal .modal-buttons button:hover {
  background-color: white;
}

.endModal h2 {
  font-size: 2em;
  margin: 0;
  margin-bottom: 20px;
}
            
          
!
            
              const { PropTypes } = React
const { render } = ReactDOM
const { createStore, applyMiddleware } = Redux
const { Provider, connect } = ReactRedux
const thunk = ReduxThunk.default

const TOKEN_X = "X"
const TOKEN_O = "O"

const nextToken = (t) => t === TOKEN_X ? TOKEN_O : TOKEN_X

/* ---- UTILITY ---- */

const isBoardFull = (board) => board.every(r => r.every(c => c))

const calculateWin = (token, board, winCombo) => {
  const numToField = n => ({ x: n % 3, y: Math.floor(n / 3) })
  return Boolean(winCombo.find(combo => 
    combo.every(field => {
      const coords = numToField(field)
      return board[coords.y][coords.x] === token
    })
  ))
}

const calculateComputerTurn = (token, board, winCombo) => {
  const freeFields = (b) => b.reduce((p, c, y) =>
                                     c.forEach((f, x) => {
                                              if(!f) p.push({x, y}) }) || p
                                     , [])
  
  
  let result
  
  const miniMax = (playerToken, deep = 0) => {
    const fields = freeFields(board)
    const loose = calculateWin(nextToken(playerToken), board, winCombo)
    const win = calculateWin(playerToken, board, winCombo)
    if(!fields.length || loose || win)
      return loose ? -1 : (win ? 1 : 0)
    let maxVal = -Number.MAX_SAFE_INTEGER
    fields.forEach(({x, y}) => {
      board[y][x] = playerToken
      const minVal = -miniMax(nextToken(playerToken), deep-1)
      board[y][x] = null
      if(minVal > maxVal) {
        maxVal = minVal
        if(deep === 0)
          result = {x, y}
      }
    })
    return maxVal
  }
  
  miniMax(token)
  return result
}

/* ---- ACTIONS ---- */
const CHOOSE_PLAYER = 'CHOOSE_PLAYER'
const SET_STONE = 'SET_STONE'
const RESET_GAME = 'RESET_GAME'
const FULL_RESET = 'FULL_RESET'

const setPlayerToken = (token) => {
  return {
    type: CHOOSE_PLAYER,
    token
  }
}

const resetGame = () => {
  return {
    type: RESET_GAME
  }
}

const fullReset = () => {
  return {
    type: FULL_RESET
  }
}

const setStone = (token, x, y) => {
  return {
    type: SET_STONE, x, y, token
  }
}

/* ---- ACTION CREATORS ---- */
const setComputerStone = (random) => {
  return (dispatch, getState) => {
    const boardState = getState().boardState
    const computerToken = nextToken(getState().playerToken)
    let coords
    if(random) {
      const positions = [0, 2, 4, 6, 8]
      const posIndex = Math.floor(Math.random() * 5)
      const position = positions[posIndex]
      coords = { x: position % 3, y: Math.floor(position / 3) }
    } else
      coords = calculateComputerTurn(computerToken, boardState.board, boardState.winCombinations)
    if(coords)
      dispatch(setStone(computerToken, coords.x, coords.y))
  }
}

const setStoneAction = (token, x, y) => {
  return (dispatch, getState) => {
    let state = getState()
    
    if(state.boardState.board[y][x]) return
    
    dispatch(setStone(token, x, y))
    
    // Get new state
    state = getState()
    const isWin = calculateWin(state.playerToken, state.boardState.board, state.boardState.winCombinations)
    
    if(isBoardFull(state.boardState.board) || isWin) return
    
    setTimeout(() => { dispatch(setComputerStone()) }, 1000)
  }
}

const resetGameAction = () => {
  return (dispatch, getState) => {
    dispatch(resetGame())
    if(!getState().boardState.playerActive)
      dispatch(setComputerStone(true))
  }
}

const chooseToken = (token) => {
  return (dispatch, getState) => {
    dispatch(setPlayerToken(token))
    dispatch(resetGameAction())
  }
}

/* ---- REDUCERS ---- */
const initialState = {
  inMenu: true,
  playerToken: TOKEN_X,
  tokenOfWinPlayer: null,
  boardState: {
    winCombinations: [
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
      [0, 3, 6],
      [1, 4, 7],
      [2, 5, 8],
      [0, 4, 8],
      [2, 4, 6]
    ],
    playerActive: true,
    board: [
      [null, null, null],
      [null, null, null],
      [null, null, null]
    ]
  }
}

function ticTacToe(state = initialState, action) {
  switch(action.type) {
    case FULL_RESET:
      return Object.assign({}, initialState)
    case RESET_GAME:
      return Object.assign({}, state, {
        tokenOfWinPlayer: null,
        boardState: Object.assign({}, state.boardState, {
          board: initialState.boardState.board,
          playerActive: Boolean(Math.floor(Math.random() * 2))
        })
      })
    case CHOOSE_PLAYER:
      return Object.assign({}, state, 
        { 
          inMenu: false,
          playerToken: action.token
        })
    case SET_STONE:
      if(state.boardState.board[action.y][action.x]) return state

      const newBoard = [...state.boardState.board.map(r => [...r])]
      newBoard[action.y][action.x] = action.token
      
      return Object.assign({}, state,
        {
          boardState: Object.assign({}, state.boardState, {
            board: newBoard,
            playerActive: !state.boardState.playerActive
          })
        })
    default:
      return state
  }
}

/* ---- MENU ---- */

let Menu = ({onPlayerChoice}) => (
  <div className="menu">
    <h1>Choose your player</h1>
    <div className="menu-buttons">
      <button onClick={() => onPlayerChoice(TOKEN_X)}>{TOKEN_X}</button>
      <button onClick={() => onPlayerChoice(TOKEN_O)}>{TOKEN_O}</button>
    </div>
  </div>
)

const mapDispatchToProps = (dispatch) => {
  return {
    onPlayerChoice: (choice) =>
      dispatch(chooseToken(choice))
  }
}

Menu.propTypes = {
  onPlayerChoice: PropTypes.func.isRequired
}

Menu = connect(s => s, mapDispatchToProps)(Menu)

/* ---- PLAYFIELD ---- */

let PlayField = ({playerToken, winToken, gameEnd, playerActive, board, onFieldClick, onResetClick}) => {
  const canPlay = field => playerActive && !field
  const click = playerActive ? onFieldClick.bind(null, playerToken) : () => {}
  const fullResetClick = () => onResetClick(true)
  
  let endMsg = playerToken === winToken ? "You won!" : "You lost!"
  if(!winToken) endMsg = "Its a draw!"
  
  const endDisplay = <div className="endModalOverlay">
            <div className="endModal">
              <h2>{endMsg}</h2>
              <div className="modal-buttons">
                <button onClick={fullResetClick}>Play again</button>
              </div>
            </div>
          </div>
        
  return <div className="game">
      <div className="board">
        {
          board.map((row, y) =>
               row.map((field, x) =>
                <div className="field" disabled={!canPlay(field)} onClick={() => click(x, y)}>{field}</div>))
        }
      </div>
      { gameEnd ? endDisplay : '' }
      <button disabled={!playerActive} 
        className="reset-button" onClick={() => onResetClick()}>Reset</button>
    </div>
}

const mapPlayFieldStateToProps = (state) => {
  const playerWon = calculateWin(state.playerToken, state.boardState.board, state.boardState.winCombinations)
  const computerWon = calculateWin(nextToken(state.playerToken), state.boardState.board, state.boardState.winCombinations)
  const gameEnd = isBoardFull(state.boardState.board) || playerWon || computerWon
  
  let winToken = null
  if(playerWon) winToken = state.playerToken
  else if(computerWon) winToken = nextToken(state.playerToken)
  
  return Object.assign({}, state.boardState, {
    playerToken: state.playerToken,
    winToken,
    gameEnd
  })
}

const mapPlayFieldDispatchToProps = (dispatch) => {
  return {
    onFieldClick: (token, x, y) => {
      dispatch(setStoneAction(token, x, y))
    },
    onResetClick: (full) => {
      if(full)
        dispatch(fullReset())
      else
        dispatch(resetGameAction())
    }
  }
}

PlayField.propTypes = {
  playerActive: PropTypes.bool.isRequired,
  onFieldClick: PropTypes.func.isRequired,
  onResetClick: PropTypes.func.isRequired
}

PlayField = connect(
  mapPlayFieldStateToProps,
  mapPlayFieldDispatchToProps)(PlayField)

/* ---- TICTACTOE ---- */
let TicTacToe = ({inMenu}) => {
  const main = inMenu ? <Menu /> : <PlayField />
  return <div>{main}</div>
}

TicTacToe.propTypes = {
  inMenu: PropTypes.bool.isRequired
}

TicTacToe = connect(state => state)(TicTacToe)

/* ---- RENDER ---- */
let store = createStore(ticTacToe, applyMiddleware(thunk))

render(
  <Provider store={store}>
    <TicTacToe />
  </Provider>,
  document.getElementById('root')
)
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console