Giter Club home page Giter Club logo

game-project-api's Introduction

General Assembly Logo

A Tic-tac-toe data store API

An API to store tic-tac-toe game state and let two players compete across the internet. It allows players to register as users of the API and play against other registered users.

The API does not currently validate game states.

API end-points

Verb URI Pattern Controller#Action
POST /sign-up users#signup
POST /sign-in users#signin
DELETE /sign-out/:id users#signout
PATCH /change-password/:id users#changepw
GET /games games#index
POST /games games#create
GET /games/:id games#show
PATCH /games/:id games#update
GET /games/:id/watch games#watch

All data returned from API actions is formatted as JSON.


User actions

Summary:

Request Response
Verb URI body Status body
POST `/sign-up` credentials 201, Created user
400 Bad Request empty
POST `/sign-in` credentials 200 OK user w/token
401 Unauthorized empty
DELETE `/sign-out/:id` empty 201 Created empty
401 Unauthorized empty
PATCH `/change-password/:id` passwords 204 No Content user w/token
400 Bad Request empty

signup

The create action expects a POST of credentials identifying a new user to create, e.g. using getFormFields:

<form>
  <input name="credentials[email]" type="text" value="[email protected]">
  <input name="credentials[password]" type="password" value="an example password">
  <input name="credentials[password_confirmation]" type="password" value="an example password">
</form>

or using JSON:

{
  "credentials": {
    "email": "[email protected]",
    "password": "an example password",
    "password_confirmation": "an example password"
  }
}

The password_confirmation field is optional.

If the request is successful, the response will have an HTTP Status of 201, Created, and the body will be JSON containing the id and email of the new user, e.g.:

{
  "user": {
    "id": 1,
    "email": "[email protected]"
  }
}

If the request is unsuccessful, the response will have an HTTP Status of 400 Bad Request, and the response body will be empty.

signin

The signin action expects a POST with credentials identifying a previously registered user, e.g.:

<form>
  <input name="credentials[email]" type="text" value="[email protected]">
  <input name="credentials[password]" type="password" value="an example password">
</form>

or:

{
  "credentials": {
    "email": "[email protected]",
    "password": "an example password"
  }
}

If the request is successful, the response will have an HTTP Status of 200 OK, and the body will be JSON containing the user's id, email, and the token used to authenticate other requests, e.g.:

{
  "user": {
    "id": 1,
    "email": "[email protected]",
    "token": "an example authentication token"
  }
}

If the request is unsuccessful, the response will have an HTTP Status of 401 Unauthorized, and the response body will be empty.

signout

The signout actions is a DELETE specifying the id of the user to sign out.

If the request is successful the response will have an HTTP status of 204 No Content.

If the request is unsuccessful, the response will have a status of 401 Unauthorized.

changepw

The changepw action expects a PATCH of passwords specifying the old and new.

If the request is successful the response will have an HTTP status of 204 No Content.

If the request is unsuccessful the reponse will have an HTTP status of 400 Bad Request.


The sign-out and change-password requests must include a valid HTTP header Authorization: Token token=<token> or they will be rejected with a status of 401 Unauthorized.

Game actions

All games action requests must include a valid HTTP header Authorization: Token token=<token> or they will be rejected with a status of 401 Unauthorized.

All of the game actions, except for watch, follow the RESTful style.

Games are associated with users, player_x and player_o. Actions, other than update, will only retrieve a game if the user associated with the Authorization header is one of those two users. If this requirement is unmet, the response will be 404 Not Found, except for the index action which will return an empty games array.

Summary:

Request Response
Verb URI body Status body
GET `/games[?over=]` n/a 200, OK games found
The optional `over` query parameter restricts the response to games with a matching `over` property. 200, OK empty games
The default is to retrieve all games associated with the user.. 401 Unauthorized empty
POST `/games` n/a 201, Created game created
401 Unauthorized empty
400 Bad Request errors
GET `/games/:id` n/a 200, OK game found
401 Unauthorized empty
404 Not Found empty
PATCH `/games/:id` empty 200, OK game joined
400 Bad Request errors
400 Bad Request empty
PATCH `/games/:id` game delta 200, OK game updated
400 Bad Request errors
404 Not Found empty

index

The index action is a GET that retrieves all the games associated with a user. The response body will contain JSON containing an array of games, e.g.:

{
  "games": [
    {
      "id": 1,
      "cells": ["o","x","o","x","o","x","o","x","o"],
      "over": true,
      "player_x": {
        "id": 1,
        "email": "[email protected]"
      },
      "player_o": {
        "id": 3,
        "email": "[email protected]"
      }
    },
    {
      "id": 2,
      "cells": ["","","","","","","","",""],
      "over": false,
      "player_x": {
        "id": 3,
        "email": "[email protected]"
      },
      "player_o": {
        "id": 1,
        "email": "[email protected]"
      }
    }
  ]
}

If the over query parameter is specified the results will be restricted accordingly.

If there are no games associated with the user, the response body will contain an empty games array, e.g.:

{
  "games": [
  ]
}

create

The create action expects a POST with an empty body (e.g '' or '{}' if JSON). If the request is successful, the response will have an HTTP Status of 201 Created, and the body will contain JSON of the created game with player_x set to the user calling create, e.g.:

{
  "game": {
    "id": 3,
    "cells": ["","","","","","","","",""],
    "over": false,
    "player_x": {
      "id": 1,
      "email": "[email protected]"
    },
    "player_o": null
  }
}

If the request is unsuccessful, the response will have an HTTP Status of 400 Bad Request, and the response body will be JSON describing the errors.

show

The show action is a GET specifing the id of the game to retrieve. If the request is successful the status will be 200, OK, and the response body will contain JSON for the game requested, e.g.:

{
  "game": {
    "id": 1,
    "cells": ["o","x","o","x","o","x","o","x","o"],
    "over": true,
    "player_x": {
      "id": 1,
      "email": "[email protected]"
    },
    "player_o": {
      "id": 3,
      "email": "[email protected]"
    }
  }
}

update

join a game as player 'o'

This update action expects an empty (e.g '' or '{}' if JSON) PATCH to join an existing game.

If the request is successful, the response will have an HTTP Status of 200 OK, and the body will be JSON containing the game joined, e.g.:

{
  "game": {
    "id": 1,
    "cells": ["","","","","","","","",""],
    "over":false,
    "player_x": {
      "id": 1,
      "email": "[email protected]"
      },
    "player_o": {
      "id": 3,
      "email":
      "[email protected]"
    }
  }
}

If the request is unsuccessful, the response will have an HTTP Status of 400 Bad Request, and the response body will be empty (game cannot be joined, player_o already set or user making request is player_x) or JSON describing the errors.

update a game's states

This update action expects a PATCH with changes to to an existing game, e.g.:

<form>
  <input name="game[cell][index]" type="text" value="0">
  <input name="game[cell][value]" type="text" value="x">
  <input name="game[over]" type="text" value="false">
</form>
{
  "game": {
    "cell": {
      "index": 0,
      "value": "x"
    },
    "over": false
  }
}

If the request is successful, the response will have an HTTP Status of 200 OK, and the body will be JSON containing the modified game, e.g.:

{
  "game": {
    "id": 1,
    "cells": ["x","","","","","","","",""],
    "over":false,
    "player_x": {
      "id": 1,
      "email": "[email protected]"
      },
    "player_o": {
      "id": 3,
      "email":
      "[email protected]"
    }
  }
}

If the request is unsuccessful, the response will have an HTTP Status of 400 Bad Request, and the response body will be JSON describing the errors.

watch

The watch action is handled differently than all the others. Because watch implements a streaming source of data, we'll use a wrapper around the html5 object EventSource to handle the events sent.

You can find the wrapper here. The wrapper is also available from the deployed app at the path /js/resource-watcher-0.1.0.js.

The events that watch implements let you know when a game has been updated. By using this interface you can write code that lets a player see another's move almost as it happens. Updates to the game from one player's browser are sent to the other's browser.

You create a watcher object using the resourceWatcher function. This function takes two parameters, the watch url and a configuration object which must contain the Authorization token, and may contain an optional timeout in seconds, e.g.:

let gameWatcher = resourceWatcher('<server>/games/:id/watch', {
      Authorization: 'Token token=<token>'[,
      timeout: <timeout>]
});

By default, watching a game times-out after 120 seconds.

You should add a handler for change and error events. The error events are not the most informative. The change event may pass to your handler an object with a root key of "timeout" or "heartbeat".

Otherwise, it will pass an object with a root key of "game". Each key in this object will contain an array of length 2. The first element of such an array will contain the value for that key before the update. The last element will contain the value after the update. The code example that follows shows handling the most important case, a change to the game board.

gameWatcher.on('change', function (data) {
  console.log(data);
  if (data.game && data.game.cells) {
    const diff = changes => {
      let before = changes[0];
      let after = changes[1];
      for (let i = 0; i < after.length; i++) {
        if (before[i] !== after[i]) {
          return {
            index: i,
            value: after[i],
          };
        }
      }

      return { index: -1, value: '' };
    };

    let cell = diff(data.game.cells);
    $('#watch-index').val(cell.index);
    $('#watch-value').val(cell.value);
  } else if (data.timeout) { //not an error
    gameWatcher.close();
  }
});

gameWatcher.on('error', function (e) {
  console.error('an error has occurred with the stream', e);
});
  1. All content is licensed under a CC­BY­NC­SA 4.0 license.
  2. All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact [email protected].

game-project-api's People

Contributors

berziiii avatar dependabot[bot] avatar jrhorn424 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

game-project-api's Issues

documentation requirement issue

this is just following up on what i wrote in slack... just looking for some clarification.

From the requirements,

"Visually display the results of retrieving game statistics, such as total games won by a user. (READ)"

I don't see anywhere in the documentation that visualizing the GET games statistics in console is not acceptable... wondering if to fully meet requirement we need to place the game statistics/history on the SPA itself or if "visually" seeing it in console is adequate.

Thanks,
Matt :)

One on one

I dont think I understand the API from the token-auths. I was wondering if I could get some clarification.

Function not updating userTurn value

I am trying to have the my function changeTurn() change the value of userTurn from 'o' to 'x' inside of the rungame function. The value changes correctly within the if statement but I can't figure out how to update the value globally.

const gameArray = [null, null, null, null, null, null, null, null, null]

let userTurn = null

const addTokenToArray = function (userClick, userTurn) {
  gameArray[userClick - 1] = userTurn
  return gameArray
}

const changeTurn = function (userTurn) {
  if (userTurn === 'x') {
    userTurn = 'o'
  } else {
    userTurn = 'x'
  }
  return userTurn
}

const runGame = function (userClick, userTurn) {
  if (gameArray[userClick - 1] === null) {
    if (userTurn === 'x') {
      addTokenToArray(userClick, userTurn)
      changeTurn(userTurn)
    } else {
      addTokenToArray(userClick, userTurn)
      changeTurn(userTurn)
    }
  } else if (gameArray[userClick - 1] !== null) {
    console.log('invalid move')
  }
}

Can't delete style.css

I'm trying to organize my files. i previously had my css in style.css but want to move it in index.scss now to conform with what we do in class.

It works without problems, but my api starts yelling at me. It tries for some reason to access the file that I deleted.

I solved it through having now am empty style.ss with all my css in index.scss but I would like to delete the empty file.

screen shot 2016-06-02 at 11 46 09 am

issue with change password request

hello, I'm having issues with change password...

It can't find a module and it's having module build fails

// $('#change-pwd').on('submit', function (event) {
// event.preventDefault();
// let data = getFormFields(this);
// authApi.changepwd(authUi.signOutsuccess, authUi.failure);
// console.log(data;
// });

ncaught Error: Cannot find module "./auth/events.js"webpackMissingModule @ index.js:9(anonymous function) @ index.js:9(anonymous function) @ bundle.js:346__webpack_require__ @ bootstrap fc5b826…:50(anonymous function) @ index.js:8__webpack_require__ @ bootstrap fc5b826…:50webpackJsonpCallback @ bootstrap fc5b826…:21(anonymous function) @ bundle.js:1

I think the CHANGEPW method is not named correctly

In the API guid teh change password method is listed as being: "changepw" for the URL path.

When I used that I got the error below:

ActionController::RoutingError (No route matches [PATCH] "/changepw/7"):
actionpack (4.2.7.1) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'

By changing the path to "change-password" I got it to work.

Try to sign up and console shows error briefly then dissapears

I try to to sign up and then console logs error for split second then disappears. Page then reads: Cannot POST /index.html

I checked urls and imports and all requires. Cant find the problem

//app-data.js
const app = {
  api: 'http://tic-tac-toe.wdibos.com'
};

//api.js
const signUp = (success, failure, data) => {
  $.ajax({
    method: 'POST',
    url: app.api + '/sign-up',
    data,
  }).done(success)
    .fail(failure);
};

Watch documentation unclear (I think)

I think the Watch documentation should say that you can only watch a game you have already joined.

I know that a watcher requires a token, and it can be argued that this implies that you need to be in the game before you can watch, but when I was first learning how to use the given watcher code I thought the first step was to implement "Watch" as a streaming feature for third parties, and then the next step would be to use it as part of a multiplayer mode after that. I wasted a lot of time trying to get 3rd party streaming to work. I forget everything I tried, but here are some:

  • Using your own auth token to watch, as if the API might not care who is watching, it is just there because the Game API always needs a token.
  • Using another player's token
  • Using two different tokens (in a bunch of different ways)

Anyway, I couldn't get that to work, and I wasted a lot of time trying to do that. Once I knew you had to be in the game to watch, the actual feature of just automatically setting up a watcher when you make a game or join a game is really easy, it is just basically the same Ajax call as everything else.

Need help on git

I made some changes on my file on master branch and after commit, and when I check on "git status", it shows a message that "On branch master Your branch is ahead of 'origin/master' by 3 commits. (use "git push" to publish your local commits) nothing to commit, working directory clean".

And then I did "git push origin master", it throw me error like "To [email protected]:tina513/game-project-client.git ! [rejected] master -> master (fetch first)
error: failed to push some refs to '[email protected]:tina513/game-project-client.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details."

Please let me know how to update my github, because on my github page, the last commit I made is 3 hours ago. So it definitely not up to date.

New problems with tic tac toe

I made a couple big changes along with Chris right before he took off and now my update game is not working. Should I post my code?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.