Update WordService.ts

This commit is contained in:
Hugo Bernier 2020-05-28 22:40:20 -04:00 committed by GitHub
parent 395aaa1316
commit 3819af3f68
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 245 additions and 195 deletions

View File

@ -1,75 +1,107 @@
// import * as $ from '../assets/jquery.min'; // import * as $ from '../assets/jquery.min';
import { SPComponentLoader } from '@microsoft/sp-loader';
import WordGame from './WordGame';
import { WebPartContext } from '@microsoft/sp-webpart-base'; import { WebPartContext } from '@microsoft/sp-webpart-base';
import { import {
SPHttpClient, SPHttpClient,
SPHttpClientResponse, SPHttpClientResponse,
HttpClientConfiguration,
ISPHttpClientOptions ISPHttpClientOptions
} from '@microsoft/sp-http'; } from '@microsoft/sp-http';
// tslint:disable-next-line: no-any
const wordjpg: any = require('../assets/wordlist.jpg'); const wordjpg: any = require('../assets/wordlist.jpg');
// tslint:disable-next-line: no-any
const $: any = require('../assets/jquery.min'); const $: any = require('../assets/jquery.min');
// const wordlist: any = require('../assets/wordlist.json');
export class Game export class Game {
{ public rounds: Round[] = [];
rounds:Round[] = [];
} }
export class Round export class Round {
{ public word: string = '';
word = ""; public answers: string[] = [];
answers:string[] = []; public correctAnswer: string = '';
correctAnswer = ""; public incorrectAnswers: string[] = [];
incorrectAnswers:string[] = [];
} }
export class WordGameListItem {
// tslint:disable-next-line: variable-name
public Name: string;
// tslint:disable-next-line: variable-name
public Score: number;
// tslint:disable-next-line: variable-name
public Seconds: number;
// tslint:disable-next-line: variable-name
public Details: string;
constructor(name: string, score: number, seconds: number, details: string) {
this.Name = name;
this.Score = score;
this.Seconds = seconds;
this.Details = details;
}
}
export class WordService { export class WordService {
public allwords: string[] = [];
public words3: string[] = [];
public words4: string[] = [];
public words5: string[] = [];
public words6: string[] = [];
public words7: string[] = [];
public words8: string[] = [];
public context: WebPartContext;
allwords: string[] = []; public GenerateGame(): Game {
words3: string[] = [];
words4: string[] = [];
words5: string[] = [];
words6: string[] = [];
words7: string[] = [];
words8: string[] = [];
context:WebPartContext;
GenerateGame():Game const game: Game = new Game();
{
let game = new Game(); const round1: Round = new Round();
round1.word = this.GetRandomScrambledWord(5);
round1.answers = this.FindPossibleWords(round1.word);
let round1 = new Round(); round1.word = this.GetRandomScrambledWord(5); round1.answers = this.FindPossibleWords(round1.word); const round2: Round = new Round();
let round2 = new Round(); round2.word = this.GetRandomScrambledWord(5); round2.answers = this.FindPossibleWords(round2.word); round2.word = this.GetRandomScrambledWord(5);
let round3 = new Round(); round3.word = this.GetRandomScrambledWord(5); round3.answers = this.FindPossibleWords(round3.word); round2.answers = this.FindPossibleWords(round2.word);
let round4 = new Round(); round4.word = this.GetRandomScrambledWord(6); round4.answers = this.FindPossibleWords(round4.word);
let round5 = new Round(); round5.word = this.GetRandomScrambledWord(6); round5.answers = this.FindPossibleWords(round5.word);
let round6 = new Round(); round6.word = this.GetRandomScrambledWord(6); round6.answers = this.FindPossibleWords(round6.word);
game.rounds.push(round1); const round3: Round = new Round();
game.rounds.push(round2); round3.word = this.GetRandomScrambledWord(5);
game.rounds.push(round3); round3.answers = this.FindPossibleWords(round3.word);
game.rounds.push(round4);
game.rounds.push(round5);
game.rounds.push(round6);
return game; const round4: Round = new Round();
round4.word = this.GetRandomScrambledWord(6);
round4.answers = this.FindPossibleWords(round4.word);
const round5: Round = new Round();
round5.word = this.GetRandomScrambledWord(6);
round5.answers = this.FindPossibleWords(round5.word);
const round6: Round = new Round();
round6.word = this.GetRandomScrambledWord(6);
round6.answers = this.FindPossibleWords(round6.word);
game.rounds.push(round1);
game.rounds.push(round2);
game.rounds.push(round3);
game.rounds.push(round4);
game.rounds.push(round5);
game.rounds.push(round6);
return game;
} }
public async loadWords(): Promise<void> {
async loadWords() { // tslint:disable-next-line: no-string-literal
window['wordService'] = this;
window["wordService"] = this;
/* SP Loader Implementation */ /* SP Loader Implementation */
// console.log(jquery); // console.log(jquery);
// await SPComponentLoader.loadScript('../assets/jquery.min.js', { globalExportsName: "ScriptGlobal" }); // await SPComponentLoader.loadScript('../assets/jquery.min.js', { globalExportsName: "ScriptGlobal" });
// console.log('jquery loaded'); // console.log('jquery loaded');
/* JSON File Implementation /* JSON File Implementation
If you have a custom word list you would like to use If you have a custom word list you would like to use
add it as a JSON file in assets/wordlist.json and add it as a JSON file in assets/wordlist.json and
@ -80,24 +112,25 @@ export class WordService {
// for(let i=0;i<wordlistlength;i++) // for(let i=0;i<wordlistlength;i++)
// this.allwords.push(wordvalues[i]); // this.allwords.push(wordvalues[i]);
/* Text File Implementation /* Text File Implementation
Yields the smallest file download size vs JSON (700k vs 1.3mb) Yields the smallest file download size vs JSON (700k vs 1.3mb)
The word list is a text file stored as wordlist.jpg and The word list is a text file stored as wordlist.jpg and
loaded as text/plain using an overrided mime type */ loaded as text/plain using an overrided mime type */
var responseText = await $.ajax({ const responseText: string = await $.ajax({
url: wordjpg, url: wordjpg,
beforeSend: function (xhr) { beforeSend: (xhr) => {
xhr.overrideMimeType("text/plain; charset=x-user-defined"); xhr.overrideMimeType('text/plain; charset=x-user-defined');
} }
}) as string; }) as string;
this.allwords = responseText.split("\r\n"); this.allwords = responseText.split('\r\n');
this.allwords.forEach(word => { this.allwords.forEach(word => {
if (word.indexOf("-") > -1) if (word.indexOf('-') > -1) {
return; return;
if (word.indexOf("-") > -1) }
if (word.indexOf('-') > -1) {
return; return;
}
switch (word.length) { switch (word.length) {
case 3: case 3:
this.words3.push(word); this.words3.push(word);
@ -126,13 +159,13 @@ export class WordService {
} }
GetWordCount(): number { public GetWordCount(): number {
return this.allwords.length; return this.allwords.length;
} }
GetRandomScrambledWord(level: number) { public GetRandomScrambledWord(level: number): string {
let randomWord = ""; let randomWord: string = '';
let randwordnum = 0; let randwordnum: number = 0;
switch (level) { switch (level) {
case 3: case 3:
randwordnum = Math.floor(Math.random() * Math.floor(this.words3.length)); randwordnum = Math.floor(Math.random() * Math.floor(this.words3.length));
@ -162,109 +195,122 @@ export class WordService {
break; break;
} }
let scrambledWord = this.ScrambleWord(randomWord); const scrambledWord: string = this.ScrambleWord(randomWord);
return scrambledWord; return scrambledWord;
} }
FindPossibleWords(currentWord: string) { public FindPossibleWords(currentWord: string): string[] {
//coati // coati
//taco // taco
//currentWord = "coati"; // currentWord = "coati";
let possibleWords: string[] = []; const possibleWords: string[] = [];
this.allwords.forEach(word => { this.allwords.forEach(word => {
let tempword = word;//taco let tempword: string = word; // taco
for (let i = 0; i < currentWord.length; i++) { for (let i: number = 0; i < currentWord.length; i++) {
let letter = currentWord[i]; const letter: string = currentWord[i];
if (tempword.indexOf(letter) > -1) { if (tempword.indexOf(letter) > -1) {
tempword = tempword.slice(0, tempword.indexOf(letter)) + tempword.slice(tempword.indexOf(letter) + 1); tempword = tempword.slice(0, tempword.indexOf(letter)) + tempword.slice(tempword.indexOf(letter) + 1);
} } else {
else {
tempword = 'n'; tempword = 'n';
break; break;
} }
} }
if (tempword.length == 0) if (tempword.length === 0) {
possibleWords.push(word) possibleWords.push(word);
}
}); });
return possibleWords; return possibleWords;
} }
//replace a character in a string public ScrambleWord(word: string): string {
private replaceCharAt(orig:string, index:number, replacement:string): string { let notScrambled: boolean = true;
return orig.substr(0, index) + replacement + orig.substr(index + replacement.length); let scrambledWord: string = '';
} let count: number = 0;
const originalword: string = word;
ScrambleWord(word: string): string {
let notScrambled = true;
let scrambledWord = "";
let count = 0;
var originalword = word;
while (notScrambled) { while (notScrambled) {
word = originalword; word = originalword;
let chars = ''; let chars: string = '';
for (let i = 0; i < word.length; i++) for (let i: number = 0; i < word.length; i++) {
chars += ' '; chars += ' ';
}
let index = 0; let index: number = 0;
while (word.length > 0) { while (word.length > 0) {
let next = Math.floor(Math.random() * Math.floor(word.length)); // Get a random number between 0 and the length of the word. // Get a random number between 0 and the length of the word.
chars = this.replaceCharAt(chars, index, word[next]); // Take the character from the random position and add to our char array. const next: number = Math.floor(Math.random() * Math.floor(word.length));
word = word.substr(0, next) + word.substr(next + 1); // Remove the character from the word.
// Take the character from the random position and add to our char array.
chars = this.replaceCharAt(chars, index, word[next]);
// Remove the character from the word.
word = word.substr(0, next) + word.substr(next + 1);
++index; ++index;
} }
scrambledWord = chars.slice(0); scrambledWord = chars.slice(0);
count++; count++;
if (originalword!=scrambledWord) if (originalword !== scrambledWord) {
notScrambled = false; notScrambled = false;
}
//just in case there is a problem // just in case there is a problem
if (count == 10) if (count === 10) {
notScrambled = false; notScrambled = false;
}
} }
return scrambledWord; return scrambledWord;
} }
//SHAREPOINT APIS // SHAREPOINT APIS
SetContext(context:WebPartContext){ public SetContext(context: WebPartContext): void {
this.context = context; this.context = context;
} }
public async SubmitScore(score:number,seconds:number,details:string){ public async SubmitScore(score: number, seconds: number, details: string): Promise<void> {
try{ try {
await this.CreateListIfNotExists(); await this.CreateListIfNotExists();
await this.CreateListItem(score,seconds,details); await this.CreateListItem(score, seconds, details);
}catch(error){} } catch (error) {
// do nothing
}
} }
async GetHighScores():Promise<WordGameListItem[]>{ public async GetHighScores(): Promise<WordGameListItem[]> {
var scores:WordGameListItem[] = []; let scores: WordGameListItem[] = [];
try{ try {
let result = await this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + "/_api/web/lists/GetByTitle('WordGameList')/items", SPHttpClient.configurations.v1); const result: SPHttpClientResponse = await this.context.spHttpClient.get(
let json:any = await result.json(); this.context.pageContext.web.absoluteUrl
+ "/_api/web/lists/GetByTitle('WordGameList')/items",
SPHttpClient.configurations.v1);
// tslint:disable-next-line: no-any
const json: any = await result.json();
console.log(json); console.log(json);
json.value.forEach(item => { json.value.forEach(item => {
scores.push(new WordGameListItem(item.Title,item.Score,item.Seconds,item.Details)); scores.push(new WordGameListItem(item.Title,
item.Score,
item.Seconds,
item.Details));
}); });
scores.sort((a,b)=> {return b.Score-a.Score}); scores.sort((a, b) => {
return b.Score - a.Score;
});
//top 10 // top 10
if (scores.length>10) if (scores.length > 10) {
scores = scores.slice(0,10); scores = scores.slice(0, 10);
}
console.log('high scores',scores); console.log('high scores', scores);
}catch(error){ } catch (error) {
console.log('could not find list'); console.log('could not find list');
} }
@ -272,18 +318,28 @@ export class WordService {
} }
async CreateListIfNotExists(){ // replace a character in a string
let result = await this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + '/_api/web/lists', SPHttpClient.configurations.v1); private replaceCharAt(orig: string, index: number, replacement: string): string {
let json:any = await result.json(); return orig.substr(0, index) + replacement + orig.substr(index + replacement.length);
let exists = false; }
private async CreateListIfNotExists(): Promise<void> {
const result: SPHttpClientResponse = await this.context.spHttpClient.get(
this.context.pageContext.web.absoluteUrl
+ '/_api/web/lists',
SPHttpClient.configurations.v1);
// tslint:disable-next-line: no-any
const json: any = await result.json();
let exists: boolean = false;
json.value.forEach(list => { json.value.forEach(list => {
if (list.Title=='WordGameList'){ if (list.Title === 'WordGameList') {
console.log('list found'); console.log('list found');
exists = true; exists = true;
} }
}); });
console.log(json); console.log(json);
if (exists==false){ if (exists === false) {
console.log('Attempting to create list'); console.log('Attempting to create list');
await this.CreateList(); await this.CreateList();
await this.AddListColumnNumber('Score'); await this.AddListColumnNumber('Score');
@ -292,117 +348,111 @@ export class WordService {
} }
} }
async CreateListItem(score:number,seconds:number,details:string){ private async CreateListItem(score: number, seconds: number, details: string): Promise<void> {
var listMetadata = { const listMetadata: {} = {
"__metadata": { '__metadata': {
"type": "SP.Data.WordGameListListItem" 'type': 'SP.Data.WordGameListListItem'
}, },
"Title": this.context.pageContext.user.displayName, 'Title': this.context.pageContext.user.displayName,
"Score": score, 'Score': score,
"Seconds": seconds, 'Seconds': seconds,
"Details": details 'Details': details
}; };
var options: ISPHttpClientOptions = { const options: ISPHttpClientOptions = {
headers: { headers: {
"Accept": "application/json;odata=verbose", 'Accept': 'application/json;odata=verbose',
"Content-Type": "application/json;odata=verbose", 'Content-Type': 'application/json;odata=verbose',
"OData-Version": "" //Really important to specify 'OData-Version': '' // Really important to specify
}, },
body: JSON.stringify(listMetadata) body: JSON.stringify(listMetadata)
}; };
let result = await this.context.spHttpClient.post( const result: SPHttpClientResponse = await this.context.spHttpClient.post(
this.context.pageContext.web.absoluteUrl + "/_api/web/lists/GetByTitle('WordGameList')/items", SPHttpClient.configurations.v1,options); this.context.pageContext.web.absoluteUrl
let json:any = await result.json(); + "/_api/web/lists/GetByTitle('WordGameList')/items",
SPHttpClient.configurations.v1, options);
// tslint:disable-next-line: no-any
const json: any = await result.json();
console.log(json); console.log(json);
} }
async CreateList(){ private async CreateList(): Promise<void> {
var listMetadata = { const listMetadata: {} = {
"__metadata": { '__metadata': {
"type": "SP.List" 'type': 'SP.List'
}, },
"AllowContentTypes": true, 'AllowContentTypes': true,
"BaseTemplate": 100, 'BaseTemplate': 100,
"ContentTypesEnabled": true, 'ContentTypesEnabled': true,
"Description": "Holds high scores for the word game", 'Description': 'Holds high scores for the word game',
"Title": "WordGameList" 'Title': 'WordGameList'
}; };
var options: ISPHttpClientOptions = { const options: ISPHttpClientOptions = {
headers: { headers: {
"Accept": "application/json;odata=verbose", 'Accept': 'application/json;odata=verbose',
"Content-Type": "application/json;odata=verbose", 'Content-Type': 'application/json;odata=verbose',
"OData-Version": "" //Really important to specify 'OData-Version': '' // Really important to specify
}, },
body: JSON.stringify(listMetadata) body: JSON.stringify(listMetadata)
}; };
let result = await this.context.spHttpClient.post( const result: SPHttpClientResponse = await this.context.spHttpClient.post(
this.context.pageContext.web.absoluteUrl + '/_api/web/lists', SPHttpClient.configurations.v1,options); this.context.pageContext.web.absoluteUrl + '/_api/web/lists', SPHttpClient.configurations.v1, options);
let json:any = await result.json(); // tslint:disable-next-line: no-any
const json: any = await result.json();
console.log(json); console.log(json);
} }
async AddListColumnMultiLineText(name:string){ private async AddListColumnMultiLineText(name: string): Promise<void> {
var listMetadata = { const listMetadata: {} = {
'__metadata': {'type':'SP.FieldNumber'}, '__metadata': { 'type': 'SP.FieldNumber' },
'FieldTypeKind': 3, 'FieldTypeKind': 3,
'Title': name, 'Title': name
}; };
var options: ISPHttpClientOptions = { const options: ISPHttpClientOptions = {
headers: { headers: {
"Accept": "application/json;odata=verbose", 'Accept': 'application/json;odata=verbose',
"Content-Type": "application/json;odata=verbose", 'Content-Type': 'application/json;odata=verbose',
"OData-Version": "" //Really important to specify 'OData-Version': '' // Really important to specify
}, },
body: JSON.stringify(listMetadata) body: JSON.stringify(listMetadata)
}; };
let result = await this.context.spHttpClient.post( const result: SPHttpClientResponse = await this.context.spHttpClient.post(
this.context.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('WordGameList')/fields", SPHttpClient.configurations.v1,options); this.context.pageContext.web.absoluteUrl
let json:any = await result.json(); + "/_api/web/lists/getbytitle('WordGameList')/fields",
SPHttpClient.configurations.v1, options);
// tslint:disable-next-line: no-any
const json: any = await result.json();
console.log(json); console.log(json);
} }
async AddListColumnNumber(name:string){ private async AddListColumnNumber(name: string): Promise<void> {
var listMetadata = { const listMetadata: {} = {
'__metadata': {'type':'SP.FieldNumber'}, '__metadata': { 'type': 'SP.FieldNumber' },
'FieldTypeKind': 9, 'FieldTypeKind': 9,
'Title': name, 'Title': name,
'MinimumValue': 0, 'MinimumValue': 0,
'MaximumValue': 1000000 'MaximumValue': 1000000
}; };
var options: ISPHttpClientOptions = { const options: ISPHttpClientOptions = {
headers: { headers: {
"Accept": "application/json;odata=verbose", 'Accept': 'application/json;odata=verbose',
"Content-Type": "application/json;odata=verbose", 'Content-Type': 'application/json;odata=verbose',
"OData-Version": "" //Really important to specify 'OData-Version': '' // Really important to specify
}, },
body: JSON.stringify(listMetadata) body: JSON.stringify(listMetadata)
}; };
let result = await this.context.spHttpClient.post( const result: SPHttpClientResponse = await this.context.spHttpClient.post(
this.context.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('WordGameList')/fields", SPHttpClient.configurations.v1,options); this.context.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('WordGameList')/fields",
let json:any = await result.json(); SPHttpClient.configurations.v1, options);
// tslint:disable-next-line: no-any
const json: any = await result.json();
console.log(json); console.log(json);
} }
}
export class WordGameListItem{
Name:string;
Score:number;
Seconds:number;
Details:string;
constructor(name:string,score:number,seconds:number,details:string){
this.Name = name;
this.Score = score;
this.Seconds = seconds;
this.Details = details;
}
} }