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.

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 class="wrapper">
  <header class="text-center">
    <h1>Tic Tac Toe</h1>
    <p class="lead">Defeat your friends and show no mercy</p>
  </header>

  <div id="board"></div>
  <div class="alerts welcome"></div>
  <div class="notifications"></div>

  <form action="" method="POST">
    <div class="input-group">
      <div class="input-group-addon">Player 1</div>
      <input name="pl-1" class="form-control" type="text" value=""/>
    </div>
    <div class="input-group">
      <div class="input-group-addon">Player 2</div>
      <input name="pl-2" class="form-control" type="text" value=""/>
    </div>
    <div class="text-center">
      <input type="submit" class="btn btn-lg btn-primary" value="Start"/>
    </div>
  </form>
</div>

              
            
!

CSS

              
                * {
  font-family: 'Chewy', cursive;
}

body {
  margin: 2em;
}

.wrapper{
  width: 700px;
  margin: 0 auto;
}

.alerts {
  color: #31708f;
  background-color: #d9edf7;
  border-color: #bce8f1;
  font-size: 1.75em;
  margin-bottom: 0.7em;
  border-radius: 5px;
  max-width: 250px;
  width: 35%;
  padding: 0.5em;
  text-align: center;
  float: left;
}

.welcome{
  float: none;
  width: 55%;
  margin:15px auto;
  max-width: 400px;
}

#board {
  max-width: 600px;
  width: 60%;
  float: left;
}

.square {
  width: 30%;
  height: 120px;
  background-color: cornsilk;
  border: 1px groove crimson;
  cursor: pointer;
  float: left;
  font-size: 68px;
  text-align: center;
}

.square:nth-of-type(3n + 1) {
  clear: both;
}

.square.x {
  color: crimson;
}

.square.o {
  color: #3997ff;
}

.notifications {
  max-width: 250px;
  width: 35%;
  padding: 1em;
  text-align: center;
  background-color: beige;
  float: left;
}

.notifications p {
  color: #7f7f7e;
  font-size: 1.2em;
}

.alerts, .notifications {
  display: none;
}

form {
  clear: both;
  width: 400px;
  margin: 0 auto;
  max-width: 500px;
}

.input-group{
  width: 100%;
  margin-bottom: 5px;
}

.input-group-addon{
  width: 75px;
}

form div:last-of-type {
  margin-top: 10px;
}

a.play-again {
  font-size: 1.5em;
  cursor: pointer;
}

              
            
!

JS

              
                $ ->
  Tic =
    data:
      turns: 0
      x: {}
      o: {}
      gameOver: false

    initialize: ->
      @data.gameOver = false
      @.setPlayerNames()
      @.retrieveStats()
      @.assignRoles()
      @.prepareBoard()
      @.updateNotifications()
      @.addListeners()

    setPlayerNames: ->
      @data.player1 = $("input[name='pl-1']").val()
      @data.player2 = $("input[name='pl-2']").val()

    retrieveStats: ->
      @data.p1stats = localStorage[@data.player1] || wins: 0, loses: 0
      if typeof @data.p1stats is "string" then @data.p1stats = JSON.parse @data.p1stats
      @data.p2stats = localStorage[@data.player2] || wins: 0, loses: 0
      if typeof @data.p2stats is "string" then @data.p2stats = JSON.parse @data.p2stats

    getPlayerName: (symbol) ->
      name = if @data.rolep1 == symbol then @data.player1 else @data.player2
      return name

    prepareBoard: ->
      $("form").hide()
      $("#board").empty()
      $(".alerts").removeClass("welcome").show()
      $(".alerts").text("#{@.getPlayerName("X")} Goes First")
      $("<div>", {class: "square"}).appendTo("#board") for square in [0..8]

    assignRoles: ->
      roles = ["X","O"].sort(->
        return 0.5 - Math.random()
      )
      @data.rolep1 = roles[0]
      @data.rolep2 = roles[1]

    updateNotifications: ->
      $(".notifications").empty().show()
      @.addNotification "#{@data.player1} is playing #{@data.rolep1}"
      @.addNotification "#{@data.player2} is playing #{@data.rolep2}"
      @.addNotification "#{@data.player1} has #{@data.p1stats.wins} wins and #{@data.p1stats.loses} loses"
      @.addNotification "#{@data.player2} has #{@data.p2stats.wins} wins and #{@data.p2stats.loses} loses"

    addNotification: (msg) ->
      $(".notifications").append($("<p>", {text: msg}));

    addListeners: ->
      $(".square").click ->
        if Tic.data.gameOver is no and not $(@).text().length
          if Tic.data.turns % 2 is 0 then $(@).html("X").addClass("x moved")
          else if Tic.data.turns % 2 isnt 0 then $(@).html("O").addClass("o moved")
          Tic.data.turns++
          Tic.checkEnd()
          if Tic.data.gameOver isnt yes and $(".moved").length >= 9 then Tic.addToScore("none")

    checkEnd : ->
      @.data.x = {}
      @.data.o = {}

      #diagonal check
      diagonals = [[0,4,8], [2,4,6]]
      for diagonal in diagonals
         for col in diagonal
           @.checkField(col, 'diagonal')
         @.checkWin()
         @.emptyStorageVar('diagonal')
      for row in [0..2]
        start = row * 3
        end = (row * 3) + 2
        middle = (row * 3) + 1

        #vertical check
        @.checkField(start, 'start')
        @.checkField(middle, 'middle')
        @.checkField(end, 'end')
        @.checkWin()

        # horizontal check
        for column in [start..end]
          @.checkField(column, 'horizontal')
        @.checkWin()
        @.emptyStorageVar('horizontal')

    checkField: (field, storageVar) ->
      if $(".square").eq(field).hasClass("x")
        if @.data.x[storageVar]? then @.data.x[storageVar]++ else @.data.x[storageVar] = 1
      else if $(".square").eq(field).hasClass("o")
        if @.data.o[storageVar]? then @.data.o[storageVar]++ else @.data.o[storageVar] = 1

    checkWin: ->
      for key,value of @.data.x
        if value >= 3
          localStorage.x++
          @.showAlert "#{@.getPlayerName("X")} wins"
          @.data.gameOver = true
          @.addToScore("X")
      for key,value of @.data.o
        if value >= 3
          localStorage.o++
          @.showAlert "#{@.getPlayerName("O")} wins"
          @.data.gameOver = true
          @.addToScore("O")

    addToScore: (winningParty) ->
      @data.turns = 0
      @data.x = {}
      @data.o = {}
      @data.gameOver = yes
      if winningParty is "none"
        @.showAlert "The game was a tie"
      else
        if @data.rolep1 == winningParty then ++@data.p1stats.wins else ++@data.p1stats.loses
        if @data.rolep2 == winningParty then ++@data.p2stats.wins else ++@data.p2stats.loses
        localStorage[@data.player1] = JSON.stringify @data.p1stats
        localStorage[@data.player2] = JSON.stringify @data.p2stats
      @.updateNotifications()
      $(".notifications").append "<a class='play-again'>Play Again?</a>"

    emptyStorageVar: (storageVar) ->
      @.data.x[storageVar] = null
      @.data.o[storageVar] = null

    showAlert: (msg) ->
      $(".alerts").text(msg).slideDown()

  $("form").on "submit", (evt) ->
    evt.preventDefault()
    $inputs = $("input[type='text']")

    namesNotEntered = $inputs.filter(->
      return @.value.trim() isnt ""
    ).length isnt 2

    namesIndentical = $inputs[0].value is $inputs[1].value

    if namesNotEntered then Tic.showAlert("Player names cannot be empty")
    else if namesIndentical then Tic.showAlert("Player names cannot be identical")
    else Tic.initialize()

  $("body").on("click",".play-again", -> Tic.initialize())

              
            
!
999px

Console