Pen Settings

HTML

CSS

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

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

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

Behavior

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

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.

HTML

              
                <div id="app"></div>
              
            
!

CSS

              
                body {
  background-image: url(https://res.cloudinary.com/domxil2ks/image/upload/s--qcL4YzG---/v1507298762/fractals-environment-1728594_1280_v1ex3n.jpg);
  background-size: cover;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
  margin: 0;
  padding-bottom: 6rem;
  min-height: 100%;
}

input, button, submit { 
  border:none; 
  background: none;
} 

#main {
 margin: 10%;
 color: #c1bfea;
 border: 1px solid #FFF;
 width: 80%;
 height: 80vh;
  -webkit-box-shadow: 10px 11px 3px 1px rgba(0,0,0,0.75);
  -moz-box-shadow: 10px 11px 3px 1px rgba(0,0,0,0.75);
box-shadow: 10px 11px 3px 1px rgba(0,0,0,0.75);
}

#score {
  color: #FFF;
  text-align: center;
  padding-top: 50px;
}

.outer-field {
  width: 100%;
  height: 33.33%;
}

.inner-field {
  height: 100%;
  width: 33.33%;
  background: none;
  float: left;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 80px;
}

.inner-field:hover {
  cursor: pointer;
-webkit-box-shadow: 0px 0px 3px 4px rgba(192,192,192,1);
-moz-box-shadow: 0px 0px 3px 4px rgba(192,192,192,1);
box-shadow: 0px 0px 3px 4px rgba(192,192,192,1);
}

.buttons {
  text-align: center;
  margin: 30px 0px;
}

.modal-background {
background: rgba(242,246,248,0.4);
background: -moz-linear-gradient(top, rgba(242,246,248,1) 0%, rgba(216,225,231,1) 50%, rgba(181,198,208,1) 51%, rgba(224,239,249,1) 100%);
background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(242,246,248,1)), color-stop(50%, rgba(216,225,231,1)), color-stop(51%, rgba(181,198,208,1)), color-stop(100%, rgba(224,239,249,1)));
background: -webkit-linear-gradient(top, rgba(242,246,248,1) 0%, rgba(216,225,231,1) 50%, rgba(181,198,208,1) 51%, rgba(224,239,249,1) 100%);
background: -o-linear-gradient(top, rgba(242,246,248,1) 0%, rgba(216,225,231,1) 50%, rgba(181,198,208,1) 51%, rgba(224,239,249,1) 100%);
background: -ms-linear-gradient(top, rgba(242,246,248,1) 0%, rgba(216,225,231,1) 50%, rgba(181,198,208,1) 51%, rgba(224,239,249,1) 100%);
background: linear-gradient(to bottom, rgba(242,246,248,1) 0%, rgba(216,225,231,1) 50%, rgba(181,198,208,1) 51%, rgba(224,239,249,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f2f6f8', endColorstr='#e0eff9', GradientType=0 );
}

footer {
  color: #FFF;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  text-align: left;
}

footer p a {
  text-decoration: none;
}
              
            
!

JS

              
                class TicTacToe extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      0: "", 1: "", 2: "",
      3: "", 4: "", 5: "",
      6: "", 7: "", 8: "",
      score: 0,
      player: "times",
      ai: "circle-o",
      status: "game",
      text: "Choose your symbol",
      style: {
        display: "block"
      }
    }
  }
  
  chooseAvatar(avatar) {
    if(avatar != "x") {
      this.setState({
        player: "circle-o",
        ai: "times"
      }, this.startGame);
    } else {
      this.startGame();
    }
  }
  
  startGame() {
    const startFields = [0, 2, 6, 8];
    this.setState({ 
      style: { 
        display: "none" 
        },
      [_.sample(startFields)]: this.state.ai
    });
  }
  
  emptyFields(board) {
    return board.filter(entry => entry != this.state.player && entry != this.state.ai);
  }
  
  renderPlayField(playField) {
    return _.take(playField, 9).map(entry => {
      if(entry[1] == "") {
        return entry[0];
      } else return entry[1]
    });
  }
  
  newGame() {
    this.setState({
      0: "", 1: "", 2: "",
      3: "", 4: "", 5: "",
      6: "", 7: "", 8: "",
      status: "game"
    }, this.startGame);
  }
  
  winning(board, player) {
    if((board[0] == player && board[1] == player && board[2] == player) ||
       (board[3] == player && board[4] == player && board[5] == player) ||
       (board[6] == player && board[7] == player && board[8] == player) ||
       (board[0] == player && board[3] == player && board[6] == player) ||
       (board[1] == player && board[4] == player && board[7] == player) ||
       (board[2] == player && board[5] == player && board[8] == player) ||
       (board[0] == player && board[4] == player && board[8] == player) ||
       (board[2] == player && board[4] == player && board[6] == player) ) {
      return true
    } else return false;
  }
  
  componentDidUpdate() {
    let playField = this.renderPlayField(Object.entries(this.state));
    let openFields = this.emptyFields(playField);

    if(this.winning(playField, this.state.ai) && this.state.status != "lost" && this.state.status != "drawed" && openFields.length !== 0) {
      setTimeout(() => {
        this.setState({
          status: "lost",
          text: "You Lost! Do you want to play again?",
          score: this.state.score + 1, 
          style: {
            display: "block"
          }
        })
      }, 300);
    } else if(openFields.length == 0 && this.state.status == "game") {
      setTimeout(() => {
        this.setState({ 
          status: "drawed",
          text: "You Drawed! Do you want to play again?",
          style: {
            display: "block"
          }
        })
      }, 300);
    }
  }
  
  miniMax(newBoard, player){
  //available spots
  let openFields = this.emptyFields(newBoard);

  // checks for the terminal states such as win, lose, and tie and returning a value accordingly
  if (this.winning(newBoard, this.state.player)) {
     return { score:-10 };
  }
	else if (this.winning(newBoard, this.state.ai)) {
    return { score:10 };
	}
  else if (openFields.length == 0) {
  	return { score:0 };
  }

// an array to collect all the objects
  let moves = [];

  // loop through available spots
  for(let i = 0; i < openFields.length; i++){
    //create an object for each and store the index of that spot that was stored as a number in the object's index key
    let move = {};
  	move.index = newBoard[openFields[i]];

    // set the empty spot to the current player
    newBoard[openFields[i]] = player;

    //if collect the score resulted from calling minimax on the opponent of the current player
    if (player == this.state.ai){
      let result = this.miniMax(newBoard, this.state.player);
      move.score = result.score;
    }
    else {
      let result = this.miniMax(newBoard, this.state.ai);
      move.score = result.score;
    }
    //reset the spot to empty
    newBoard[openFields[i]] = move.index;
    // push the object to the array
    moves.push(move);
  }
// if it is the computer's turn loop over the moves and choose the move with the highest score
  let bestMove;
  if(player === this.state.ai){
    let bestScore = -10000;
    for(let k = 0; k < moves.length; k++){
      if(moves[k].score > bestScore){
        bestScore = moves[k].score;
        bestMove = k;
      }
    }
  } else {
// else loop over the moves and choose the move with the lowest score
    let bestScore = 10000;
    for(var j = 0; j < moves.length; j++){
      if(moves[j].score < bestScore){
        bestScore = moves[j].score;
        bestMove = j;
      }
    }
  }
// return the chosen move (object) from the array to the higher depth
  return moves[bestMove];
}
  
  setStone(field) {
    if(this.state[field] != "") {
      return;
    } 
    
    this.setState({ [parseInt(field)]: this.state.player }, () => {
      let playField = this.renderPlayField(Object.entries(this.state));
      let aiMove = this.miniMax(playField, this.state.ai);
      
      this.setState({ [parseInt(aiMove.index)]: this.state.ai });
    });
  }
  
  render() {
    let counter = 0;
    const avatars = [{ value: "x", icon: "times" }, { value: "o", icon: "circle-o" }];
    const listAvatars = avatars.map(avatar => {
      return(
        <div className="w3-half">
          <button className="w3-btn w3-white w3-border"
            onClick={ () => this.chooseAvatar(avatar.value)}>
            <i className={`fa fa-${avatar.icon}`}></i>
          </button>
        </div>
      );
    });
    
    const playAgain = (
      <div>
        <div className="w3-half">
              <button className="w3-btn w3-green" onClick={() => this.newGame() }>Yes</button>     
        </div>

        <div className="w3-half">
          <button className="w3-btn w3-red" 
            onClick={() => this.setState({ style: { display: "none" } })}>No</button>      
        </div>
      </div>
    );
    
    return(
      <div id="wrapper">
        <Modal style={ this.state.style} text={ this.state.text } listAvatars={ listAvatars } playAgain={ playAgain } status={ this.state.status }/>
        
        <h2 id="score">Computer { this.state.score } : 0 Player</h2>

        <div id="main">
          {
            _.times(3, () => {             
              return( 
                <div className="outer-field w3-border">
                  { _.times(3, () => {
                    return(
                      <button id={ counter } className="inner-field w3-border"
                        value={ counter }
                        onClick={ event => this.setStone(event.target.value) }>
                        { <i className={`fa fa-${this.state[counter++]}`}></i> }
                      </button>
                    )
                  }) }
                </div>
              );
            })
          }
        </div>
               <footer className="footer">
          <p>
            Created by: &nbsp;
            <a href="https://codepen.io/Gh05d/full/WEmwPr/" target="_blank">
               Gh05d
            </a>
          </p>
          <p><time>{new Date().getFullYear()}</time></p>
        </footer> 
      </div>
    );
  }
}

const Modal = ({ style, text, listAvatars, playAgain, status }) => (
  <div style={ style } className="w3-modal">
    <div className="w3-modal-content w3-card-4">
      <div className="modal-background">
        <header className="w3-container w3-gray">
          <h2>{ text }</h2>
        </header>
        <div className="w3-container buttons">
          { status == "game" ? listAvatars : playAgain }
        </div>

        <footer className="w3-container w3-gray">
          <p>Have fun...</p>
        </footer>
      </div>
    </div>
  </div>
);
    
ReactDOM.render(<TicTacToe />, document.getElementById("app"));
              
            
!
999px

Console