-
Notifications
You must be signed in to change notification settings - Fork 4
Oil Snouts
Magnus Gudmundsson edited this page Jun 10, 2016
·
2 revisions
import {Component, OnInit} from '@angular/core';
import { WordService } from './word.service';
enum gameState {
Waiting,
Playing,
Lost,
Won };
const TotalMoves = 6;
@Component({
selector: 'my-hangman',
template: ` <h3>Let's play {{title}}</h3>
<div class="container bongo">
<div *ngIf="currentGameState!=1">
<button class="btn btn-lg btn-primary btn-block"
(click)="startGame()" type="submit">Play</button>
</div>
<div class="smallpadd">
<span *ngFor="#letter of incorrectLetters">{{letter}} </span>
</div>
<div>Moves Left : {{nrOfMoves}}</div>
<div id="theWord" class="smallpadd">
<span *ngFor="#letter of currentWord">
<span *ngIf="letterCorrect(letter)">{{letter}}</span>
<span *ngIf="!letterCorrect(letter)">_</span>
</span>
</div>
<div id="Valid Letters"class="btn-group">
<button *ngFor="#letter of validLetters"
[disabled]="hasBeenUsed(letter)||currentGameState!=1"
(click)="makeMove(letter)">{{letter}}</button>
</div>
<div *ngIf="currentGameState===2">You Lost.....</div>
<div *ngIf="currentGameState === 3">You Won.....</div>
</div>
`, styles: [
`
.bongo { padding:200px;}
.smallpadd {padding:20px;}
:disabled {background-color:#aaaaaa;}
`],
providers: [WordService]
})
export class HangmanComponent implements OnInit {
public title = 'Hangman';
validLetters: Array<string> = 'abcdefghijklmnopqrstuvwxyz'.split('');
correctLetters: Array<string>;
incorrectLetters: Array<string>;
currentWord: Array<string>;
nrOfMoves: number;
currentGameState: gameState;
uniqueLetterCount:number;
constructor(private wordService: WordService) { }
ngOnInit() {
this.currentGameState = gameState.Waiting;
this.correctLetters = new Array<string>();
this.incorrectLetters = new Array<string>();
}
letterCorrect(letter: string): boolean {
return this.correctLetters.indexOf(letter) != -1;
}
hasBeenUsed(letter: string): boolean {
return this.correctLetters.indexOf(letter) != -1 || this.incorrectLetters.indexOf(letter) != -1;
}
startGame() {
this.currentGameState = gameState.Playing;
this.nrOfMoves = TotalMoves;
this.correctLetters = new Array<string>();
this.incorrectLetters = new Array<string>();
//TODO ! get word from wordservice
// count uniqueLetters
let word = this.wordService.getUnusedWord();
this.uniqueLetterCount =this.countUniqueCharacters(word);
this.currentWord = word.split('');
}
makeMove(letter: string) {
//player has chosen a letter. What to do?
if (this.currentWord.indexOf(letter) != -1) {
this.correctLetters.push(letter);
}
else {
this.incorrectLetters.push(letter);
this.nrOfMoves--;
}
//And after that
this.validateGame();
}
validateGame() {
// it aint over till its game over
if (this.correctLetters.length === this.uniqueLetterCount) {
this.currentGameState = gameState.Won;
}
if (this.nrOfMoves === 0) {
this.currentGameState = gameState.Lost;
}
}
countUniqueCharacters(s: string) {
let countOfUniqueChars = s.length;
for (let i = 0; i < s.length; i++) {
if (i != s.indexOf(s[i])) {
countOfUniqueChars--;
}
}
return countOfUniqueChars;
}
}import {Component, OnInit} from '@angular/core';
import {LoginComponent} from './login.component';
import {HangmanComponent} from './hangman.component';
import {iCurrentUser} from './currentuser'
@Component({
selector: 'my-app',
template: `<div class="container">
<h2 class="form-signin-heading">{{title}}</h2>
<my-login (userLoggedIn)=updateUser($event) [ngClass]="{xinvisible:user.isAuthed}"></my-login>
<my-hangman [ngClass]="{xinvisible:!user.isAuthed}" class="container-fluid"></my-hangman>
<div [ngClass]="{xinvisible:!user.isAuthed}" class="container-fluid"> I know you, {{user.extId}} of course :) </div>
</div>
`,
styles: [`
.xinvisible { display:none};
`],
directives: [LoginComponent, HangmanComponent]
})
export class AppComponent implements OnInit {
public title = 'Meanwhile in Anthonys galaxy...';
appClass: string;
loginClass: string;
user: iCurrentUser;
//left here for educational purposes....
constructor() { }
ngOnInit() {
this.user = {isAuthed:false, extId:""}
if (localStorage.getItem('user') != null) {
this.user = JSON.parse(localStorage.getItem('user'));
}
}
updateUser(usr: iCurrentUser) {
this.user = usr;
localStorage.setItem("user", JSON.stringify(this.user));
}
}Solution 2 is basically the same, but with a fake room service, and no additions in main and app.component for http and rxjs
import {Component, OnInit} from '@angular/core';
import {HTTP_PROVIDERS} from '@angular/http';
import {LoginComponent} from './login.component';
import {RoomComponent} from './room.component';
import {iCurrentUser} from './currentuser';
@Component({
selector: 'my-app',
template: `<div class="container">
<h2 class="form-signin-heading">{{title}}</h2>
<my-login (userLoggedIn)=updateUser($event) parent="Tonys Galaxy" [ngClass]="{xinvisible:user.isAuthed}"></my-login>
<my-room></my-room>
<div [ngClass]="{xinvisible:!user.isAuthed}" class="container-fluid"> I know you, {{user.extId}} of course :) </div>
</div>
`,
styles: [`
.xinvisible { display:none};
`],
directives: [LoginComponent, RoomComponent],
providers: [HTTP_PROVIDERS]
})The rest is of the component is unchanged.
import {bootstrap} from '@angular/platform-browser-dynamic';
import {ServerService} from './server.service';
import 'rxjs/Rx'
import {AppComponent} from './app';
bootstrap(AppComponent, [ServerService]);<div class="container">
<form [ngFormModel]="userForm" (submit)="submit()">
<hr>
<input ngControl="name" type="text" class="form-control" placeholder="Name" >
<control-messages control="name" id="name"></control-messages>
<hr>
<textarea ngControl="description" class="form-control" rows="4" placeholder="Description"></textarea>
<control-messages control="description" id="description"></control-messages>
<hr>
<input ngControl="picture" type="text" class="form-control" placeholder="PictureUrl">
<control-messages control="picture" id="picture"></control-messages>
<hr>
<select class="form-control" ngControl="type" placeholder="Type">
<option *ngFor="#theType of types">{{theType}}</option>
</select>
<hr>
<div ngControlGroup="exits">
<p> North </p>
<select class="form-control" ngControl="North">
<option *ngFor="#room of availableRooms" value="{{room.id}}">{{room.name}}</option>
</select>
<p> East </p>
<select class="form-control" ngControl="East">
<option *ngFor="#room of availableRooms" value="{{room.id}}">{{room.name}}</option>
</select>
<p> West </p>
<select class="form-control" ngControl="West">
<option *ngFor="#room of availableRooms" value="{{room.id}}">{{room.name}}</option>
</select>
<p> South</p>
<select class="form-control" ngControl="South">
<option *ngFor="#room of availableRooms" value="{{room.id}}">{{room.name}}</option>
</select>
</div>
<hr>
<button [disabled]="!userForm.valid" class="btn btn-primary">Save</button>
</form>
</div>import {Component, OnInit} from '@angular/core';
import { FormBuilder, Validators} from '@angular/common';
import {RoomService} from './room.service';
import {ControlMessages} from './control-messages.component';
import {ValidationService} from './validation.service';
@Component({
selector: 'my-room',
templateUrl: 'app/room.component.html',
styles: [
`
.bongo { padding:200px;}
.smallpadd {padding:20px;}
:disabled {background-color:#aaaaaa;}
`],
providers: [RoomService],
directives: [ControlMessages]
})
export class RoomComponent implements OnInit {
userForm:any;
title = 'Some rooms';
availableRooms:any
types = ["indoors","outdoors","under water","in space", "other"];
constructor(private roomService: RoomService,
private formBuilder:FormBuilder) {
}
setform() {
this.userForm = this.formBuilder.group({
'name': ['', Validators.required],
'description': ['', Validators.required],
'picture' :['',ValidationService.emptyOrHttpImage],
'type' :['',Validators.nullValidator],
'exits': this.formBuilder.group ({
'North' :['0',Validators.nullValidator],
'East' :['0',Validators.nullValidator],
'West' :['0',Validators.nullValidator],
'South' :['0',Validators.nullValidator] })
});
}
ngOnInit() {
this.setform();
this.getRooms();
}
getRooms() {
this.roomService.getRooms().subscribe(res => {
this.availableRooms = [{"id":"0", "name":"This is not an exit"}].concat(res);
});
}
submit() {
var finalExits = Array<any>();
for(var key in this.userForm.value.exits) {
if(this.userForm.value.exits[key] != "0" && key != undefined) {
finalExits.push(
{
"name" : key,
"leadsToRoomId" : this.userForm.value.exits[key]
});
}
}
let room = this.userForm.value;
room.exits = finalExits;
room.dungeonId = "56ec088f68057ee424aed1db";
this.roomService.addRoom(room).subscribe(res => {
alert("room is saved" + JSON.stringify(res));
this.setform();
this.getRooms();
});
}
}import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import {ServerService} from './server.service';
@Injectable()
export class RoomService {
constructor(private http:Http, private serverService:ServerService) {}
public getRooms() {
return this.http.get(this.serverService.server +'/api/rooms/')
.map(res=> res.json());
}
public addRoom(itm:any) {
return this.http.post(this.serverService.server + '/api/rooms/',
JSON.stringify(itm),
{headers: new Headers({'Content-Type':'application/json'})})
.map(res => res.json());
}
}
import {Injectable} from '@angular/core';
@Injectable()
export class ServerService {
private _server: string = "http://xxxx.azurewebsites.net";
get server():string {
return this._server;
}
}xxxx is of course something else, mail me if you want to test it. :)
I basically copied validation service and message service
from http://plnkr.co/edit/6RkM0eRftf3KQpoDCktz?p=preview
and added this to validation service
static emptyOrHttpImage(control:any) {
if (control.value.match('')) {
return null;
}
else return this.httpImageValidator(control);
}
static httpImageValidator(control:any) {
// regex nicked from http://stackoverflow.com/questions/8834813/regex-to-match-image-url
if (control.value.match( /^https?:\/\/(?:[a-z\-]+\.)+[a-z]{2,6}(?:\/[^\/#?]+)+\.(?:jpe?g|gif|png)$/)) {
return null;
} else {
return { 'invalidImage': true };
}
}[Setup, Startup](Setup, Startup)
[Assignment #1] (Assignment-%231)
[Assignment #2] (Assignment-%232)
[Assignment #3] (Assignment-%233)
[Links] (Links)
[Slide Shows] (Slide Shows)