Skip to content

Instantly share code, notes, and snippets.

@cviktor
Last active March 26, 2017 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cviktor/b2b8d07fe7f0a42901b1a53d0310980a to your computer and use it in GitHub Desktop.
Save cviktor/b2b8d07fe7f0a42901b1a53d0310980a to your computer and use it in GitHub Desktop.
Kliensoldali technológiák - Typescript
checkWinner() {
var points = 0;
for (let fun of [
(i: number, j: number) => this.board[i][j],
(i: number, j: number) => this.board[j][i]
]) {
for (let i = 0; i < this.x; i++) {
let state = TileState.Empty;
points = 1;
for (let j = 0; j < this.y; j++) {
let tile = fun(i, j);
console.log(`${i}, ${j}, ${tile.state}, ${state}, ${points}`);
if (tile.state !== TileState.Empty && tile.state == state) {
if (++points >= 5) {
this.won(tile.state === TileState.X ?
this.playerOne : this.playerTwo);
}
} else {
points = 1;
}
state = tile.state;
}
}
}
}
initializeBoard(tableElement: JQuery, board: Tile[][]) {
tableElement.children().remove();
let tBody = $("<tbody></tbody>");
tableElement.append(tBody);
console.log(tableElement.children());
for (let i = 0; i < this.y; i++) {
var rowTiles: Tile[] = [];
let row = $("<tr></tr>");
tBody.append(row);
for (let j = 0; j < this.x; j++) {
let column = $("<td></td>");
row.append(column);
rowTiles.push(new Tile(column));
}
this.board.push(rowTiles);
}
}
loadState() {
let data = <SaveData>JSON.parse(localStorage.getItem("amoeba-table"));
if (!data)
return false;
if (this.x !== data.x || this.y !== data.y) {
localStorage.removeItem("amoeba-table");
return false;
}
this.initializeBoard(this.tableElement, this.board = []);
for (let i = 0; i < data.x; i++) {
for (let j = 0; j < data.y; j++) {
this.board[i][j].setState(data.tileStates[i][j]);
}
}
this.playerOne = data.playerOne;
this.playerTwo = data.playerTwo;
this.currentPlayer =
(data.current === 'player-one') ? this.playerOne : this.playerTwo;
return true;
}
onTileClicked(tile: Tile) {
if (tile.state === TileState.Empty && this.winner === undefined) {
if (this.currentPlayer === this.playerOne) {
tile.setState(TileState.X);
this.currentPlayer = this.playerTwo;
} else if (this.currentPlayer === this.playerTwo) {
tile.setState(TileState.O);
this.currentPlayer = this.playerOne;
}
this.checkWinner();
}
}
import { TileState } from "./tile";
export interface SaveData {
playerOne: PlayerInfo;
playerTwo: PlayerInfo;
current: 'player-one' | 'player-two';
x: number;
y: number;
tileStates: TileState[][];
}
export interface PlayerInfo {
name: string;
id: number;
gamesWon: number;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment