# A-level Computing/AQA/Paper 1/Skeleton program/2018

This is for the new Computer Science specification (2018) - we sincerely hope you fail and mess your entire future up.

Big Ol Fat L

Roses are red, Kendall Jenner is gorgeous, Never surprise Oscar Pistorius

## Possible Section C Questions

Section C:

State the name of a user defined subroutine - CreateTileDictionary

State the name of an identifier for an array variable - Tiles, Contents, TStringArray, TIntegerArray

Give an example of instantiation - TileDictionary As New Dictionary(Of Char, Integer)

Give an example of a subroutine that returns - (1) - An integer - TTileDictionary (2) - A boolean value - QueueOfTiles.IsEmpty (3) - A string - QueueOfTiles.Remove, GetStarttingHand

Give the name of a built in function - print(), open()

Give an example of an assignment statement - MaxHandSize = 20

Give a name of a subclass that uses iteration and give an example - AddEndOfTurnTiles (For Count := 1 to NoOfEndOfTurnTiles) DO CheckWordIsValid(While...Do)

Give the name of a subclass that uses selection - GetScoreForWord(If Length(word)>7 then Score := Score+20 etc..)

Give the name of a subclass that uses exception handling - LoadALlowedWords (Try...Finally) Why has Try...Finally been used -

State the steps you would have to take in order to add 63.4 players to the game

Name the subroutine that uses a linear search algorithm - CheckWordIsValid (Follow up) Give the time complexity of a linear search- O(n), Disadvantage of Linear search - Has to look through each word step by step to find if the word is valid therefore inefficient

Recursion - N/A

Draw a class diagram for QueueOfTiles / a hierarchy chart for the program

Give the name of a method and describe its purpose-

Give an example of an abstract data structure used- a linear queue

## Have more vowels

C#:

```public void Add()
{
int RandNo = 0;
int[] Vowels = { 0, 4, 8, 14, 20 }; // A, E, I, O, U

if (Rear < MaxSize - 1)
{
if (Rnd.Next(0, 2) == 0) // 50% chance of it being a vowel
{
RandNo = Vowels[Rnd.Next(0, 5)]; // Set RandNo to one of the values inside the Vowel array
}
else // Consonants
{
do
{
RandNo = Rnd.Next(0, 26); // Generate a number between 0-25
} while (Vowels.Contains(RandNo)); // Loop again if we generate a vowel
}
Rear++;
Contents[Rear] = Convert.ToChar(65 + RandNo).ToString();
}
}
This is not exactly 50:50, I know..
The new distribution will be 10:21
```

Delphi/Pascal:

```procedure QueueOfTiles.Add();
var
Letter : Char;
VowelWanted : boolean;
IsVowel : boolean;
begin
if Rear < MaxSize - 1 then
begin
VowelWanted := (Random(2)=1); //True for 50% of calls
Rear := Rear + 1;
repeat
Letter := Char(65+Random(26));
IsVowel := (Pos(Letter, 'AEIOU')<>0); //True when letter is in AEIOU
until (IsVowel=VowelWanted);
Contents[Rear] := letter;
end;
end;

//Performance wise, this isn't the most efficient technique, it just repeatedly
//tries new letters until it gets the kind it wants vowel/consonant, but it does
//require minimal typing, and AQA isn't going to benchmark anything.
```

Java:

```void add() {
Random rnd = new Random();
if (rear < maxSize - 1) {
int randNo = rnd.nextInt(30);
rear += 1;
switch (randNo) {
case 26:
contents[rear] = (char) (65);
break;
case 27:
contents[rear] = (char) (69);
break;
case 28:
contents[rear] = (char) (73);
break;
case 29:
contents[rear] = (char) (79);
break;
case 30:
contents[rear] = (char) (85);
default:
contents[rear] = (char) (65 + randNo);
break;
}
}
}
```

Python:

```#By HAMMAD MEHMOOD, HERSCHEL GRAMMAR SCHOOL
Vowels = [0,4,8,14,20] # Letters A E I O U
ProbabilityOfVowel = random.randint(0,1) #50% chance for Vowel
if self._Rear < self._MaxSize - 1:
if ProbabilityOfVowel == 0:#If ProbabilityOfVowel is 0
RandNo = random.choice(Vowels) #Choose a random Vowel
else:
RandNo = random.randint(0, 25)
while RandNo in Vowels: #If it's a vowel
RandNo = random.randint(0, 25)#Get another number
#This repeats until it gets a consonant
self._Rear += 1
self._Contents[self._Rear] = chr(65 + RandNo)
#This will make sure the first bit gets a vowel and the second part a consonant
#By HAMMAD MEHMOOD, HERSCHEL GRAMMAR SCHOOL
```

VB.NET:

```    'by the beautiful kat pokesie @actuallypokesie on twitter dot com forward slash actuallypokesie
'this one is waaay more condensed than the last one
Dim RandNo As Integer
Dim ConstStr As String = "BCDFGHJKLMNPQRSTVWXYZ" 'Obtain random character from this string
Dim VowelStr As String = "AEIOU" 'Same here fam
If Rear < MaxSize - 1 Then
Rear += 1
RandNo = Int(Rnd() * 2)
If RandNo = 1 Then 'You want a consonant?
Contents(Rear) = ConstStr.Chars(Int(Rnd() * 21)) 'YOU GET A CONSONANT
End If
End If
End Sub
'ok thanks like comment follow share for more epic content
```

## Change the distribution of letters

Change the distribution of letters so that more common letters like 'E' are more likely to be put into a hand than 'Z'

C#:

```            public void Add()
{
int RandNo = 0;
if (Rear < MaxSize - 1)
{
int[] Value1 = { 0, 4, 8, 13, 14, 17, 18, 19 };
int[] Value2 = { 1, 2, 3, 6, 11, 12, 15, 20 };
int[] Value3 = { 5, 7, 10, 21, 22, 24 };
int[] Value5 = { 9, 16, 23, 25 };

RandNo = Rnd.Next(0, 10);
if (RandNo < 4) // 40% chance
{
RandNo = Value1[Rnd.Next(0, Value1.Length)]; // Pick a random Value1 character
}
else if (RandNo < 7) // 30% chance
{
RandNo = Value2[Rnd.Next(0, Value2.Length)]; // Pick a random Value2 character
}
else if (RandNo < 9) // 20% chance
{
RandNo = Value3[Rnd.Next(0, Value3.Length)]; // Pick a random Value3 character
}
else // 10% chance
{
RandNo = Value5[Rnd.Next(0, Value5.Length)]; // Pick a random Value5 character

}
Rear++;
Contents[Rear] = Convert.ToChar(65 + RandNo).ToString();
}
}
```

Delphi/Pascal:

```const
//Could alternatively be a local variable, but this seemed likely to be marginally kinder to memory

begin
if Rear < MaxSize - 1 then
begin
Rear := Rear + 1;
Contents[Rear] := WeightedLetters[1+Random(Length(WeightedLetters))]; //Pick a random letter from the 'weighted' array
end;
end;
```

Java:

```void add()
{
Random rnd = new Random();
int randNo = 0;
randNo = rnd.nextInt(101);
int[] letter1 = {0, 4, 8, 13, 14, 17, 18, 19};
int[] letter2 = {1, 2, 3, 6, 11, 12, 15, 20};
int[] letter3 = {5, 7, 10, 21, 22, 24};
int[] letter4 = {9, 16, 23, 25};
if(randNo <= 49)
{
randNo = letter1[rnd.nextInt(8)];
} else if(randNo <= 79){
randNo = letter2[rnd.nextInt(8)];
} else if(randNo <= 89){
randNo = letter3[rnd.nextInt(6)];
}else {
randNo = letter4[rnd.nextInt(4)];
}
rear += 1;
contents[rear] = (char)(65 + randNo);
}
//BY YA BOI JOSHUA MEMESON
```

Java: Alternative solution:

```         String letters = "aaaaaaaabbcccddddeeeeeeeeeeeefffggghhhhhhiiiiiijkllllmmnnnnnnooooooopqrrrrrsssssstttttttttuuvvwwxyyz";
ArrayList<Character> Letter_Weighted = new ArrayList<>();

{
Random rnd = new Random();
if (rear < maxSize - 1)
{
int randNo = rnd.nextInt(Letter_Weighted.size());
rear += 1;
contents[rear] = Letter_Weighted.get(randNo);
Letter_Weighted.remove(randNo);
}
}
QueueOfTiles(int maxSize)
{
for (int i = 0; i< letters.length(); i++) {
Letter_Weighted.get(i);

}
contents = new char[maxSize];
rear = -1;
this.maxSize = maxSize;
for (int count = 0; count < maxSize; count++)
{
}
}

// Done by Nima```

Python:

```import string
if self._Rear < self._MaxSize - 1:
char_amounts = { 'A': 8, 'B': 2, 'C': 3, 'D': 3, 'E': 12, 'F':3,
'G': 3, 'H': 5, 'I': 6, 'J': 1, 'K': 1, 'L': 4,
'M': 2, 'N': 6, 'O': 7, 'P': 1, 'Q': 1, 'R': 5,
'S': 6, 'T': 9, 'U': 2, 'V': 2, 'W': 2, 'X': 1,
'Y': 2, 'Z': 1
}
letters = "".join([key * char_amounts[key] for key in char_values])
self._Rear += 1
self._Contents[self._Rear] = random.choice(letters)

OR:yntaxhighlight>

<syntaxhighlight lang="vbnet">
'Solution by Matthew Woods | Havant College

Dim RandNo As Integer
Dim Set1() As Integer = {0, 4, 8, 14, 18}
Dim Set2() As Integer = {2, 11, 13, 18, 19}
Dim Set3() As Integer = {3, 7, 12, 15, 20}
Dim Set4() As Integer = {1, 5, 6, 7, 24}
Dim Set5() As Integer = {10, 21, 23, 25, 9, 16}
If Rear < MaxSize - 1 Then
RandNo = Int(Rnd() * 15)
Select Case RandNo
Case RandNo >= 0 And RandNo <= 4
RandNo = Int(Rnd() * 5)
Rear += 1
Contents(Rear) = Chr(65 + Set1(RandNo))
Case RandNo >= 5 And RandNo <= 8
RandNo = Int(Rnd() * 5)
Rear += 1
Contents(Rear) = Chr(65 + Set2(RandNo))
Case RandNo >= 9 And RandNo <= 11
RandNo = Int(Rnd() * 5)
Rear += 1
Contents(Rear) = Chr(65 + Set3(RandNo))
Case RandNo >= 12 And RandNo <= 14
RandNo = Int(Rnd() * 5)
Rear += 1
Contents(Rear) = Chr(65 + Set4(RandNo))
Case RandNo = 15
RandNo = Int(Rnd() * 6)
Rear += 1
Contents(Rear) = Chr(65 + Set5(RandNo))
End Select
End If
End Sub

'Solution by Matthew Woods | Havant College
```

VB.NET:

```    'Solution by Matthew Woods | Havant College

Dim RandNo As Integer
Dim Letters As String = "aaaaaaaabbcccddddeeeeeeeeeeeefffggghhhhhhiiiiiijkllllmmnnnnnnooooooopqrrrrrsssssstttttttttuuvvwwxyyz"
If Rear < MaxSize - 1 Then
RandNo = Int(Rnd() * Letters.Count)
Rear += 1
Contents(Rear) = Letters.Chars(RandNo)
End If
End Sub

'Solution by Matthew Woods | Havant College
```

VB.NET (Alternate):

```'Solution by Matthew Woods | Havant College

Dim RandNo As Integer
Dim Set1() As Integer = {0, 4, 8, 14, 18}
Dim Set2() As Integer = {2, 11, 13, 18, 19}
Dim Set3() As Integer = {3, 7, 12, 15, 20}
Dim Set4() As Integer = {1, 5, 6, 7, 24}
Dim Set5() As Integer = {10, 21, 23, 25, 9, 16}
If Rear < MaxSize - 1 Then
RandNo = Int(Rnd() * 15)
Select Case RandNo
Case RandNo >= 0 And RandNo <= 4
RandNo = Int(Rnd() * 5)
Rear += 1
Contents(Rear) = Chr(65 + Set1(RandNo))
Case RandNo >= 5 And RandNo <= 8
RandNo = Int(Rnd() * 5)
Rear += 1
Contents(Rear) = Chr(65 + Set2(RandNo))
Case RandNo >= 9 And RandNo <= 11
RandNo = Int(Rnd() * 5)
Rear += 1
Contents(Rear) = Chr(65 + Set3(RandNo))
Case RandNo >= 12 And RandNo <= 14
RandNo = Int(Rnd() * 5)
Rear += 1
Contents(Rear) = Chr(65 + Set4(RandNo))
Case RandNo = 15
RandNo = Int(Rnd() * 6)
Rear += 1
Contents(Rear) = Chr(65 + Set5(RandNo))
End Select
End If
End Sub

'Solution by Matthew Woods | Havant College
```

## Shuffle letter in hand

An option to reshuffle the letters in the player's hand to help to find a word.

C#:

```public static string SuffleLettersInHand(string PlayerTiles)
{
char[] array = PlayerTiles.ToCharArray();
Random Rnd = new Random();
for (int i = array.Length - 1; i > 1; i--)
{
int k = Rnd.Next(i + 1);
var value = array[k];
array[k] = array[i];
array[i] = value;
}
return new string(array);
}

private static string GetChoice()	//Asks and records the users game choice
{
string Choice;
Console.WriteLine();
Console.WriteLine("Either:");
Console.WriteLine("     enter the word you would like to play OR");
Console.WriteLine("     press 1 to display the letter values OR");
Console.WriteLine("     press 2 to shuffle letters in hand OR");
Console.WriteLine("     press 4 to view the tile queue OR");

....

private static void HaveTurn(string PlayerName, ref string PlayerTiles, ref int PlayerTilesPlayed, ref int PlayerScore, Dictionary<char, int> TileDictionary, ref QueueOfTiles TileQueue, List<string> AllowedWords, int MaxHandSize, int NoOfEndOfTurnTiles)
{
Console.WriteLine();
Console.WriteLine(PlayerName + " it is your turn.");
DisplayTilesInHand(PlayerTiles);	//Prints out all the letters the player can use to create a word.
string NewTileChoice = "2";
bool ValidChoice = false;
bool ValidWord = false;
string Choice = "";
while (!ValidChoice) //While Choice is NOT valid
{
Choice = GetChoice();
if (Choice == "1")  //press 1 to display the letter values
{
DisplayTileValues(TileDictionary, AllowedWords);	//Prints each letter and its corresponding point value
}
else if(Choice == "2")
{
PlayerTiles = SuffleLettersInHand(PlayerTiles);
DisplayTilesInHand(PlayerTiles);
}

....
```

Delphi/Pascal:

```procedure ShufflePlayerTiles (var PlayerTiles : string);
var
tempTile : char;
i : integer;
newTilePos : integer;
begin
for i := 1 to Length(PlayerTiles) do
begin
newTilePos := 1+Random(Length(PlayerTiles));
tempTile := PlayerTiles[newTilePos];
PlayerTiles[newTilePos] := PlayerTiles[i];
PlayerTiles[i]:= tempTile;
end;
end;

//...

function GetChoice() : string;

//...

writeln('     press 7 to view your tiles again OR');
writeLn('     press 8 to shuffle the letters');
writeln('     press 0 to fill hand and stop the game.');

//...

procedure HaveTurn(PlayerName : string; var PlayerTiles : string; var PlayerTilesPlayed : integer;

//...
else if Choice = '7' then
DisplayTilesInHand(PlayerTiles)
else if Choice = '8' then
begin
ShufflePlayerTiles(PlayerTiles);
DisplayTilesInHand(PlayerTiles);
end
else if Choice = '0' then
begin
ValidChoice := True;
FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize);
end

//...
```

Java:

```String handShuffle(String playerTiles)
{
Random rnd = new Random();
char oldHand[] = playerTiles.toCharArray();
char newHand[] = new char[playerTiles.length()];
for(int x = 0; x < playerTiles.length(); x++){
int position = 0;
do{
position = rnd.nextInt(oldHand.length);
}while(oldHand[position] == '0');
newHand[x] = oldHand[position];
oldHand[position] = '0';
}
String shuffled = new String(newHand);
return shuffled;
}

//ABOVE IS MY VERSION BELOW IS THE ORIGINAL

String shuffleHand(String playerTiles) {
Random rand = new Random();
int noChar = playerTiles.length();
char[] arrOfChars = playerTiles.toCharArray();
int randNo;
char randChar;
String shuffledTiles = "";
int i = 0;
while (i < noChar) {
randNo = rand.nextInt(arrOfChars.length);
while (arrOfChars[randNo] == '\$') {
randNo = rand.nextInt(arrOfChars.length);
}
randChar = arrOfChars[randNo];
arrOfChars[randNo] = '\$';
shuffledTiles = shuffledTiles + randChar;
i++;
}
return shuffledTiles;
}
//turns playerTiles into an array of characters, gets a position in the array, checks if a character has already been taken
//gets a different position of array if already chosen, gets a character from that array position, replaces character with \$ symbol once character has been taken from it
//adds character onto new shuffled tiles hand, increments the count, then returns the shuffled hand once completed loop.
```

Python:

```#By HAMMAD MEHMOOD, HERSCHEL GRAMMAR SCHOOL
# All the changes have comments, this can be further developed to reduce the score by 1 if this option is used
def SuffleLettersInHand(PlayerTiles):
ListOfTiles = list(PlayerTiles) #Makes a list with the letters of the tile
random.shuffle(ListOfTiles) #So it can use the shuffle function(for lists) to put letters in random positions
PlayerTiles = ''.join(ListOfTiles) #Make it a string again
return PlayerTiles

def HaveTurn(PlayerName, PlayerTiles, PlayerTilesPlayed, PlayerScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles):
print()
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
while not ValidChoice:
Choice = GetChoice()
if Choice == "1":
DisplayTileValues(TileDictionary, AllowedWords)
elif Choice == "2": #Display the new option
PlayerTiles = SuffleLettersInHand(PlayerTiles) #Call this function to shuffle the letters
DisplayTilesInHand(PlayerTiles) #Display the tiles again
#PlayerScore -= 1 it´s optional
elif Choice == "4":
TileQueue.Show()
elif Choice == "7":
DisplayTilesInHand(PlayerTiles)
elif Choice == "0":
ValidChoice = True
TileQueue, PlayerTiles = FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
else:
ValidChoice = True
if len(Choice) == 0:
ValidWord = False
else:
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
if ValidWord:
ValidWord = CheckWordIsValid(Choice, AllowedWords)
if ValidWord:
print()
print("Valid word")
print()
PlayerTiles, PlayerScore, PlayerTilesPlayed = UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
if not ValidWord:
print()
print("Not a valid attempt, you lose your turn.")
print()
if NewTileChoice != "4":
TileQueue, PlayerTiles = AddEndOfTurnTiles(TileQueue, PlayerTiles, NewTileChoice, Choice)
print()
print("You have played", PlayerTilesPlayed, "tiles so far in this game.")
return PlayerTiles, PlayerTilesPlayed, PlayerScore, TileQueue
#By HAMMAD MEHMOOD, HERSCHEL GRAMMAR SCHOOL
```

VB.NET:

```  Sub ShuffleTilesInHand(ByRef PlayerTiles)
Dim ShuffleArray(Len(PlayerTiles))
Dim CopyOfPlayerTiles As String = PlayerTiles
Dim Pointer As Integer = 1
Dim SecondPassComplete As Boolean = False

If Len(CopyOfPlayerTiles) Mod 2 = 0 Then
ReDim ShuffleArray(Len(PlayerTiles) + 1)
End If

For i = 1 To Len(CopyOfPlayerTiles)
ShuffleArray(i - 1) = Mid\$(CopyOfPlayerTiles, i, 1)
Next

CopyOfPlayerTiles = ""
Do Until SecondPassComplete = True
CopyOfPlayerTiles = CopyOfPlayerTiles + ShuffleArray(Pointer)
Pointer += 2
If Pointer = ShuffleArray.Length - 1 Or Pointer = ShuffleArray.Length Then

If Pointer = ShuffleArray.Length Then
SecondPassComplete = True
Else
CopyOfPlayerTiles = CopyOfPlayerTiles + ShuffleArray(Pointer)
Pointer = 0
End If
End If
Loop

PlayerTiles = CopyOfPlayerTiles

End Sub
----------------------------------------------------------------------------------------------------------------------------------------------------
Alternative Solution by Hamza Shahid

Function Shuffle(ByVal x As String)
Dim rnd As New Random
Dim substring As String = ""
For i As Integer = 0 To 10
Dim random As Integer = rnd.Next(1, x.Length - 1)
substring = x.Substring(0, random)
x = x.Substring(random, x.Length - random)
x &= substring
Next
Return x
End Function

----------------------------------------------------------------------------------------------------------------------------------------------------------
Public Sub ShuffleLetterInHand(ByRef PlayerTiles As String)
Dim random As New Random
Dim CopyOfPlayerTiles As String = PlayerTiles
Dim TilesArray() As Char = CopyOfPlayerTiles.ToCharArray
Dim rnd As Integer
Dim iTemp As Char ''This is a temporary variable

For i As Integer = 0 To TilesArray.Length - 1

If i = TilesArray.Length - 1 Then
rnd = random.Next(0, TilesArray.Length - 2)
iTemp = TilesArray(i)
TilesArray(i) = TilesArray(rnd)
TilesArray(rnd) = iTemp
Else
rnd = random.Next(i + 1, TilesArray.Length)
iTemp = TilesArray(i)
TilesArray(i) = TilesArray(rnd)
TilesArray(rnd) = iTemp
End If

Next

PlayerTiles = Nothing

For Each item In TilesArray

PlayerTiles += item

Next

Console.WriteLine("This is your shuffled hand: " & PlayerTiles)
End Sub

----------------------------------------------------------------------------------------------------------------------------------------------------------

Function ShuffleTiles(ByVal PlayerTiles As String)
Dim ArrayLength As Integer = PlayerTiles.Length() - 1
Dim TilesToShuffle(ArrayLength) As String
Dim TileReference As Integer
Dim ResolvedTiles As String = ""

For count = 0 To ArrayLength
TilesToShuffle(count) = PlayerTiles(count)
Next

For count = 0 To ArrayLength                  ' This loop just takes a random position from the TilesToShuffle array where the value of the array position is not "-",
TileReference = CInt(Rnd() * ArrayLength) ' adds it to the string to be output and replaces the value that was used with a "-" so it is not used again.
Do While TilesToShuffle(TileReference) = "-"
TileReference = CInt(Rnd() * ArrayLength)
Loop
ResolvedTiles += TilesToShuffle(TileReference)
TilesToShuffle(TileReference) = "-"
Next

Return ResolvedTiles
End Function
```

## Allow players to skip and end their turn

Allow players to skip a turn and end their turn by drawing three or more letters

C#:

```static int RandomNumber = 3;
private static void AddEndOfTurnTiles(ref QueueOfTiles TileQueue, ref string PlayerTiles, string NewTileChoice, string Choice)
{
int NoOfEndOfTurnTiles = 0;
if (NewTileChoice == "1")
{
NoOfEndOfTurnTiles = Choice.Length;
}
else if (NewTileChoice == "2")
{
NoOfEndOfTurnTiles = 3;
}
else if (NewTileChoice == "99")
{
NoOfEndOfTurnTiles = RandomNumber;
}
else
{
NoOfEndOfTurnTiles = Choice.Length + 3;
}
for (int Count = 0; Count < NoOfEndOfTurnTiles; Count++)
{
PlayerTiles = PlayerTiles + TileQueue.Remove();
}
}

private static string GetChoice()
{
string Choice;
Console.WriteLine();
Console.WriteLine("Either:");
Console.WriteLine("     enter the word you would like to play OR");
Console.WriteLine("     press 1 to display the letter values OR");
Console.WriteLine("     press 4 to view the tile queue OR");
Console.WriteLine("     press 7 to view your tiles again OR");
Console.WriteLine("     press 8 to skip a turn OR");
Console.WriteLine("     press 0 to fill hand and stop the game.");
Console.Write("> ");
Console.WriteLine();
Choice = Choice.ToUpper();
return Choice;
}

private static void HaveTurn(string PlayerName, ref string PlayerTiles, ref int PlayerTilesPlayed, ref int PlayerScore, Dictionary<char, int> TileDictionary, ref QueueOfTiles TileQueue, List<string> AllowedWords, int MaxHandSize, int NoOfEndOfTurnTiles)
{
Console.WriteLine();
Console.WriteLine(PlayerName + " it is your turn.");
DisplayTilesInHand(PlayerTiles);
string NewTileChoice = "2";
bool ValidChoice = false;
bool ValidWord = false;
string Choice = "";
while (!ValidChoice)
{
Choice = GetChoice();
if (Choice == "1")
{
DisplayTileValues(TileDictionary, AllowedWords);
}
else if (Choice == "4")
{
TileQueue.Show();
}
else if (Choice == "7")
{
DisplayTilesInHand(PlayerTiles);
}
else if (Choice == "8")
{
ValidChoice = true;
Random rand = new Random();
RandomNumber = rand.Next(0, 5) + 3;
Console.WriteLine("Skip Turn - You will get " + RandomNumber + " Extra Letters ");
AddEndOfTurnTiles(ref TileQueue, ref PlayerTiles, "99", Choice);
}
else if (Choice == "0")
{
ValidChoice = true;
FillHandWithTiles(ref TileQueue, ref PlayerTiles, MaxHandSize);
}
else
{
ValidChoice = true;
if (Choice.Length == 0)
{
ValidWord = false;
}
else
{
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles);
}
if (ValidWord)
{
ValidWord = CheckWordIsValid(Choice, AllowedWords);
if (ValidWord)
{
Console.WriteLine();
Console.WriteLine("Valid word");
Console.WriteLine();
UpdateAfterAllowedWord(Choice, ref PlayerTiles, ref PlayerScore, ref PlayerTilesPlayed, TileDictionary, AllowedWords);
NewTileChoice = GetNewTileChoice();
}
}
if (!ValidWord)
{
Console.WriteLine();
Console.WriteLine("Not a valid attempt, you lose your turn.");
Console.WriteLine();
}
if (NewTileChoice != "4")
{
AddEndOfTurnTiles(ref TileQueue, ref PlayerTiles, NewTileChoice, Choice);
}
Console.WriteLine();
Console.WriteLine("Your new score is:" + PlayerScore);
Console.WriteLine("You have played " + PlayerTilesPlayed + " tiles so far in this game.");
}
}
}
```

Delphi/Pascal:

```procedure AddEndOfTurnTiles(var TileQueue : QueueOfTiles; var PlayerTiles : string; NewTileChoice : string; Choice : string; AdditionalLetters : integer = 3);
//Implemented a 'default parameter', it's not required for the other calls (defaults to 3), but I can use it to specify otherwise
//http://wiki.freepascal.org/Default_parameter
var
NoOfEndOfTurnTiles : integer;
Count : integer;
begin
if NewTileChoice = '1' then
NoOfEndOfTurnTiles := length(Choice)
else if NewTileChoice = '2' then
else
NoOfEndOfTurnTiles := length(Choice) + 3;
for Count := 1 to NoOfEndOfTurnTiles do
begin
PlayerTiles := PlayerTiles + TileQueue.Remove();
end;
end;

function GetChoice() : string;
//...
writeln('     press 1 to display the letter values OR');
writeLn('     press 2 to skip turn and pick up at least 3 letters (random)');
writeln('     press 4 to view the tile queue OR');
//...

procedure HaveTurn(PlayerName : string; var PlayerTiles : string; var PlayerTilesPlayed : integer;

//...

if Choice = '1' then
DisplayTileValues(TileDictionary, AllowedWords)
else if Choice = '2' then
begin
ValidChoice := True;
AddEndOfTurnTiles(TileQueue, PlayerTiles, '2', '', 3 + Random(5));
DisplayTilesInHand(PlayerTiles);
end
else if Choice = '4' then
TileQueue.Show()

//...
```

Java:

```	int RandomNumber = 3;

String newTileChoice, String choice)
{
int noOfEndOfTurnTiles;
if(newTileChoice.equals("1"))
{
noOfEndOfTurnTiles = choice.length();
}
else if(newTileChoice.equals("2"))
{
noOfEndOfTurnTiles = 3;
}
else if (newTileChoice.equals("99"))
{
int NumberOfTiles = Integer.parseInt(newTileChoice);
noOfEndOfTurnTiles = RandomNumber;
}
else
{
noOfEndOfTurnTiles = choice.length()+3;
}
for (int count = 0; count < noOfEndOfTurnTiles; count++)
{
playerTiles.playerTiles += tileQueue.remove();
}
}

String getChoice()
{
Console.println();
Console.println("Either:");
Console.println("     enter the word you would like to play OR");
Console.println("     press 1 to display the letter values OR");
Console.println("     press 4 to view the tile queue OR");
Console.println("     press 7 to view your tiles again OR");
Console.println("     press 8 to skip a turn OR");
Console.println("     press 0 to fill hand and stop the game.");
Console.print("> ");
Console.println();
choice = choice.toUpperCase();
return choice;
}

void haveTurn(String playerName, Tiles playerTiles,
TileCount playerTilesPlayed, Score playerScore, Map tileDictionary,
QueueOfTiles tileQueue, String[] allowedWords, int maxHandSize,
int noOfEndOfTurnTiles)
{
Console.println();
Console.println(playerName + " it is your turn.");
displayTilesInHand(playerTiles.playerTiles);
String newTileChoice = "2";
boolean validChoice = false;
boolean validWord;
while (!validChoice)
{
String choice = getChoice();
if (choice.equals("1"))
{
displayTileValues(tileDictionary, allowedWords);
}
else if (choice.equals("4"))
{
tileQueue.show();
}
else if (choice.equals("7"))
{
displayTilesInHand(playerTiles.playerTiles);
}
else if (choice.equals("0"))
{
validChoice = true;
fillHandWithTiles(tileQueue, playerTiles, maxHandSize);
}
else if (choice.equals("8")) {
validChoice = true;
Random rand = new Random();
int RN = rand.nextInt(5) + 3;
RandomNumber = RN;
Console.println("Skip Turn - You will get " + RandomNumber + " Extra Letters ");
}
else
{
validChoice = true;
if (choice.length() == 0)
{
validWord = false;
}
else
{
validWord = checkWordIsInTiles(choice, playerTiles.playerTiles);
}
if (validWord)
{
validWord = checkWordIsValid(choice, allowedWords);
if (validWord)
{
Console.println();
Console.println("Valid word");
Console.println();
updateAfterAllowedWord(choice, playerTiles, playerScore,
playerTilesPlayed, tileDictionary, allowedWords);
newTileChoice = getNewTileChoice();
}
}
if (!validWord)
{
Console.println();
Console.println("Not a valid attempt, you lose your turn.");
Console.println();
}
if (!newTileChoice.equals("4"))
{
}
Console.println();
Console.println("Your new score is:" + playerScore.score);
Console.println("You have played " + playerTilesPlayed.numberOfTiles + " tiles so far in this game.");
}
}
}
```

Python:

```def AddEndOfTurnTiles(TileQueue, PlayerTiles, NewTileChoice, Choice):
if NewTileChoice == "1":
NoOfEndOfTurnTiles = len(Choice)
elif NewTileChoice == "2":
NoOfEndOfTurnTiles = 3
elif NewTileChoice == "99":
NoOfEndOfTurnTiles = 3 + random.randint(0,5)
print("You have drawn {} tiles".format(NoOfEndOfTurnTiles))
else:
NoOfEndOfTurnTiles = len(Choice) + 3
for Count in range(NoOfEndOfTurnTiles):
PlayerTiles += TileQueue.Remove()
return TileQueue, PlayerTiles

def GetChoice():
print()
print("Either:")
print("     enter the word you would like to play OR")
print("     press 1 to display the letter values OR")
print("     press 4 to view the tile queue OR")
print("     press 7 to view your tiles again OR")
print("     press 8 to skip your turn and draw 3 or more tiles OR")
print("     press 0 to fill hand and stop the game.")
Choice = input(">")
print()
Choice = Choice.upper()
return Choice

def HaveTurn(PlayerName, PlayerTiles, PlayerTilesPlayed, PlayerScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles):
print()
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
while not ValidChoice:
Choice = GetChoice()
if Choice == "1":
DisplayTileValues(TileDictionary, AllowedWords)
elif Choice == "4":
TileQueue.Show()
elif Choice == "7":
DisplayTilesInHand(PlayerTiles)
elif Choice == "0":
ValidChoice = True
TileQueue, PlayerTiles = FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
elif Choice == "8":
TileQueue, PlayerTiles = AddEndOfTurnTiles(TileQueue, PlayerTiles, "99", Choice)  # call AddEndOfTurnTiles and pass '99' as NewTileChoice
DisplayTilesInHand(PlayerTiles)
ValidChoice = True  # set the flag to True to break out of loop
else:
ValidChoice = True
if len(Choice) == 0:
ValidWord = False
else:
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
if ValidWord:
ValidWord = CheckWordIsValid(Choice, AllowedWords)
if ValidWord:
print()
print("Valid word")
print()
PlayerTiles, PlayerScore, PlayerTilesPlayed = UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
if not ValidWord:
print()
print("Not a valid attempt, you lose your turn.")
print()
if NewTileChoice != "4":
TileQueue, PlayerTiles = AddEndOfTurnTiles(TileQueue, PlayerTiles, NewTileChoice, Choice)
print()
print("You have played", PlayerTilesPlayed, "tiles so far in this game.")
return PlayerTiles, PlayerTilesPlayed, PlayerScore, TileQueue
```

VB.NET:

```Sub AddEndOfTurnTiles(ByRef TileQueue As QueueOfTiles, ByRef PlayerTiles As String, ByVal NewTileChoice As String, ByVal Choice As String)

Dim NoOfEndOfTurnTiles As Integer
If NewTileChoice = "1" Then
NoOfEndOfTurnTiles = Len(Choice)
ElseIf NewTileChoice = "2" Then
NoOfEndOfTurnTiles = 3

' new else if created. deals three penalty card.
ElseIf NewTileChoice = "9" Then

NoOfEndOfTurnTiles = 3

Else
NoOfEndOfTurnTiles = Len(Choice) + 3
End If
For Count = 0 To NoOfEndOfTurnTiles - 1
PlayerTiles += TileQueue.Remove()
Next
End Sub

Function GetChoice()
Dim Choice As String
Console.WriteLine()
Console.WriteLine("Either:")
Console.WriteLine("     enter the word you would like to play OR")
Console.WriteLine("     press 1 to display the letter values OR")
Console.WriteLine("     press 4 to view the tile queue OR")
Console.WriteLine("     press 7 to view your tiles again OR")

' this is new command line created.
Console.WriteLine("     press 9 to skip your turn and draw penalty cards OR")

Console.WriteLine("     press 0 to fill hand and stop the game.")
Console.Write("> ")
Console.WriteLine()
Choice = Choice.ToUpper()
Return Choice
End Function

Sub HaveTurn(ByVal PlayerName As String, ByRef PlayerTiles As String, ByRef PlayerTilesPlayed As String, ByRef PlayerScore As Integer, ByVal TileDictionary As Dictionary(Of Char, Integer), ByRef TileQueue As QueueOfTiles, ByRef AllowedWords As List(Of String), ByVal MaxHandSize As Integer, ByVal NoOfEndOfTurnTiles As Integer)
Dim NewTileChoice As String
Dim Choice As String
Dim ValidChoice As Boolean
Dim ValidWord As Boolean
Console.WriteLine()
Console.WriteLine(PlayerName & " it is your turn.")
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
While Not ValidChoice
Choice = GetChoice()
If Choice = "1" Then
DisplayTileValues(TileDictionary, AllowedWords)
ElseIf Choice = "4" Then
TileQueue.Show()
ElseIf Choice = "7" Then
DisplayTilesInHand(PlayerTiles)

' new statement for the skip.
ElseIf Choice = "9" Then

' Allows the code to continue running
ValidChoice = True

' called function which draws three penalty card

' text output to alert the player of the penalty
Console.WriteLine("Number of new tiles added is 3")

ElseIf Choice = "0" Then
ValidChoice = True
FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
Else
ValidChoice = True
If Len(Choice) = 0 Then
ValidWord = False
Else
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
End If
If ValidWord Then
ValidWord = CheckWordIsValid(Choice, AllowedWords)
If ValidWord Then
Console.WriteLine()
Console.WriteLine("Valid word")
Console.WriteLine()
UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
End If
End If
If Not ValidWord Then
Console.WriteLine()
Console.WriteLine("Not a valid attempt, you lose your turn.")
Console.WriteLine()
End If
If NewTileChoice <> "4" Then
End If
Console.WriteLine()
Console.WriteLine("Your word was: " & Choice)
Console.WriteLine("Your new score is: " & PlayerScore)
Console.WriteLine("You have played " & PlayerTilesPlayed & " tiles so far in this game.")
End If
End While
End Sub
```

## When a number other than 1, 4, 7 or 0 is entered, the program shouldn't use that as a word attempt

When a number other than 1, 4, 7 or 0 is entered the program shouldn't use that as a word attempt (adding validation to GetChoice)

C#:

```        private static string GetChoice()
{
string Choice = "";
string[] ValidChoice = { "1", "4", "7", "0" };
bool bLoop = true;
while (bLoop)
{
Console.WriteLine();
Console.WriteLine("Either:");
Console.WriteLine("     enter the word you would like to play OR");
Console.WriteLine("     press 1 to display the letter values OR");
Console.WriteLine("     press 4 to view the tile queue OR");
Console.WriteLine("     press 7 to view your tiles again OR");
Console.WriteLine("     press 0 to fill hand and stop the game.");
Console.Write("> ");
Console.WriteLine();
Choice = Choice.ToUpper();

if (Char.IsDigit(Choice[0]) && Array.IndexOf(ValidChoice, Choice) == -1)
Console.WriteLine("Noooooooo! Invalid choice");
else
bLoop = false;
}
return Choice;
}
```

Delphi/Pascal:

```//Been at this for ages, this is the only way i can find to get this working, if anyone else has a more efficient method please replace
//Edit not sure if this is a good way of doing it but I thought of checking string to int conversion,sorry if this is wrong!
//Create a new function checkchoice for the purposes of this check
function CheckChoice(Choice : string) : boolean;
begin
try
strtoint(Choice);
CheckChoice:=true;
except
CheckChoice:=false;
end;

end;

//Then make these modifications with the Getchoice function and it should work
function GetChoice() : string;
var
Choice : string;
Check : Boolean;
begin
repeat
writeln;
writeln('Either:');
writeln('     enter the word you would like to play OR');
writeln('     press 1 to display the letter values OR');
writeln('     press 4 to view the tile queue OR');
writeln('     press 7 to view your tiles again OR');
writeln('     press 0 to fill hand and stop the game.');
write('> ');
Check := CheckChoice(Choice);
if CheckChoice(choice) = false then
writeln('Invalid input try again');
until Check = True;
writeln;
Choice := UpperCase(Choice);
GetChoice := Choice;
end;
```

Java:

```    void haveTurn(String playerName, Tiles playerTiles,
TileCount playerTilesPlayed, Score playerScore, Map tileDictionary,
QueueOfTiles tileQueue, String[] allowedWords, int maxHandSize,
int noOfEndOfTurnTiles)
{
Console.println();
Console.println(playerName + " it is your turn.");
displayTilesInHand(playerTiles.playerTiles);
String newTileChoice = "2";
boolean validChoice = false;
boolean validWord;
while (!validChoice)
{
String choice = getChoice();
boolean choicecorrect = false;
while (choicecorrect) {
if (choice.equals("1"))
{
choicecorrect = true;
displayTileValues(tileDictionary, allowedWords);
}
else if (choice.equals("4"))
{
choicecorrect = true;
tileQueue.show();
}
else if (choice.equals("7"))
{
choicecorrect = true;
displayTilesInHand(playerTiles.playerTiles);
}
else if (choice.equals("0"))
{
choicecorrect = true;
validChoice = true;
fillHandWithTiles(tileQueue, playerTiles, maxHandSize);
}
else if (choice.equals("2") || choice.equals("3") || choice.equals("5") || choice.equals("6") || choice.equals("8") || choice.equals("9") || choice.equals("1")) {
choicecorrect = false;
}
else
{
choicecorrect = true;
validChoice = true;
if (choice.length() == 0)
{
validWord = false;
}
else
{
validWord = checkWordIsInTiles(choice, playerTiles.playerTiles);
}
if (validWord)
{
validWord = checkWordIsValid(choice, allowedWords);
if (validWord)
{
Console.println();
Console.println("Valid word");
Console.println();
updateAfterAllowedWord(choice, playerTiles, playerScore,
playerTilesPlayed, tileDictionary, allowedWords);
newTileChoice = getNewTileChoice();
}
}
if (!validWord)
{
Console.println();
Console.println("Not a valid attempt, you lose your turn.");
Console.println();
}
if (!newTileChoice.equals("4"))
{
}
Console.println();
Console.println("Your new score is:" + playerScore.score);
Console.println("You have played " + playerTilesPlayed.numberOfTiles + " tiles so far in this game.");
}
}
}
}
```

Python:

```#Insert into the 'GetChoice' function

if Choice.lstrip('-').isdigit():
ValidNum = False
while ValidNum == False:
if Choice in ["1","4","7","0"]:
ValidNum = True
else:
raw_input = input("Please enter a valid number")
Choice = raw_input(">")
```

VB.NET:

```Function GetChoice()
Dim Choice As String

' Set as False so whenever this function is called, the value is
' reset.
Dim Check As Boolean = False

' Added do loop which will continue this section of the code until
' a specific condition is met. In this case we created boolean variable
' which shows if the check function has passed or failed.
Do

Console.WriteLine()
Console.WriteLine("Either:")
Console.WriteLine("     enter the word you would like to play OR")
Console.WriteLine("     press 1 to display the letter values OR")
Console.WriteLine("     press 4 to view the tile queue OR")
Console.WriteLine("     press 7 to view your tiles again OR")
Console.WriteLine("     press 0 to fill hand and stop the game.")
Console.Write("> ")
Console.WriteLine()

' ChoiceCheck is new function created for this purpose.
Check = ChoiceCheck(Choice)

' If statement which output a message when function returns false.
If Check = False Then
Console.WriteLine("Invalid Input. Please enter correct option")

End If

' Loops until the check clears.
Loop Until Check = True
Choice = Choice.ToUpper()
Return Choice
End Function

' New function written for the check.
Function ChoiceCheck(ByVal Choice As String) As Boolean

' To be fair, this could be more steramlined. This is only way i could
' immediatly think of.
If Choice = "1" Or Choice = "4" Or Choice = "7" Or Choice = "0" Then
Return True

' not in the spec but this will prevent return key being registered as valid attemp.
ElseIf Choice = "" Then
Return False

Else
Return False

End If

End Function
```

Alternative Solution By Big Heny Jnes

```Choice = GetChoice()
Checker = RemoveInvalidCharacters(Choice)
If Checker = False Then
Else
Try
Number = CInt(Choice)
Catch
Checker = True
End Try
If Number < 0 Or Number = 2 Or Number = 3 Or Number = 5 Or Number = 6 Or Number > 7 Then
Checker = False
End If
If Choice = "1" Then
DisplayTileValues(TileDictionary, AllowedWords)
ElseIf Choice = "4" Then
TileQueue.Show()
ElseIf Choice = "7" Then
DisplayTilesInHand(PlayerTiles)
ElseIf Choice = "0" Then
ValidChoice = True
FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
ElseIf Checker = False Then
Else
ValidChoice = True
If Len(Choice) = 0 Then
ValidWord = False
Else
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
End If
If ValidWord Then
ValidWord = CheckWordIsValid(Choice, AllowedWords)
If ValidWord Then
Console.WriteLine()
Console.WriteLine("Valid word")
Console.WriteLine()
UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
End If
End If
If Not ValidWord Then
Console.WriteLine()
Console.WriteLine("Not a valid attempt, you lose your turn.")
Console.WriteLine()
End If
If NewTileChoice <> "4" Then
End If
Console.WriteLine()
Console.WriteLine("Your word was: " & Choice)
Console.WriteLine("Your new score is: " & PlayerScore)
Console.WriteLine("You have played " & PlayerTilesPlayed & " tiles so far in this game.")
End If
End If
End While
End Sub

Function RemoveInvalidCharacters(ByVal Choice As String) As Boolean
Dim FinalOutput As String = ""
Dim Check As Boolean
Dim Value As Integer
Dim x As Integer = -1
Do
x += 1
Value = Asc(Choice.Substring(x, 1))
If Value > 96 And Value < 123 Then
Value -= 32
End If
If (Value >= 65 And Value <= 90) Or (Value >= 48 And Value <= 57) Then
Check = True
Else
Check = False
End If
Loop Until Check = False Or x = Choice.Length - 1
Return Check
End Function
```

Alternative Solution by FatMatt

```Sub HaveTurn(ByVal PlayerName As String, ByRef Turd As String, ByRef PlayerTilesPlayed As String, ByRef PlayerScore As Integer, ByVal TileDictionary As Dictionary(Of Char, Integer), ByRef TileQueue As QueueOfTiles, ByRef AllowedWords As List(Of String), ByVal MaxHandSize As Integer, ByVal NoOfEndOfTurnTiles As Integer)
Dim NewTileChoice As String
Dim Choice As String
Dim ValidChoice As Boolean
Dim ValidWord As Boolean
Console.WriteLine()
Console.WriteLine(PlayerName & " it is your turn.")
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
While Not ValidChoice
Choice = GetChoice()
If Choice = "1" Then
DisplayTileValues(TileDictionary, AllowedWords)
ElseIf Choice = "4" Then
TileQueue.Show()
ElseIf Choice = "7" Then
DisplayTilesInHand(PlayerTiles)
ElseIf Choice = "0" Then
ValidChoice = True
FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
ElseIf IsNumeric(Choice) Then
Console.WriteLine("Invalid input")
```

Alternative Solution By Hamza Shahid

``` Function GetChoice()

Dim Choice As String

Console.WriteLine()
Console.WriteLine("Either:")
Console.WriteLine("     enter the word you would like to play OR")
Console.WriteLine("     press 1 to display the letter values OR")
Console.WriteLine("     press 2 to swap your letters OR")
Console.WriteLine("     press 4 to view the tile queue OR")
Console.WriteLine("     press 7 to view your tiles again OR")
Console.WriteLine("     press 8 to add extra words to the Valid words list OR")
Console.WriteLine("     press 9 to view score table")
Console.WriteLine("     press 0 to fill hand and stop the game.")

Console.Write("> ")
Dim i = 1
Dim legalnums As String = "1247890"
Dim digits = "0123456789"
legalnums = legalnums.ToCharArray()
While i > 0
For Each item As String In digits
If Choice.Contains(item) And digits.Contains(Choice) = False Then
Console.WriteLine("INVALID INPUT")
Else
Choice = Choice
i = 0
End If
Next
End While
Console.WriteLine()
Choice = Choice.ToUpper()

Return Choice

End Function
```

## Save Game Feature

A feature that allows the user to save the game

C#:

``` private static void SaveGame
(int PlayerOneScore, int PlayerTwoScore, string PlayerOneTiles, string PlayerTwoTiles
,int PlayerOneTilesPlayed, int PlayerTwoTilesPlayed)
{
using(StreamWriter sw = new StreamWriter(fName))
{
/* Writes game details to file in one go using a formatted string. */
sw.Write(
String.Format("{0},{1},{2}{6}{3},{4},{5}{6}"
,PlayerOneScore,PlayerOneTilesPlayed,PlayerOneTiles
,PlayerTwoScore,PlayerTwoTilesPlayed,PlayerTwoTiles
,Environment.NewLine) /* Environment.NewLine is used because the characters for a new line are platform dependent*/
);
}
Console.WriteLine("Game saved as {0}!", fName);
}
private static void PlayGame(List<string> AllowedWords, Dictionary<char, int> TileDictionary, bool RandomStart, int StartHandSize, int MaxHandSize, int MaxTilesPlayed, int NoOfEndOfTurnTiles)
{
/* Unchanged AQA code has been omitted from the top of this method */
while (PlayerOneTilesPlayed <= MaxTilesPlayed && PlayerTwoTilesPlayed <= MaxTilesPlayed && PlayerOneTiles.Length < MaxHandSize && PlayerTwoTiles.Length < MaxHandSize)
{
HaveTurn("Player One", ref PlayerOneTiles, ref PlayerOneTilesPlayed, ref PlayerOneScore, TileDictionary, ref TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles);
Console.WriteLine();
Console.WriteLine("Press Enter to continue");
Console.WriteLine();
HaveTurn("Player Two", ref PlayerTwoTiles, ref PlayerTwoTilesPlayed, ref PlayerTwoScore, TileDictionary, ref TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles);
Console.WriteLine("Press 1 to save the game.");
if (Console.ReadLine().Equals("1")) /* Save the game */
{
SaveGame(PlayerOneScore, PlayerTwoScore, PlayerOneTiles, PlayerTwoTiles, PlayerOneTilesPlayed, PlayerTwoTilesPlayed);
}
}
/* Unchanged AQUA code has been omitted from the bottom of this method */
}
```

Delphi/Pascal:

```//Definitely not the most efficient way of doing it, but it works

procedure SaveGame(PlayerOneScore:integer;PlayerTwoScore:integer;PlayerOneTilesPlayed:integer;PlayerTwoTilesPlayed:integer;PlayerOneTiles:string;PlayerTwoTiles:string);
var
TFin:TextFile;
FileName:string;
begin
WriteLn('Please enter a file name for save:');
FileName:=FileName+'.txt';
AssignFile(TFin,FileName);
Rewrite(TFin);
writeln(TFin,PlayerOneScore);
writeln(TFin,PlayerTwoScore);
writeln(TFin,PlayerOneTilesPlayed);
writeln(TFin,PlayerTwoTilesPlayed);
writeln(TFin,PlayerOneTiles);
writeln(TFin,PlayerTwoTiles);
CloseFile(TFin);
end;
```

Java:

Python:

```def LoadGame():
SaveFile = open("save.txt",'r')
PlayerOneData = lines[0].replace("\n","").split("|")
PlayerTwoData = lines[1].replace("\n","").split("|")
TileQueueRaw = list(lines[2].replace("\n",""))
TileQueue = QueueOfTiles(len(TileQueueRaw))
TileQueue._Contents = TileQueueRaw
SaveFile.close()
return PlayerOneData,PlayerTwoData,TileQueue

def SaveGame(PlayerData,TileQueue):
if os.path.exists("save.txt"):
os.remove("save.txt")
SaveFile = open("save.txt",'a')
for data in PlayerData:
for item in data:
SaveFile.write(str(item))
if not item == data[-1]: SaveFile.write("|")
SaveFile.write("\n")
TileQueueLetters = "".join(TileQueue._Contents)
SaveFile.write(TileQueueLetters+"\n")
SaveFile.close()

def PlayGame(AllowedWords, TileDictionary, RandomStart, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles, Load=False):
PlayerOneScore = 50
PlayerTwoScore = 50
PlayerOneTilesPlayed = 0
PlayerTwoTilesPlayed = 0
TileQueue = QueueOfTiles(20)
if RandomStart:
PlayerOneTiles = GetStartingHand(TileQueue, StartHandSize)
PlayerTwoTiles = GetStartingHand(TileQueue, StartHandSize)
else:
PlayerOneTiles = "BTAHANDENONSARJ"
PlayerTwoTiles = "CELZXIOTNESMUAA"
else:
try:
PlayerOneScore = int(PlayerOneScore)
PlayerTwoScore = int(PlayerTwoScore)
PlayerOneTilesPlayed = int(PlayerOneTilesPlayed)
PlayerTwoTilesPlayed = int(PlayerTwoTilesPlayed)
except:
print()
print()
return False

while PlayerOneTilesPlayed <= MaxTilesPlayed and PlayerTwoTilesPlayed <= MaxTilesPlayed and len(PlayerOneTiles) < MaxHandSize and len(PlayerTwoTiles) < MaxHandSize:
PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileQueue = HaveTurn("Player One", PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles)
print()
input("Press Enter to continue")
print()
PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileQueue = HaveTurn("Player Two", PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles)
print()
if input("Would you like to save the game? (Y/N)").lower() == "y":
PlayerOneData = (PlayerOneScore,PlayerOneTilesPlayed,PlayerOneTiles)
PlayerTwoData = (PlayerTwoScore,PlayerTwoTilesPlayed,PlayerTwoTiles)
SaveGame((PlayerOneData,PlayerTwoData),TileQueue)

DisplayWinner(PlayerOneScore, PlayerTwoScore)

print()
print("=========")
print("=========")
print()
print("1. Play game with random start hand")
print("2. Play game with training start hand")
print("9. Quit")
print()

def Main():
print("++++++++++++++++++++++++++++++++++++++")
print("+ Welcome to the WORDS WITH AQA game +")
print("++++++++++++++++++++++++++++++++++++++")
print()
print()
TileDictionary = CreateTileDictionary()
MaxHandSize = 20
MaxTilesPlayed = 50
NoOfEndOfTurnTiles = 3
StartHandSize = 15
Choice = ""
while Choice != "9":
Choice = input("Enter your choice: ")
if Choice == "1":
PlayGame(AllowedWords, TileDictionary, True, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles)
elif Choice == "2":
PlayGame(AllowedWords, TileDictionary, False, 15, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles)
elif Choice == "3":
if PlayGame(AllowedWords, TileDictionary, True, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles,Load=True) is False: Main()
```

Python (Json):

```#Python 3.6+
#The original solution used Pickle to serialise the TileQueue object however pickle is not on the spec and is Python specific
#Json is on the spec therefore it would be more relevant if the solution was implemented solely in Json, plus its 'cleaner'

import json, sys

def saveGame(flag, PlayerOneScore, PlayerOneTilesPlayed,  PlayerOneTiles, PlayerTwoScore, PlayerTwoTilesPlayed, PlayerTwoTiles, TileQueue):
game_data = {'flag':flag, 'player1data': [PlayerOneScore, PlayerOneTilesPlayed,  PlayerOneTiles], 'player2data':[PlayerTwoScore, PlayerTwoTilesPlayed, PlayerTwoTiles], 'queue_obj': TileQueue.__dict__ }
json.dump(game_data, open('save.txt','w'), separators=(',', ': '))
print('saved')

TileQueue = QueueOfTiles(20).__dict__ = game_data['queue_obj']
return game_data, TileQueue

def PlayGame(AllowedWords, TileDictionary, RandomStart, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles, load=0):
flag = 1
PlayerOneScore = 50
PlayerTwoScore = 50
PlayerOneTilesPlayed = 0
PlayerTwoTilesPlayed = 0
TileQueue = QueueOfTiles(20)

if RandomStart:
PlayerOneTiles = GetStartingHand(TileQueue, StartHandSize)
PlayerTwoTiles = GetStartingHand(TileQueue, StartHandSize)
else:
PlayerOneTiles = "BTAHANDENONSARJ"
PlayerTwoTiles = "CELZXIOTNESMUAA"

else:
try:
except BaseException as e:
print(f'Error: Unable to load game -> {e}', file=sys.stderr)
return

flag = game_data['flag']
PlayerOneScore = game_data['player1data'][0]
PlayerTwoScore = game_data['player2data'][0]
PlayerOneTilesPlayed = game_data['player1data'][1]
PlayerTwoTilesPlayed = game_data['player2data'][1]
PlayerOneTiles = game_data['player1data'][-1]
PlayerTwoTiles = game_data['player2data'][-1]

while PlayerOneTilesPlayed <= MaxTilesPlayed and PlayerTwoTilesPlayed <= MaxTilesPlayed and len(PlayerOneTiles) < MaxHandSize and len(PlayerTwoTiles) < MaxHandSize:
if flag:
flag = 0
PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileQueue = HaveTurn("Player One", PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles)
else:
flag = 1
PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileQueue = HaveTurn("Player Two", PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles)

print()
choice = input("Press Enter to continue or type save to save game: ")
if choice == "save":
try:
saveGame(flag, PlayerOneScore, PlayerOneTilesPlayed,  PlayerOneTiles, PlayerTwoScore, PlayerTwoTilesPlayed, PlayerTwoTiles, TileQueue)
except BaseException as e:
print(f'Error: Unable to save game -> {e}', file=sys.stderr)
print()

print()
print("=========")
print("=========")
print()
print("1. Play game with random start hand")
print("2. Play game with training start hand")
print("9. Quit")
print()

def Main():
print("++++++++++++++++++++++++++++++++++++++")
print("+ Welcome to the WORDS WITH AQA game +")
print("++++++++++++++++++++++++++++++++++++++")
print()
print()
TileDictionary = CreateTileDictionary()
MaxHandSize = 20
MaxTilesPlayed = 50
NoOfEndOfTurnTiles = 3
StartHandSize = 15
Choice = ""
while Choice != "9":
Choice = input("Enter your choice: ")
if Choice == "1":
PlayGame(AllowedWords, TileDictionary, True, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles)
elif Choice == "2":
PlayGame(AllowedWords, TileDictionary, False, 15, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles)
elif Choice == '3':
PlayGame(AllowedWords, TileDictionary, False, 15, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles, load=1)
```

VB.NET:

```Sub SaveGame(ByVal PlayerName As String, ByRef PlayerTiles As String, ByRef PlayerTilesPlayed As String, ByRef PlayerScore As Integer)
Dim SaveFileText As New List(Of String)
End While
Dim SaveFileWriter As New IO.StreamWriter("savegame.txt")
If PlayerName = "Player One" Then
SaveFileWriter.WriteLine(PlayerName & ControlChars.Tab & PlayerTiles & ControlChars.Tab & PlayerTilesPlayed & ControlChars.Tab & PlayerScore)
If SaveFileText.Count <> 0 Then
SaveFileWriter.WriteLine(SaveFileText(1))
Else
SaveFileWriter.WriteLine("Player Two")
End If
Else
If SaveFileText.Count <> 0 Then
SaveFileWriter.WriteLine(SaveFileText(0))
Else
SaveFileWriter.WriteLine("Player One")
End If
SaveFileWriter.WriteLine(PlayerName & ControlChars.Tab & PlayerTiles & ControlChars.Tab & PlayerTilesPlayed & ControlChars.Tab & PlayerScore)
End If
SaveFileWriter.Close()
End Sub

Sub LoadGame(ByVal PlayerName As String, ByRef PlayerTiles As String, ByRef PlayerTilesPlayed As String, ByRef PlayerScore As Integer)
Dim SaveFileText As New List(Of String)
Dim PlayerData As String() = New String(3) {}
End While
If PlayerName = "Player One" Then
PlayerData = SaveFileText(0).Split(ControlChars.Tab)
Else
PlayerData = SaveFileText(1).Split(ControlChars.Tab)
End If
PlayerTiles = PlayerData(1)
PlayerTilesPlayed = PlayerData(2)
PlayerScore = PlayerData(3)
End Sub

Sub HaveTurn(ByVal PlayerName As String, ByRef PlayerTiles As String, ByRef PlayerTilesPlayed As String, ByRef PlayerScore As Integer, ByVal TileDictionary As Dictionary(Of Char, Integer), ByRef TileQueue As QueueOfTiles, ByRef AllowedWords As List(Of String), ByVal MaxHandSize As Integer, ByVal NoOfEndOfTurnTiles As Integer)
SaveGame(PlayerName, PlayerTiles, PlayerTilesPlayed, PlayerScore) 'saves game at the start of each turn (for the player whose turn it is currently)
Dim NewTileChoice As String
Dim Choice As String
Dim ValidChoice As Boolean
Dim ValidWord As Boolean
Console.WriteLine()
Console.WriteLine(PlayerName & " it is your turn.")
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
While Not ValidChoice
Choice = GetChoice()
If Choice = "1" Then
DisplayTileValues(TileDictionary, AllowedWords)
ElseIf Choice = "4" Then
TileQueue.Show()
ElseIf Choice = "5" Then
ReshuffleTilesInHand(PlayerTiles)
ElseIf Choice = "6" Then
ValidChoice = True
ElseIf Choice = "7" Then
DisplayTilesInHand(PlayerTiles)
ElseIf Choice = "0" Then
ValidChoice = True
FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
Else
ValidChoice = True
If Len(Choice) = 0 Then
ValidWord = False
Else
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
End If
If ValidWord Then
ValidWord = CheckWordIsValid(Choice, AllowedWords)
If ValidWord Then
Console.WriteLine()
Console.WriteLine("Valid word")
Console.WriteLine()
UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
End If
End If
If Not ValidWord Then
Console.WriteLine()
Console.WriteLine("Not a valid attempt, you lose your turn.")
Console.WriteLine()
End If
If NewTileChoice <> "4" Then
End If
Console.WriteLine()
Console.WriteLine("Your word was: " & Choice)
Console.WriteLine("Your new score is: " & PlayerScore)
Console.WriteLine("You have played " & PlayerTilesPlayed & " tiles so far in this game.")
End If
End While
End Sub

Sub PlayGame(ByRef AllowedWords As List(Of String), ByVal TileDictionary As Dictionary(Of Char, Integer), ByVal RandomStart As Boolean, ByVal StartHandSize As Integer, ByVal MaxHandSize As Integer, ByVal MaxTilesPlayed As Integer, ByVal NoOfEndOfTurnTiles As Integer, Optional ByVal LoadGameFromFile As Boolean = False)
Dim PlayerOneScore As Integer
Dim PlayerTwoScore As Integer
Dim PlayerOneTilesPlayed As Integer
Dim PlayerTwoTilesPlayed As Integer
Dim PlayerOneTiles As String
Dim PlayerTwoTiles As String
Dim TileQueue As New QueueOfTiles(20)
PlayerOneScore = 50
PlayerTwoScore = 50
PlayerOneTilesPlayed = 0
PlayerTwoTilesPlayed = 0
If RandomStart Then
PlayerOneTiles = GetStartingHand(TileQueue, StartHandSize)
PlayerTwoTiles = GetStartingHand(TileQueue, StartHandSize)
Else
PlayerOneTiles = "BTAHANDENONSARJ"
PlayerTwoTiles = "CELZXIOTNESMUAA"
End If
End If
While PlayerOneTilesPlayed <= MaxTilesPlayed And PlayerTwoTilesPlayed <= MaxTilesPlayed And Len(PlayerOneTiles) < MaxHandSize And Len(PlayerTwoTiles) < MaxHandSize
HaveTurn("Player One", PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles)
Console.WriteLine()
Console.Write("Press Enter to continue")
Console.WriteLine()
HaveTurn("Player Two", PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles)
End While
DisplayWinner(PlayerOneScore, PlayerTwoScore)
End Sub

Console.WriteLine()
Console.WriteLine("=========")
Console.WriteLine("=========")
Console.WriteLine()
Console.WriteLine("1. Play game with random start hand")
Console.WriteLine("2. Play game with training start hand")
Console.WriteLine("9. Quit")
Console.WriteLine()
End Sub

Sub Main()
Dim MaxHandSize As Integer
Dim MaxTilesPlayed As Integer
Dim NoOfEndOfTurnTiles As Integer
Dim StartHandSize As Integer
Dim Choice As String
Dim AllowedWords As New List(Of String)
Dim TileDictionary As New Dictionary(Of Char, Integer)()
Console.WriteLine("++++++++++++++++++++++++++++++++++++++")
Console.WriteLine("+ Welcome to the WORDS WITH AQA game +")
Console.WriteLine("++++++++++++++++++++++++++++++++++++++")
Console.WriteLine()
Console.WriteLine()
TileDictionary = CreateTileDictionary()
MaxHandSize = 20
MaxTilesPlayed = 50
NoOfEndOfTurnTiles = 3
StartHandSize = 15
Choice = ""
While Choice <> "9"
If Choice = "1" Then
PlayGame(AllowedWords, TileDictionary, True, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles)
ElseIf Choice = "2" Then
PlayGame(AllowedWords, TileDictionary, False, 15, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles)
ElseIf Choice = "3" Then 'if load game option chosen, parameter LoadGameFromFile set to true
PlayGame(AllowedWords, TileDictionary, True, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles, True)
End If
End While
End Sub
```

## Improve the searching algorithm

To check if the word is valid the program uses linear search O(n), improve it using a more efficient algorithm, e.g. binary search O(logn)

C#:

```private static bool CheckWordIsValid(string Word, List<string> AllowedWords)
{
/*
* Performs a Binary Search for Word in AllowedWords.
*/
bool ValidWord = false;
int mid;
int low = 0;
int high = AllowedWords.Count - 1;
while (low <= high)
{
mid = (low + high) / 2;
if (String.Compare(Word, AllowedWords[mid]) < 0)
{
/* Word < AllowedWords[mid] so only consider lower half of list*/
high = mid - 1;
}
else if (String.Compare(Word, AllowedWords[mid]) > 0)
{
/* Word > AllowedWords[mid] so only consider upper half of list*/
low = mid + 1;
}
else
{
/* The word was found */
ValidWord = true;
}
}
return ValidWord;
}
```

Delphi/Pascal:

```function CheckWordIsValid(Word:string;AllowedWords:TStringArray):boolean;
var
ValidWord:boolean;
middle,low,high:integer;
begin
ValidWord:=false;
low:=0;
high:=length(AllowedWords)-1;
while(low<=high) AND (NOT ValidWord) do
begin
middle:=(low+high) div 2;
if(AllowedWords[middle]=Word)then ValidWord:=true
else if(AllowedWords[middle]<Word)then low:=middle+1
else high:=middle-1;
end;
CheckWordIsValid:=ValidWord;
end;
```

Java:

```//Sheamol

boolean checkWordIsValid(String word, String[] allowedWords)
{
boolean validWord = false;
while (start<=end){
mid=(start+end)/2;
if (allowedWords[mid].equals(word)){
validWord=true;
return validWord;
}
else if(allowedWords[mid].compareTo(word)>0){
end=mid-1;
}
else if(allowedWords[mid].compareTo(word)<0){
start=mid+1;
}
}
return validWord;
}
```

Python:

```#By HAMMAD MEHMOOD, HERSCHEL GRAMMAR SCHOOL
def CheckWordIsValid(Word, AllowedWords):
"""
It uses an iterative binary search to find the word in the list instead of
linear search, Complexity of Linear Search is O(n) and Binary Serach is O(log n)
"""
ValidWord = False
First = 0
Last = len(AllowedWords)- 1
while First <= Last and not ValidWord:
Midpoint = (First + Last)//2
if AllowedWords[Midpoint] == Word:
ValidWord = True
Index = Midpoint
else:
if AllowedWords[Midpoint] < Word:
First = Midpoint + 1
else:
Last = Midpoint - 1
return ValidWord
#By HAMMAD MEHMOOD, HERSCHEL GRAMMAR SCHOOL

#Will this only work when the words are in alphabetical order? (If you add words to the document will this not work?) rb
#Yes, only works on alphabetically / sorted lists. pl

#By Anas Baig reppin Brentside high WEST LONDON
def CheckWordIsValid(Word, AllowedWords, first, last, ValidWord):
if last > first:
return ValidWord
mid = last + (first - last)
mid//=2
if Word == AllowedWords[mid]:
ValidWord = True
return ValidWord
else:
if Word < AllowedWords[mid]:
return CheckWordIsValid(Word, AllowedWords, mid-1, last, ValidWord)
else:
return CheckWordIsValid(Word, AllowedWords, first, mid+1, ValidWord)
#binary search implemented using recursion.
#call with ValidWord being False.

#By Jozef Tanzer, Truro School
def CheckWordIsValid(Word, AllowedWords):
if AllowedWords[int(len(AllowedWords)/2)] == Word:
return True
elif len(AllowedWords) == 1:
#the fact that it got here means that the current word is not valid
return False
elif AllowedWords[int(len(AllowedWords)/2)] < Word:
return CheckWordIsValid(Word, AllowedWords[int(len(AllowedWords)/2):])
return CheckWordIsValid(Word, AllowedWords[:int(len(AllowedWords)/2)])
#without changing parameters
#the min value of int(len(AllowedWords)/2) is 1 so Allowed words will always be at least one long.

#By Foz - Binary search algorithm
def CheckWordIsValid(Word, AllowedWords):
ValidWord = False
lower_bound = 0
upper_bound = len(AllowedWords)
while not ValidWord and lower_bound != upper_bound:
middle = (upper_bound + lower_bound) // 2
if Word == AllowedWords[middle]:
ValidWord = True
elif Word > AllowedWords[middle]:
lower_bound = middle
elif Word < AllowedWords[middle]:
upper_bound = middle
return ValidWord
```

VB.NET:

```Function CompareWords(ByVal word1 As String, ByVal word2 As String)
'returns word that comes before the other when ordered alphabetically
If word1.Length >= word2.Length Then
For x = 0 To word2.Length - 1
If word1.Chars(x) > word2.Chars(x) Then
Return word2
ElseIf word1.Chars(x) < word2.Chars(x) Then
Return word1
End If
Next
Return word2
Else
For x = 0 To word1.Length - 1
If word1.Chars(x) > word2.Chars(x) Then
Return word2
ElseIf word1.Chars(x) < word2.Chars(x) Then
Return word1
End If
Next
Return word1
End If
End Function

Function CheckWordIsValid(ByVal Word As String, ByRef AllowedWords As List(Of String)) As Boolean
Dim ValidWord As Boolean
Dim Midpoint As Integer = Math.Round((AllowedWords.Count - 1) / 2)
Dim UpperLimit As Integer = AllowedWords.Count - 1
Dim LowerLimit As Integer = 0
ValidWord = False
Do Until ValidWord
If Word <> AllowedWords(Midpoint) Then
If Midpoint = LowerLimit Or Midpoint = UpperLimit Then
Exit Do
End If
If CompareWords(Word, AllowedWords(Midpoint)) = Word Then
UpperLimit = Midpoint
Midpoint = Math.Round(LowerLimit + ((Midpoint - LowerLimit) / 2))
Else
LowerLimit = Midpoint
Midpoint = Math.Round(UpperLimit - ((UpperLimit - Midpoint) / 2))
End If
Else
ValidWord = True
End If
Loop
Return ValidWord
End Function
```

## Alert the User if aqawords.txt File is Missing

Tell the player(s) if the required text file is missing

C#:

```private static void LoadAllowedWords(ref List<string> AllowedWords)
{
try
{
{
}
}
catch (FileNotFoundException)
{
Environment.Exit(0);
// AllowedWords.Clear();
}
}
```

Delphi/Pascal:

The below unit can be applied to any file name and therefore is very versatile. For example, if the inappropriate words .txt file is needed then this can also be searched for.

```unit checkForFile;

{\$mode objfpc}{\$H+}

interface

uses
Classes, SysUtils;

function checkForFileFunc (filename : string) : boolean;
procedure checkForFileProc(filename : string);

implementation

function checkForFileFunc (filename : string) : boolean;
begin
checkForFileFunc := True;
if FileExists(filename) = False then
checkForFileFunc := False
end;

procedure checkForFileProc(filename : string);
begin
if checkForFileFunc(filename) = False then
begin
writeln(filename,' cannot be successfully located... closing program');
sleep(3000);
halt;
end
else
begin
writeln(filename,' aqawords.txt successfully located');
sleep(3000)
end;
end;
end.
```

The above unit's main procedure 'checkForFileStartup()', which runs the subroutines within the unit, can be referenced in the LoadAllowedWords() function so it now looks like this:

```function LoadAllowedWords() : TStringArray;
var
AllowedWords : TStringArray;
ListSize : integer;
TFIn : textfile;
Word : string;
begin
ListSize := 0;
checkForFileStartup('aqawords.txt');
AssignFile(TFIn, 'aqawords.txt');
try
reset(TFIn);
while not eof(TFIn) do
begin
inc(ListSize);
SetLength(AllowedWords, ListSize);
Word := UpperCase(Word);
AllowedWords[ListSize - 1] := Word;
end;
CloseFile(TFIn);
finally
end;
end;
```

Java:

```String[] loadAllowedWords()
{
String[] allowedWords = {};
try {
Path filePath = new File("aqawords.txt").toPath();
Charset charset = Charset.defaultCharset();
allowedWords = new String[stringList.size()];
int count = 0;
for(String word: stringList)
{
allowedWords[count] = word.trim().toUpperCase();
count++;
}
} catch (IOException e) {
}
return allowedWords;
}
```

Python:

```import sys

AllowedWords = []
try:
WordsFile = open("aqawords.txt", "r")
for Word in WordsFile:
AllowedWords.append(Word.strip().upper())
WordsFile.close()
except FileNotFoundError:
exit()
```

VB.NET:

```    Sub LoadAllowedWords(ByRef AllowedWords As List(Of String))
Try
End While
Catch
' AllowedWords.Clear()
Environment.Exit(0)
End Try
End Sub
```

## Allow players to add new words to the game

C#:

```private static void DisplayMenu()
{
Console.WriteLine();
Console.WriteLine("=========");
Console.WriteLine("=========");
Console.WriteLine();
Console.WriteLine("1. Play game with random start hand");
Console.WriteLine("2. Play game with training start hand");
Console.WriteLine("9. Quit");
Console.WriteLine();
}

static void Main(string[] args)
{
List<String> AllowedWords = new List<string>();
Dictionary<Char, int> TileDictionary = new Dictionary<char, int>();
int MaxHandSize = 20;
int MaxTilesPlayed = 50;
int NoOfEndOfTurnTiles = 3;
int StartHandSize = 15;
string Choice = "";
Console.WriteLine("++++++++++++++++++++++++++++++++++++++");
Console.WriteLine("+ Welcome to the WORDS WITH AQA game +");
Console.WriteLine("++++++++++++++++++++++++++++++++++++++");
Console.WriteLine("");
Console.WriteLine("");
CreateTileDictionary(ref TileDictionary);
while (Choice != "9")
{
if (Choice == "1")
{
PlayGame(AllowedWords, TileDictionary, true, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles);
}
else if (Choice == "2")
{
PlayGame(AllowedWords, TileDictionary, false, 15, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles);
}
else
{
}
else
Console.WriteLine("\n \n invalid Choice \n");
}
}

private static void AddWords(ref List<string> AllowedWords)
{
Dim word As String
Dim FileWriter As New System.IO.StreamWriter("\\coc-shares-1\studentdocuments\$\Intake 2011\11johnsons\Documents\Visual Studio 2008\Projects\Altererd prelim\aqawords.txt")
Console.WriteLine("Enter the word you would like to add to the text file.")

For Each i In AllowedWords             'This is the sub which will add a word to the fil ADDEDDDD CODEEEEEQ!?!?!?!?
FileWriter.WriteLine(i)            'WILL HAVE TO MAKE SURE THAT WORD IS ORGANISED IF SEARCH TO BE DONE

Next

FileWriter.Close()

End Sub
}
```

Delphi/Pascal:

```  procedure AddWord(var AllowedWords:TStringArray);
var
newWord:String;
TFIn : textfile;
begin
AssignFile(TFIn, 'aqawords.txt');
Append(TFIn);
SetLength(AllowedWords,Length(AllowedWords)+1);
AllowedWords[length(AllowedWords)-1]:=newWord;
writeln(TFIn,UpperCase(newWord));
CloseFile(TFIn);

end;
```

Java:

```//by margaret thatcher of the conservative and unionist party
Console.println();
Console.println("=========");
Console.println("=========");
Console.println();
Console.println("1. Play game with random start hand");
Console.println("2. Play game with training start hand");
Console.println("9. Quit");
Console.println();
}

//important
try  (BufferedWriter bw = new BufferedWriter(new FileWriter("aqawords.txt", true)))  { //true is added to modify the file
Console.writeLine("Enter the word you would like to add");
String word = Console.readLine(); //gets word
bw.newLine(); //new line
bw.write(word.toUpperCase()); //writes
bw.close(); //closes stream
} catch (Exception e) {
}
}

Main() {
...
while (!choice.equals("9")) {
if (choice.equals("1")) {
playGame(allowedWords, tileDictionary, true, startHandSize,
maxHandSize, maxTilesPlayed, noOfEndOfTurnTiles);
} else if (choice.equals("2")) {
playGame(allowedWords, tileDictionary, false, 15, maxHandSize,
maxTilesPlayed, noOfEndOfTurnTiles);
}
else if (choice.equals("3")) { //added here
}
}
}
```

Python:

```def LoadAllowedWords(): #Function to load the allowed words into the program from the AQA textfile
AllowedWords = []
NewWord = input("Would you like to add a new word: Y/N ")
if NewWord == "Y" or NewWord == "y":
try:
except FileNotFoundError:
print("Could not find aqawords.txt file")
exit()
try:
WordsFile = open("aqawords.txt", 'r')
for Word in WordsFile:
AllowedWords.append(Word.strip().upper())
WordsFile.close()
except FileNotFoundError:
print("Could not find aqawords.txt file")
exit()
for i in range(0, len(AllowedWords)-1):
for j in range(0, len(AllowedWords)-1 - i):
if AllowedWords[j] > AllowedWords[j+1]:
AllowedWords[j], AllowedWords[j+1] = AllowedWords[j+1], AllowedWords[j]
return AllowedWords #Return the list of Allowed Words.

def CheckWordIsValid(Word, AllowedWords): #Function to check if the player's word is valid
ValidWord = False #Initially set to False
Rear = len(AllowedWords) - 1
Front = 0
while Front <= Rear and not ValidWord:
mid = (Front + Rear) // 2
if Word == AllowedWords[mid]:
ValidWord = True
else:
if Word < AllowedWords[mid]:
Rear = mid - 1
else:
Front = mid + 1
print(ValidWord)
return ValidWord

#First the users is prompted if they wish to add a new word, if they do then the word they type in is appended to the aqawords.txt file. The contents of the file are then loaded in the AllowedWords list. However, since I have altered the sorting algorithm in the CheckWord is Valid Function to a binary search, the words in the AllowedWords list must be in alphabetical order. Therefore a sorting algorithm is necessary, I have used a bubble sort which is quite slow with a worst case time complexity of О(n^2).
```

VB.NET:

```Sub Main()
Dim MaxHandSize As Integer
Dim MaxTilesPlayed As Integer
Dim NoOfEndOfTurnTiles As Integer
Dim StartHandSize As Integer
Dim Choice As String
Dim AllowedWords As New List(Of String)
Dim TileDictionary As New Dictionary(Of Char, Integer)()
Console.WriteLine("++++++++++++++++++++++++++++++++++++++")
Console.WriteLine("+ Welcome to the WORDS WITH AQA game +")
Console.WriteLine("++++++++++++++++++++++++++++++++++++++")
Console.WriteLine()
Console.WriteLine()
TileDictionary = CreateTileDictionary() 'Assigns variable TitleDictionary with value returned from CreateTileDictionary function.
MaxHandSize = 20
MaxTilesPlayed = 50
NoOfEndOfTurnTiles = 3
StartHandSize = 15
Choice = ""
While Choice <> "9" 'Loops until choice is 9.
Choice = Console.ReadLine() 'Assigns Choice the users input.
If Choice = "1" Then
PlayGame(AllowedWords, TileDictionary, True, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles) 'Calls PlayGame function with random hand parameters.
ElseIf Choice = "2" Then
PlayGame(AllowedWords, TileDictionary, False, 15, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles) 'Calls PlayGame with Practice hand parameters.
ElseIf Choice = "3" Then 'New option for adding word.
AllowedWords.Clear() 'Clears current list of words. Means when you load the new word in their is no repitition of words.
LoadAllowedWords(AllowedWords) 'Calls LoadAllowedWords function to create list of words (Including new words).
End If
End While
End Sub
--------------------------------------------------------------------------------------------------------------------------------------
If File.Exists("F:\User\Documents\Programs\aqawords\aqawords\aqawords.txt") Then
Dim FileWriter As New System.IO.StreamWriter("F:\User\Documents\Programs\aqawords\aqawords\aqawords.txt", True)
Dim NewWord As String
Dim ValidWord As Boolean = True
Console.Write("Enter new word: ")
Dim CharArray() As Char = NewWord.ToCharArray
For Count As Integer = 0 To Len(NewWord) - 1
If Char.IsNumber(CharArray(Count)) Then
If ValidWord = True Then
Console.WriteLine("ERROR: Word contains numeric characters.")
ValidWord = False
End If
End If
Next
If ValidWord = True Then
FileWriter.WriteLine("") 'Creates new line in text file.
FileWriter.Write(NewWord.ToUpper) 'Writes word in upper case on new line.
FileWriter.Close()
Console.WriteLine("")
Console.WriteLine("")
End If
Else
Console.WriteLine("ERROR: aqawords.txt is missing.") 'Prints error message if text file is missing.
End If
End Sub
--------------------------------------------------------------------------------------------------------------------------------------
Console.WriteLine()
Console.WriteLine("=========")
Console.WriteLine("=========")
Console.WriteLine()
Console.WriteLine("1. Play game with random start hand")
Console.WriteLine("2. Play game with training start hand")
Console.WriteLine("9. Quit")
Console.WriteLine()
End Sub

Jake Campbell
```

## High score table feature

C#:

Create a function to read from a high score CSV file, containing the players score and then the players name. The file is read and the sorted using a bubble sort, the top 5 scores and names are then outputted.

```        private static void DisplayHighscore()
{
List<string[]> Values = new List<string[]>();	//Records the data inside the file

{
}
if (Values.Count == 0)	//If there was no data in the file
{
Console.WriteLine("There are currently no high scores.");
}
else
{
//Use a bubble sort to find the top 5 high scores.
string[] temp;
for (int write = 0; write < Values.Count(); write++)
{
for (int sort = 0; sort < Values.Count() - 1; sort++)
{
if (Convert.ToInt32(Values[sort][0]) > Convert.ToInt32(Values[sort + 1][0]))
{
temp = Values[sort + 1];
Values[sort + 1] = Values[sort];
Values[sort] = temp;
}
}
}
//Print out the top 5 in the list (original list was order smallest to highest - so last 5)
for (int i = Values.Count - 1; i >= Values.Count - 5; i--)
{
Console.WriteLine(Values[i][1] + " Scored: " + Values[i][0]);
}
}
}
```

Saves the high score into this new file.

```        private static void SaveHighScore(int Score, string name)	//The winners details are sent across
{
Console.WriteLine("Dose " + name + " want to save their high score? (Y/N)");	//Asked if they wish to save their results
if (input == "Y" || input == "y" || input == "yes")
{
File.AppendAllText("HighScore.csv", Environment.NewLine + Score + "," + Name );	//Save their result into the file.
Console.WriteLine("New High Score Saved");
Console.WriteLine("");
}
}
```

The winner of the game is asked if they would like to save their high score.

``` private static void DisplayWinner(int PlayerOneScore, int PlayerTwoScore)	//Prints out the end screen winner
{
Console.WriteLine();
Console.WriteLine("**** GAME OVER! ****");
Console.WriteLine();
Console.WriteLine("Player One your score is " + PlayerOneScore);	//Prints both players scores.
Console.WriteLine("Player Two your score is " + PlayerTwoScore);
if (PlayerOneScore > PlayerTwoScore)		//If Player one has more points than two
{
Console.WriteLine("Player One wins!");
SaveHighScore(PlayerOneScore, "PlayerOne");
}
else if (PlayerTwoScore > PlayerOneScore)   //If Player two has more points than one
{
Console.WriteLine("Player Two wins!");
SaveHighScore(PlayerTwoScore, "PlayerTwo"); //Trigger the save high score function
}
else	//Else they both have the exact same score.
{
Console.WriteLine("It is a draw!"); //No clear player has won so now high score is entered.
}
Console.WriteLine();
}
```

The "Main" function is updated to allow a choice 3 to display the current high scores.

```...
if (Choice == "1")	//If choice is one play game with random start hand (each players starting tiles are randomly generated)
{
PlayGame(AllowedWords, TileDictionary, true, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles);
}
else if (Choice == "2")	//If 2, start game with the players start hand being predefined/ same each time- so no randomisation.
{
PlayGame(AllowedWords, TileDictionary, false, 15, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles);
}
else if (Choice == "3") //If 3 (the new choice is entered)
{
DisplayHighscore(); //Display the high scores
}
...
```

The "DisplayMenu" method is also updated to show the user can press 3 to display the high score.

```         private static void DisplayMenu()	//Used to print out the starting main menu.
{
Console.WriteLine();
Console.WriteLine("=========");
Console.WriteLine("=========");
Console.WriteLine();
Console.WriteLine("1. Play game with random start hand");
Console.WriteLine("2. Play game with training start hand");
Console.WriteLine("3. Display high scores.");
Console.WriteLine("9. Quit");
Console.WriteLine();
}
```

Delphi/Pascal:

Java:

Python:

```def SaveHighscore(Name,Score):
ScoreFile = open("highscores.csv","a")
ScoreFile.write(Name+","+str(Score)+"\n")
ScoreFile.close()

try:
ScoreFile = open("highscores.csv","r")
except: return []
Highscores = []
if ',' in Line:
Highscores.append(Line.split(","))
return Highscores

def DisplayHighscores():
BestHighscores = sorted(Highscores,reverse=True,key=lambda x: x[1])
if len(BestHighscores) > 5:
BestHighscores = BestHighscores[:5]
print()
print("==========")
print("Highscores")
print("==========")
print()
for i in range(len(BestHighscores)):
print(str(i+1)+". "+BestHighscores[i][0]+" - "+BestHighscores[i][1])
if len(BestHighscores) == 0:
print("There are currently no highscores")
print()
input("Press any key to continue")

def DisplayWinner(PlayerOneScore, PlayerTwoScore):
print()
print("**** GAME OVER! ****")
print()
print("Player One your score is", PlayerOneScore)
print("Player Two your score is", PlayerTwoScore)
if PlayerOneScore > PlayerTwoScore:
print("Player One wins!")
elif PlayerTwoScore > PlayerOneScore:
print("Player Two wins!")
else:
print("It is a draw!")
if input("Player One would you like to save your score? (Y/N)").upper() == "Y":
if input("Player Two would you like to save your score? (Y/N)").upper() == "Y":
print()

print()
print("=========")
print("=========")
print()
print("1. Play game with random start hand")
print("2. Play game with training start hand")
print("3. Display highscores")
print("9. Quit")
print()

def Main():
print("++++++++++++++++++++++++++++++++++++++")
print("+ Welcome to the WORDS WITH AQA game +")
print("++++++++++++++++++++++++++++++++++++++")
print()
print()
TileDictionary = CreateTileDictionary()
MaxHandSize = 20
MaxTilesPlayed = 50
NoOfEndOfTurnTiles = 3
StartHandSize = 15
Choice = ""
while Choice != "9":
Choice = input("Enter your choice: ")
if Choice == "1":
PlayGame(AllowedWords, TileDictionary, True, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles)
elif Choice == "2":
PlayGame(AllowedWords, TileDictionary, False, 15, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles)
elif Choice == "3":
DisplayHighscores()
```

VB.NET:

```' the below code works however it will only allow 3 things adding both players scores, showing the high score table or doing both.
'there is also no cap on how many high scores can be in the high score table. There are many extensions possible from this,such as 'highlighting scores for the game just played or limiting the high score table to 15> items or only letting the highest scoring player enter 'their high score, if you want to edit it and re-upload np I just wasn't too bothered.

Sub DisplayWinner(ByVal PlayerOneScore As Integer, ByVal PlayerTwoScore As Integer)
Dim HighScoreSelect As String
Console.WriteLine()
Console.WriteLine("**** GAME OVER! ****")
Console.WriteLine()
Console.WriteLine("Player One your score is " & PlayerOneScore) 'displays players scores
Console.WriteLine("Player Two your score is " & PlayerTwoScore)
If PlayerOneScore > PlayerTwoScore Then
Console.WriteLine("Player One wins!") 'if player one has more points they win
ElseIf PlayerTwoScore > PlayerOneScore Then
Console.WriteLine("Player Two wins!") 'if player two has more they win
Else
Console.WriteLine("It is a draw!") 'if they both have the same it's a draw
End If
Console.WriteLine("1.Would you like to add these scores to the highscore table ")
Console.WriteLine("2.Display the highscore table ")
Console.WriteLine("3.Display the highscore table and add these scores ")
Console.WriteLine()

If HighScoreSelect = 1 Then
UpdateHighScoreTable(PlayerOneScore, PlayerTwoScore)
ElseIf HighScoreSelect = 2 Then
DisplayAndOrderHighScoreTable()
ElseIf HighScoreSelect = 3 Then
UpdateHighScoreTable(PlayerOneScore, PlayerTwoScore)
DisplayAndOrderHighScoreTable()
Else
End If

End Sub '

Sub UpdateHighScoreTable(ByVal PlayerOneScore As Integer, ByVal PlayerTwoScore As Integer)
Dim HighScorefilepath As String = "highscore.text" 'set file path
Dim HighScorewriter As New System.IO.StreamWriter(HighScorefilepath, True) 'create a reader

HighScorewriter.WriteLine(PlayerOneScore) 'write p1 score to the end of the file
HighScorewriter.WriteLine(PlayerTwoScore) ' write p2 score to the end of the file
HighScorewriter.Close()

End Sub

Sub DisplayAndOrderHighScoreTable()
Dim HighScorefilepath As String = "highscore.text" 'set file path
Dim Line As String = ""
Dim count As Integer = 1
Dim ScoreArray = New List(Of Integer)() ' define a list

Console.WriteLine()
Do
If Not Line Is Nothing And Line <> "" Then 'checks if there are more records if there are enters the if
End If
Loop Until Line Is Nothing

ScoreArray.Sort() 'sort the list

For Each Line In ScoreArray 'go through the whole list
Console.WriteLine(count & "." & Line) 'write the position and the score
count += 1 'increment the posistion
Next

End Sub

Jason Beard Havant collage
```

## Time limit when entering choice

Add a time limit for turns

C#:

```private static void HaveTurn(string PlayerName, ref string PlayerTiles, ref int PlayerTilesPlayed, ref int PlayerScore, Dictionary<char, int> TileDictionary, ref QueueOfTiles TileQueue, List<string> AllowedWords, int MaxHandSize, int NoOfEndOfTurnTiles)
{
Console.WriteLine();
Console.WriteLine(PlayerName + " it is your turn.");
DisplayTilesInHand(PlayerTiles);
string NewTileChoice = "2";
bool ValidChoice = false;
bool ValidWord = false;
string Choice = "";
int timeLimit = 1000 * 10; /* Ten seconds */
Stopwatch timer = new Stopwatch(); /* Stopwatch is a useful class for measuring elapsed time */
timer.Start(); /* Begin timing */
Console.WriteLine("You have {0} seconds!", timeLimit / 1000);
while (!ValidChoice)
{
if (timer.ElapsedMilliseconds > timeLimit) /* The time limit has elapsed */
{
Console.WriteLine("{0} has run out of time!",PlayerName); /* Notify the user that their turn is over */
break; /* Exit the turn loop */
}
Choice = GetChoice();
if (Choice == "1")
{
DisplayTileValues(TileDictionary, AllowedWords);
}
else if (Choice == "4")
{
TileQueue.Show();
}
else if (Choice == "7")
{
DisplayTilesInHand(PlayerTiles);
}
else if (Choice == "0")
{
ValidChoice = true;
FillHandWithTiles(ref TileQueue, ref PlayerTiles, MaxHandSize);
}
else
{
ValidChoice = true;
if (Choice.Length == 0)
{
ValidWord = false;
}
else
{
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles);
}
if (ValidWord)
{
ValidWord = CheckWordIsValid(Choice, AllowedWords);
if (ValidWord)
{
Console.WriteLine();
Console.WriteLine("Valid word");
Console.WriteLine();
UpdateAfterAllowedWord(Choice, ref PlayerTiles, ref PlayerScore, ref PlayerTilesPlayed, TileDictionary, AllowedWords);
NewTileChoice = GetNewTileChoice();
}
}
if (!ValidWord)
{
Console.WriteLine();
Console.WriteLine("Not a valid attempt, you lose your turn.");
Console.WriteLine();
}
if (NewTileChoice != "4")
{
AddEndOfTurnTiles(ref TileQueue, ref PlayerTiles, NewTileChoice, Choice);
}
Console.WriteLine();
Console.WriteLine("Your new score is:" + PlayerScore);
Console.WriteLine("You have played " + PlayerTilesPlayed + " tiles so far in this game.");
}
}
}
```

Delphi/Pascal:

```unit timeLimit;

{\$mode objfpc}{\$H+}

interface

uses
Classes, SysUtils, DateUtils;

procedure timeLimitProc (out Choice : string);

implementation
procedure timeLimitProc (out Choice : string);
var
T1, T2 : TDateTime;
const
timeSeconds = 30;
begin
T1 := Now;
write('> ');
Choice := UpperCase(Choice);
T2 := Now;
if (SecondsBetween(T1, T2)) > timeSeconds then
begin
write('You exceeded your time limit of ',timeSeconds,' seconds.');
Choice := '';
end;
end;
end.
```

This unit can be referenced in GetChoice() so it now looks like this:

```function GetChoice() : string;
var
Choice : string;
begin
writeln;
writeln('Either:');
writeln('     enter the word you would like to play OR');
writeln('     press 1 to display the letter values OR');
writeln('     press 4 to view the tile queue OR');
writeln('     press 7 to view your tiles again OR');
writeln('     press 0 to fill hand and stop the game.');
timeLimitProc(Choice);
writeln;
GetChoice := Choice;
end;
```

Java:

```String getChoice()
{
long time_begining =  System.currentTimeMillis();
Console.println();
Console.println("Either:");
Console.println("     enter the word you would like to play OR");
Console.println("     press 1 to display the letter values OR");
Console.println("     press 4 to view the tile queue OR");
Console.println("     press 7 to view your tiles again OR");
Console.println("     press 0 to fill hand and stop the game.");
Console.print("> ");
Console.println();
boolean time_left = true;
String choice = "";
choice = choice.toUpperCase();
if (System.currentTimeMillis() - time_begining > 10000) {
choice = "";
Console.print("you ran out of time");
time_left = false;
}
return choice;
}
///done by Nima
```

Python:

```import time

def GetChoice():
MaxChoiceTime = 20
StartChoiceTime = time.time()
print()
print("Either:")
print("     enter the word you would like to play OR")
print("     press 1 to display the letter values OR")
print("     press 4 to view the tile queue OR")
print("     press 7 to view your tiles again OR")
print("     press 0 to fill hand and stop the game.")
print()
print("You have {} seconds to make your choice or your turn will be invalidated".format(MaxChoiceTime))
print()
Choice = input(">")
EndChoiceTime = time.time()

if EndChoiceTime-StartChoiceTime > MaxChoiceTime:
print()
print("You took too long entering your choice and your turn has been invalidated!")
return "" #EMPTY CHOICE WILL RESULT IN AN INVALID TURN - NO NEED TO MODIFY OTHER AQA CODE
#Has no real purpose as time limit as it does not stop the turn once the time is up it allows the user to take as long as they want
#to make their choice and then stops the move once it has been entered
print()
Choice = Choice.upper()
return Choice
```

VB.NET:

```Sub HaveTurn(ByVal PlayerName As String, ByRef PlayerTiles As String, ByRef PlayerTilesPlayed As String, ByRef PlayerScore As Integer, ByVal TileDictionary As Dictionary(Of Char, Integer), ByRef TileQueue As QueueOfTiles, ByRef AllowedWords As List(Of String), ByVal MaxHandSize As Integer, ByVal NoOfEndOfTurnTiles As Integer)
SaveGame(PlayerName, PlayerTiles, PlayerTilesPlayed, PlayerScore) 'this is from a previous task [saving the game]
Dim NewTileChoice As String
Dim Choice As String
Dim ValidChoice As Boolean
Dim ValidWord As Boolean
Dim Timer As DateTime
Dim TimeTaken As Integer
Console.WriteLine()
Console.WriteLine(PlayerName & " it is your turn.")
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
While Not ValidChoice
Console.WriteLine("You have 20 seconds to choose a word.")
Timer = DateTime.Now.AddSeconds(20) 'sets the maximum time in which a player should be allowed to submit word
Choice = GetChoice()
If Choice = "1" Then
DisplayTileValues(TileDictionary, AllowedWords)
ElseIf Choice = "4" Then
TileQueue.Show()
ElseIf Choice = "5" Then
ReshuffleTilesInHand(PlayerTiles)
ElseIf Choice = "6" Then
ValidChoice = True
ElseIf Choice = "7" Then
DisplayTilesInHand(PlayerTiles)
ElseIf Choice = "0" Then
ValidChoice = True
FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
Else
ValidChoice = True
If Len(Choice) = 0 Then
ValidWord = False
Else
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
TimeTaken = DateTime.Compare(Timer, DateTime.Now) 'compares maximum time player allowed to take
'with the time they took --> returns the integer vlaue '-1' if the player took longer than the maximum time.
End If
If ValidWord And (TimeTaken <> -1) Then
ValidWord = CheckWordIsValid(Choice, AllowedWords)
If ValidWord Then
Console.WriteLine()
Console.WriteLine("Valid word")
Console.WriteLine()
UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
End If
ElseIf TimeTaken = -1 Then 'if user took too long they draw 3 penalty tiles
Console.WriteLine()
Console.WriteLine("You took too long to answer.")
Console.WriteLine()
'for an equivalent to this subroutine
End If
If Not ValidWord Then
Console.WriteLine()
Console.WriteLine("Not a valid attempt, you lose your turn.")
Console.WriteLine()
End If
If NewTileChoice <> "4" Then
End If
Console.WriteLine()
Console.WriteLine("Your word was: " & Choice)
Console.WriteLine("Your new score is: " & PlayerScore)
Console.WriteLine("You have played " & PlayerTilesPlayed & " tiles so far in this game.")
End If
End While
End Sub
```

## Inappropriate word filter

Filter out inappropriate words

C#:

```        private static string GetChoice()
{
string Choice;
string[] filteredWords = { "CHOICE1", "CHOICE2", "CHOICE3" };
Console.WriteLine();
Console.WriteLine("Either:");
Console.WriteLine("     enter the word you would like to play OR");
Console.WriteLine("     press 1 to display the letter values OR");
Console.WriteLine("     press 4 to view the tile queue OR");
Console.WriteLine("     press 7 to view your tiles again OR");
Console.WriteLine("     press 0 to fill hand and stop the game.");
Console.Write("> ");
Console.WriteLine();
Choice = Choice.ToUpper();

if(filteredWords.Contains(Choice))
{
Console.WriteLine();
return GetChoice();
}

return Choice;
}
```

Delphi/Pascal:

```//Step 1) Implement a constant to store the words that you want filtered out
const
inappropriateWords : array[0..1] of string = ('poo', 'toilet');

//Step 2) Implement a function that returns true when the word is appropriate, or false when it should be removed
function CheckIfWordIsAppropriate(word : string) : boolean;
var
i : integer;
wordIsAppropriate : boolean;
begin
wordIsAppropriate:=true;

for i:=0 to Length(inappropriateWords) do
begin
if(lowercase(inappropriateWords[i]) = lowercase(word)) then
begin
wordIsAppropriate:=false;
end;
end;
CheckIfWordIsAppropriate:=wordIsAppropriate;
end;

//Step 3) Modify the GetChoice() function to include your tasteful censorship
function GetChoice() : string;
var
Choice : string;
begin
writeln;
writeln('Either:');
writeln('     enter the word you would like to play OR');
writeln('     press 1 to display the letter values OR');
writeln('     press 4 to view the tile queue OR');
writeln('     press 7 to view your tiles again OR');
writeln('     press 0 to fill hand and stop the game.');
write('> ');
writeln;
Choice := UpperCase(Choice);

if(CheckIfWordIsAppropriate(Choice)) then
begin
//Word is fine. Return choice as normal
GetChoice := Choice;
end
else
begin
//Word is inappropriate, inform user, request new input (recursively)
writeLn('The word you entered is inappropriate, please try again');
GetChoice := GetChoice();
//Note: Persistently inappropiate users could probably create a stack overflow, but AQA probably won't notice
end;

end;
```

Java:

```//M Clarke - Thomas Adams College
//This requires a pre-existing banned.txt file with a list of inappropriate words
//please generate this before attempting to run the program
//all methds already exist except this one below. Adjust pre-existing methods as needed
//you will need to import a specific library for this. the aqaconsole scanner takes all inputted values and penalises you for an invalid input even if you delete the input of the text handle screen prior to entering

import java.util.Scanner;
//put this with the import methods at the start of the program prior to any methods
{
//similar set up/replicated the aqaWordsMethod but altered as needed
String[] disallowedWords = {};
try {
Path filePath1 = new File("banned.txt").toPath();
Charset charset1 = Charset.defaultCharset();
disallowedWords = new String[stringList1.size()];
int count = 0;
for(String word: stringList1)
{
disallowedWords[count] = word.trim().toUpperCase();
count++;
}
} catch (IOException e) {
//notifies user if the file is missing
System.exit(0);
}
return disallowedWords;
}

void haveTurn(String playerName, Tiles playerTiles,
TileCount playerTilesPlayed, Score playerScore, Map tileDictionary,
QueueOfTiles tileQueue, String[] allowedWords, int maxHandSize,
int noOfEndOfTurnTiles, String[] disallowedWords, String[] maxWordScore, String autoWin)
{
Scanner scan=new Scanner(System.in);
Console.println();
Console.println(playerName + ", it is your turn.");
displayTilesInHand(playerTiles.playerTiles);
String newTileChoice = "2";
boolean validChoice = false;
boolean validWord;
boolean validInput=false;
boolean validCheck=false;
String choice=null;
while (!validChoice)
{
while(validInput==false){
choice = getChoice();
while(validCheck==false){
System.out.println("");
System.out.println("Do you want "+choice+" to be your input? Y/N?");
//extended beyond where it initially is. validation on the user input.
try{
String res=scan.nextLine();
res=res.toUpperCase();
if(String.valueOf(res.charAt(0)).equals("Y")){
System.out.println("");
validInput=true;
validCheck=true;
}
else if(String.valueOf(res.charAt(0)).equals("N")){
validCheck=true;
}
else{
System.out.println("INVALID INPUT!");
}
}
catch(Exception e){
System.out.println("INVALID INPUT!");
}
}
}
boolean inapp=false;
for(int x=0;x<40;x++){
if((choice.toUpperCase()).equals(disallowedWords[x].toUpperCase())){
inapp=true;
Console.println("**INAPPROPRIATE WORD INPUTTED**");
}
}
if(inapp==false){
//this goes around the choice input block. if the word isnt an invalid choice, then the system checks against the typical responses

}
else{ // response if the input is a inappropriate word
Console.println();
playerScore.score -= 5;
//users penalised for attempting to put in a rude word
Console.println("Not a valid attempt, you lose your turn.");
Console.println();
Console.println();
Console.println("Your new score is:" + playerScore.score);
Console.println("You have played " + playerTilesPlayed.numberOfTiles + " tiles so far in this game.");
validChoice = true;
}
}
}

Main()
{
Console.println("++++++++++++++++++++++++++++++++++++++");
Console.println("+ Welcome to the WORDS WITH AQA game +");
Console.println("++++++++++++++++++++++++++++++++++++++");
Console.println();
Console.println();
//essential call for the system to recognise that new secondary dictionary is in place
Map tileDictionary = createTileDictionary();
int maxHandSize = 20;
int maxTilesPlayed = 50;
int noOfEndOfTurnTiles = 3;
int startHandSize = 15;
String choice = "";
while(!choice.equals("9"))
{
if (choice.equals("1"))
{
autoWin=allowedWords[rng.nextInt(allowedWords.length)];
playGame(allowedWords, tileDictionary, true, startHandSize,
maxHandSize, maxTilesPlayed, noOfEndOfTurnTiles, disallowedWords);
//passes secondary dictionary to the appropriate method so system can verify word input
}
else if (choice.equals("2"))
{
autoWin=allowedWords[rng.nextInt(allowedWords.length)];
playGame(allowedWords, tileDictionary, false, 15, maxHandSize,
maxTilesPlayed, noOfEndOfTurnTiles, disallowedWords);
}
}
}
```

Python:

```def GetChoice():
FilteredWords = ["WORD1","WORD2","WORD3","WORD4"]
print()
print("Either:")
print("     enter the word you would like to play OR")
print("     press 1 to display the letter values OR")
print("     press 4 to view the tile queue OR")
print("     press 7 to view your tiles again OR")
print("     press 0 to fill hand and stop the game.")
Choice = input(">")
print()
Choice = Choice.upper()

if Choice in FilteredWords:
print()
return GetChoice()

return Choice
```

VB.NET:

## Ask user to confirm their word choice

Ask the user to confirm their word choice or go back and change it if they made a typo etc.

C#:

```        private static void HaveTurn(string PlayerName, ref string PlayerTiles, ref int PlayerTilesPlayed, ref int PlayerScore, Dictionary<char, int> TileDictionary, ref QueueOfTiles TileQueue, List<string> AllowedWords, int MaxHandSize, int NoOfEndOfTurnTiles)
{
Console.WriteLine();
Console.WriteLine(PlayerName + " it is your turn.");
DisplayTilesInHand(PlayerTiles);
string NewTileChoice = "2";
bool ValidChoice = false;
bool ValidWord = false;
--------------------------------------------------------------------------------------
string Choice = "";
--------------------------------------------------------------------------------------
string strConfirm = "";
while (!ValidChoice)
{
Choice = GetChoice();
if (Choice == "1")
{
DisplayTileValues(TileDictionary, AllowedWords);
}
else if (Choice == "4")
{
TileQueue.Show();
}
else if (Choice == "7")
{
DisplayTilesInHand(PlayerTiles);
}
else if (Choice == "0")
{
ValidChoice = true;
FillHandWithTiles(ref TileQueue, ref PlayerTiles, MaxHandSize);
}
else
{
ValidChoice = true;
if (Choice.Length == 0)
{
ValidWord = false;
}
else
{
--------------------------------------------------------------------------------------
while(strConfirm != "YES")
{
Console.WriteLine("Are you sure you want to use " + Choice + "? (YES or NO)");
if(strConfirm == "NO")
{
Console.WriteLine("Re-Input Word");
}
}
--------------------------------------------------------------------------------------
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles);
}
if (ValidWord)
{
ValidWord = CheckWordIsValid(Choice, AllowedWords);
if (ValidWord)
{
Console.WriteLine();
Console.WriteLine("Valid word");
Console.WriteLine();
UpdateAfterAllowedWord(Choice, ref PlayerTiles, ref PlayerScore, ref PlayerTilesPlayed, TileDictionary, AllowedWords);
NewTileChoice = GetNewTileChoice();
}
}
if (!ValidWord)
{
Console.WriteLine();
Console.WriteLine("Not a valid attempt, you lose your turn.");
Console.WriteLine();
}
if (NewTileChoice != "4")
{
AddEndOfTurnTiles(ref TileQueue, ref PlayerTiles, NewTileChoice, Choice);
}
Console.WriteLine();
Console.WriteLine("Your new score is:" + PlayerScore);
Console.WriteLine("You have played " + PlayerTilesPlayed + " tiles so far in this game.");
}
}
}
```

Delphi/Pascal:

```procedure HaveTurn(PlayerName : string; var PlayerTiles : string; var PlayerTilesPlayed : integer;
var PlayerScore : integer; TileDictionary : TTileDictionary; var TileQueue : QueueOfTiles;
var AllowedWords : TStringArray; MaxHandSize : integer; NoOfEndOfTurnTiles : integer);
var
NewTileChoice : string;
ValidChoice : boolean;
ValidWord : boolean;
Choice : string;
ConfirmationInput : string; //Add a variable to store the user's reply to whether or not they confirm their choice
begin
writeln;
writeln(PlayerName, ' it is your turn.');
DisplayTilesInHand(PlayerTiles);
NewTileChoice := '2';
ValidChoice := False;
ConfirmationInput:=''; //Assign the variable to an empty string by default (they haven't confirmed yet)
while not ValidChoice do
begin
Choice := GetChoice();
if Choice = '1' then
DisplayTileValues(TileDictionary, AllowedWords)
else if Choice = '4' then
TileQueue.Show()
else if Choice = '7' then
DisplayTilesInHand(PlayerTiles)
else if Choice = '0' then
begin
ValidChoice := True;
FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize);
end
else
begin
ValidChoice := True;
if length(Choice) = 0 then
ValidWord := False
else
//Add the check to this if/else statement so that it runs whenever they had previously input a valid word
begin
repeat
writeLn('Are you sure you would like to use ''' + Choice + ''' as your choice? Enter ''y'' to confirm.');
if(ConfirmationInput <> 'y') then
begin
Choice := UpperCase(Choice);
end;
until ConfirmationInput = 'y';

ValidWord := CheckWordIsInTiles(Choice, PlayerTiles);
end;

if ValidWord then
begin
ValidWord := CheckWordIsValid(Choice, AllowedWords);
if ValidWord then
begin
writeln;
writeln('Valid word');
writeln;
UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords);
NewTileChoice := GetNewTileChoice();
end;
end;
if not ValidWord then
begin
writeln;
writeln('Not a valid attempt, you lose your turn.');
writeln;
end;
if not(NewTileChoice = '4') then
writeln;
writeln('Your new score is: ', PlayerScore);
writeln('You have played ', PlayerTilesPlayed, ' tiles so far in this game.');
end;
end;
end;
```

Java:

```void haveTurn(String playerName, Tiles playerTiles,
TileCount playerTilesPlayed, Score playerScore, Map tileDictionary,
QueueOfTiles tileQueue, String[] allowedWords, int maxHandSize,
int noOfEndOfTurnTiles)
{
Console.println();
Console.println(playerName + " it is your turn.");
displayTilesInHand(playerTiles.playerTiles);
String newTileChoice = "2";
boolean validChoice = false;
boolean validWord;
while (!validChoice)
{
String choice = getChoice();
if (choice.equals("1"))
{
displayTileValues(tileDictionary, allowedWords);
}
else if (choice.equals("4"))
{
tileQueue.show();
}
else if (choice.equals("7"))
{
displayTilesInHand(playerTiles.playerTiles);
}
else if (choice.equals("0"))
{
validChoice = true;
fillHandWithTiles(tileQueue, playerTiles, maxHandSize);
}
else
{
Console.println();
Console.println("Are you sure? Y or N");

if (ans.equals("Y")) {

validChoice = true;
if (choice.length() == 0)
{
validWord = false;
}
else
{
validWord = checkWordIsInTiles(choice, playerTiles.playerTiles);
}
if (validWord)
{
validWord = checkWordIsValid(choice, allowedWords);
if (validWord)
{
Console.println();
Console.println("Valid word");
Console.println();
updateAfterAllowedWord(choice, playerTiles, playerScore,
playerTilesPlayed, tileDictionary, allowedWords);
newTileChoice = getNewTileChoice();
}
}
if (!validWord)
{
Console.println();
Console.println("Not a valid attempt, you lose your turn.");
Console.println();
}
if (!newTileChoice.equals("4"))
{
}
Console.println();
Console.println("Your new score is:" + playerScore.score);
Console.println("You have played " + playerTilesPlayed.numberOfTiles + " tiles so far in this game.");
}
else if (ans.equals("N"))
{
displayTilesInHand(playerTiles.playerTiles);
getChoice();
}
else
{
Console.println();
Console.println("Invalid Choice!");
displayTilesInHand(playerTiles.playerTiles);
getChoice();
}
}
}
}
```

Python:

```def HaveTurn(PlayerName, PlayerTiles, PlayerTilesPlayed, PlayerScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles):
print()
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
while not ValidChoice:
Choice = GetChoice()
if Choice == "1":
DisplayTileValues(TileDictionary, AllowedWords)
elif Choice == "4":
TileQueue.Show()
elif Choice == "7":
DisplayTilesInHand(PlayerTiles)
elif Choice == "0":
ValidChoice = True
TileQueue, PlayerTiles = FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
###
elif Choice != input("Confirm the word entered:\n>").upper():
print("Chosen words do not match, please try again")
print()
###
else:
ValidChoice = True
if len(Choice) == 0:
ValidWord = False
else:
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
if ValidWord:
ValidWord = CheckWordIsValid(Choice, AllowedWords)
if ValidWord:
print()
print("Valid word")
print()
PlayerTiles, PlayerScore, PlayerTilesPlayed = UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
if not ValidWord:
print()
print("Not a valid attempt, you lose your turn.")
print()
if NewTileChoice != "4":
TileQueue, PlayerTiles = AddEndOfTurnTiles(TileQueue, PlayerTiles, NewTileChoice, Choice)
print()
print("You have played", PlayerTilesPlayed, "tiles so far in this game.")
return PlayerTiles, PlayerTilesPlayed, PlayerScore, TileQueue
```

Python 2:

```# Idris Khan Oak Acadmey
# put this in getChoice() just before choice.upper assignement
confirmed = False  # flag that controls the loop
while not confirmed:
confirmation = input('press enter to confirm your choice, '
'press (x) to enter again or type your new word\n>')
if confirmation.lower() == 'x':
confirmed = False
elif confirmation.lower() == '':
confirmed = True  # if user presses enter, take this as confirmed choice
elif confirmation.lower().isalpha():  # checks to see if input contains alphabetical characters
choice = confirmation  # take the user's new word as choice
confirmed = True

def HaveTurn(PlayerName, PlayerTiles, PlayerTilesPlayed, PlayerScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles):
print()
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
while not ValidChoice:
confirmed = False
while not confirmed:
Choice = GetChoice()
if Choice == "1":
DisplayTileValues(TileDictionary, AllowedWords)
elif Choice == "4":
TileQueue.Show()
elif Choice == "7":
DisplayTilesInHand(PlayerTiles)
elif Choice == "0":
ValidChoice = True
TileQueue, PlayerTiles = FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
else:
confirmation = input("Press enter to confirm your choice, press x to enter again\n>") # unfortunately this will take the users first input, (e.g misspelt "hand" as "hnad"), and not the new confirmed one
if confirmation.lower() == "x":
confirmed = False
else:
confirmed = True
ValidChoice = True
if len(Choice) == 0:
ValidWord = False
else:
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
if ValidWord:
ValidWord = CheckWordIsValid(Choice, AllowedWords)
if ValidWord:
print()
print("Valid word")
print()
PlayerTiles, PlayerScore, PlayerTilesPlayed = UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
if not ValidWord:
print()
print("Not a valid attempt, you lose your turn.")
print()
if NewTileChoice != "4":
TileQueue, PlayerTiles = AddEndOfTurnTiles(TileQueue, PlayerTiles, NewTileChoice, Choice)
print()
print("You have played", PlayerTilesPlayed, "tiles so far in this game.")
return PlayerTiles, PlayerTilesPlayed, PlayerScore, TileQueue
```

VB.NET:

```Sub HaveTurn(ByVal PlayerName As String, ByRef PlayerTiles As String, ByRef PlayerTilesPlayed As String, ByRef PlayerScore As Integer, ByVal TileDictionary As Dictionary(Of Char, Integer), ByRef TileQueue As QueueOfTiles, ByRef AllowedWords As List(Of String), ByVal MaxHandSize As Integer, ByVal NoOfEndOfTurnTiles As Integer)
Dim NewTileChoice As String
Dim Choice As String
Dim ValidChoice As Boolean
Dim ValidWord As Boolean
----------------------------------------------------------------------------------------------------------------------------
Dim Confirm As String
----------------------------------------------------------------------------------------------------------------------------
Console.WriteLine()
Console.WriteLine(PlayerName & " it is your turn.")
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
While Not ValidChoice
Choice = GetChoice()
If Choice = "1" Then
DisplayTileValues(TileDictionary, AllowedWords)
ElseIf Choice = "4" Then
TileQueue.Show()
ElseIf Choice = "7" Then
DisplayTilesInHand(PlayerTiles)
ElseIf Choice = "0" Then
ValidChoice = True
FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
ElseIf Choice = "9" Then
ValidChoice = True
SaveGame(PlayerTiles, PlayerScore, PlayerTiles, PlayerScore, TileQueue)
Else
ValidChoice = True
If Len(Choice) = 0 Then
ValidWord = False
Else
---------------------------------------------------------------------------------------------------------------------------------------
While Confirm <> "YES"
Console.WriteLine("Are you sure you want to use " & Choice & "? (Yes or No)")
If Confirm = "NO" Then
Console.WriteLine("Re-Input Word")
End If
End While
---------------------------------------------------------------------------------------------------------------------------------------
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
End If
If ValidWord Then
ValidWord = CheckWordIsValid(Choice, AllowedWords)
If ValidWord Then
Console.WriteLine()
Console.WriteLine("Valid word")
Console.WriteLine()
UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
End If
End If
If Not ValidWord Then
Console.WriteLine()
Console.WriteLine("Not a valid attempt, you lose your turn.")
Console.WriteLine()
End If
If NewTileChoice <> "4" Then
End If
Console.WriteLine()
Console.WriteLine("Your word was: " & Choice)
Console.WriteLine("Your new score is: " & PlayerScore)
Console.WriteLine("You have played " & PlayerTilesPlayed & " tiles so far in this game.")
End If
End While
End Sub
'Theres probably a better way to do this, but this is one solution
Michael Slater - Jumeirah College
```

## Prevent duplication of words being entered

Description of question

C#:

The have turn method was edited, such that it adds a valid word to a used word list and then checks each time the user inputs a word if it is inside of this list, if not it has not been used before and is a valid word.

``` private static void HaveTurn(string PlayerName, ref string PlayerTiles, ref int PlayerTilesPlayed, ref int PlayerScore, Dictionary<char, int> TileDictionary, ref QueueOfTiles TileQueue, List<string> AllowedWords, int MaxHandSize, int NoOfEndOfTurnTiles, ref List<string> UsedWords)
{

...
else
{
ValidChoice = true;
if (Choice.Length == 0)
{
ValidWord = false;
}
else
{
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles);
}
if (ValidWord)
{
ValidWord = CheckWordIsValid(Choice, AllowedWords);
if (ValidWord)
{
ValidWord = !UsedWords.Contains(Choice); //If the word is not in the used words file, make valid choice true.
if (ValidWord)
{
UsedWords.Add(Choice); //If the word was valid, add it to the used word list
Console.WriteLine();
Console.WriteLine("Valid word");
Console.WriteLine();
UpdateAfterAllowedWord(Choice, ref PlayerTiles, ref PlayerScore, ref PlayerTilesPlayed, TileDictionary, AllowedWords);
NewTileChoice = GetNewTileChoice();
}
else
{
Console.WriteLine("This word has already been played by another player.");
}
}
}
...
```

The PlayGame method is also amended to contain the UsedWords string list, this stores all of the valid words which have been played and is passed to the HaveTurn function by ref.

``` private static void PlayGame(List<string> AllowedWords, Dictionary<char, int> TileDictionary, bool RandomStart, int StartHandSize, int MaxHandSize, int MaxTilesPlayed, int NoOfEndOfTurnTiles)
{
List<string> UsedWords = new List<string>(); //Used to store the used valid words
...
while (PlayerOneTilesPlayed <= MaxTilesPlayed && PlayerTwoTilesPlayed <= MaxTilesPlayed && PlayerOneTiles.Length < MaxHandSize && PlayerTwoTiles.Length < MaxHandSize)
{
HaveTurn("Player One", ref PlayerOneTiles, ref PlayerOneTilesPlayed, ref PlayerOneScore, TileDictionary, ref TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, ref UsedWords);
Console.WriteLine();
Console.WriteLine("Press Enter to continue");
Console.WriteLine();
HaveTurn("Player Two", ref PlayerTwoTiles, ref PlayerTwoTilesPlayed, ref PlayerTwoScore, TileDictionary, ref TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, ref UsedWords);
}
```

Delphi/Pascal:

Java:

```//By Tekashi 6ix9ine of Scum Gang Sixth Form
//this is literally like the c# example but the List is an ArrayList and modified to suit the java syntax rules
void haveTurn(String playerName, Tiles playerTiles,
TileCount playerTilesPlayed, Score playerScore, Map tileDictionary,
QueueOfTiles tileQueue, String[] allowedWords, int maxHandSize,
int noOfEndOfTurnTiles, ArrayList usedWords)
{
...
if (validWord)
{
validWord = checkWordIsValid(choice, allowedWords);
if (validWord) {
validWord = !usedWords.contains(choice); //this just makes the valid choice true
if (validWord)
{
Console.println();
Console.println("Valid word");
Console.println();
updateAfterAllowedWord(choice, playerTiles, playerScore,
playerTilesPlayed, tileDictionary, allowedWords);
newTileChoice = getNewTileChoice();
}
else {
Console.writeLine("This word has already been played by another player."); //hey presto!!!
}
}
}
...

//later on in the program

void playGame(String[] allowedWords, Map tileDictionary, boolean randomStart,
int startHandSize, int maxHandSize, int maxTilesPlayed,
int noOfEndOfTurnTiles)
{
ArrayList<String> usedWords = new ArrayList<>(); //declare it here
...
while (playerOneTilesPlayed.numberOfTiles <= maxTilesPlayed &&
playerTwoTilesPlayed.numberOfTiles <= maxTilesPlayed &&
playerOneTiles.playerTiles.length() < maxHandSize &&
playerTwoTiles.playerTiles.length() < maxHandSize)
{
haveTurn("Player One", playerOneTiles, playerOneTilesPlayed, playerOneScore,
tileDictionary, tileQueue, allowedWords, maxHandSize,
Console.println();
Console.println("Press Enter to continue");
Console.println();
haveTurn("Player Two", playerTwoTiles, playerTwoTilesPlayed, playerTwoScore,
tileDictionary, tileQueue, allowedWords, maxHandSize,
noOfEndOfTurnTiles, usedWords); //ditto
}
...
```

Python:

```#BY HAMMAD MEHMOOD, HERSCHEL GRAMMAR SCHOOL
def PlayGame(AllowedWords, TileDictionary, RandomStart, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles):
PlayerOneScore = 50
PlayerTwoScore = 50
PlayerOneTilesPlayed = 0
PlayerTwoTilesPlayed = 0
TileQueue = QueueOfTiles(20)
WordsUsed = [] #New list to store the valid words used
#Pass the list in HaveTurn as a parameter
if RandomStart:
PlayerOneTiles = GetStartingHand(TileQueue, StartHandSize)
PlayerTwoTiles = GetStartingHand(TileQueue, StartHandSize)
else:
PlayerOneTiles = "BTAHANDENONSARJ"
PlayerTwoTiles = "CELZXIOTNESMUAA"
while PlayerOneTilesPlayed <= MaxTilesPlayed and PlayerTwoTilesPlayed <= MaxTilesPlayed and len(PlayerOneTiles) < MaxHandSize and len(PlayerTwoTiles) < MaxHandSize:
PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileQueue = HaveTurn("Player One", PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, WordsUsed)
print()
input("Press Enter to continue")
print()
PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileQueue = HaveTurn("Player Two", PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, WordsUsed)
DisplayWinner(PlayerOneScore, PlayerTwoScore)
def HaveTurn(PlayerName, PlayerTiles, PlayerTilesPlayed, PlayerScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, WordsUsed):
# The list WordsUsed is an argument in this function
print()
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
while not ValidChoice:
Choice = GetChoice()
if Choice == "1":
DisplayTileValues(TileDictionary, AllowedWords)
elif Choice == "4":
TileQueue.Show()
elif Choice == "7":
DisplayTilesInHand(PlayerTiles)
elif Choice == "0":
ValidChoice = True
TileQueue, PlayerTiles = FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
else:
ValidChoice = True
if len(Choice) == 0:
ValidWord = False
else:
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
if ValidWord:
ValidWord = CheckWordIsValid(Choice, AllowedWords, WordsUsed)#Pass the list a parameter
if ValidWord:
WordsUsed.append(Choice) #Add the word used in the list
print()
print("Valid word")
print()
PlayerTiles, PlayerScore, PlayerTilesPlayed = UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
if not ValidWord:
print()
print("Not a valid attempt, you lose your turn.")
print()
if NewTileChoice != "4":
TileQueue, PlayerTiles = AddEndOfTurnTiles(TileQueue, PlayerTiles, NewTileChoice, Choice)
print()
print("You have played", PlayerTilesPlayed, "tiles so far in this game.")
return PlayerTiles, PlayerTilesPlayed, PlayerScore, TileQueue
def CheckWordIsValid(Word, AllowedWords, WordsUsed):
ValidWord = False
Count = 0
while Count < len(AllowedWords) and not ValidWord:
if AllowedWords[Count] == Word:
ValidWord = True
Count += 1
if Word in WordsUsed: #If the word is in the list (it has already been used)
print("Sorry the word",Word,"has already been used once") #Tell the user
ValidWord = False #Word is not valid
return ValidWord
#BY HAMMAD MEHMOOD, HERSCHEL GRAMMAR SCHOOL
```

VB.NET:

```'This involves one new function being created and called just after the CheckWordIsValid call. pretty gnar
'SLAAAAAAAAAAAYEEEEEEER !!!
'By Luca

Public WordCount As Integer 'this count, starting from 0, counts how many words have been played that are unique
Public UsedWordsArray(WordCount) As String 'this array holds the words that have already been entered
'I declared these as public variables as the values they hold need to be kept for both players turns
'and declaring them in the functions/subroutines means the values they hold get cleared when that instruction set is called
Sub Main()
Dim MaxHandSize As Integer
Dim MaxTilesPlayed As Integer
Dim NoOfEndOfTurnTiles As Integer
Dim StartHandSize As Integer
Dim Choice As String
Dim AllowedWords As New List(Of String)
Dim TileDictionary As New Dictionary(Of Char, Integer)()
Console.WriteLine("++++++++++++++++++++++++++++++++++++++")
Console.WriteLine("+ Welcome to the WORDS WITH AQA game +")
Console.WriteLine("++++++++++++++++++++++++++++++++++++++")
Console.WriteLine()
Console.WriteLine()
TileDictionary = CreateTileDictionary()
MaxHandSize = 20
MaxTilesPlayed = 50
NoOfEndOfTurnTiles = 3
StartHandSize = 15
Choice = ""
While Choice <> "9"
If Choice = "1" Then
PlayGame(AllowedWords, TileDictionary, True, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles)
ElseIf Choice = "2" Then
PlayGame(AllowedWords, TileDictionary, False, 15, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles)
End If
End While
End Sub

Function CheckWordIsUnused(ByVal Word As String)
Dim ValidWord As Boolean
Dim UsedWord As Boolean = False
For i = 0 To WordCount 'the array containing used words is looped through and the player's input word is compared to each
If Word = UsedWordsArray(i) Then
UsedWord = True
ValidWord = False 'if the word has already been used, the input is an invalid word
Console.WriteLine("That word has already been used.") 'the player is informed that they are bad at a word game
Exit For
End If
Next

If UsedWord = False Then 'if the word has not been used yet, it is added to the array
WordCount = WordCount + 1 'the size of the array is incremented by one to make space for the next possible word
ReDim Preserve UsedWordsArray(WordCount) 'the array is redefined with this new length and preserved to keep the used words in it
UsedWordsArray(WordCount - 1) = Word 'the player's word is put into the next available space
ValidWord = True
End If

Return ValidWord
End Function

Sub HaveTurn(ByVal PlayerName As String, ByRef PlayerTiles As String, ByRef PlayerTilesPlayed As String, ByRef PlayerScore As Integer, ByVal TileDictionary
As Dictionary(Of Char, Integer), ByRef TileQueue As QueueOfTiles, ByRef AllowedWords As List(Of String), ByVal MaxHandSize As Integer, ByVal
NoOfEndOfTurnTiles As Integer)
Dim NewTileChoice As String
Dim Choice As String
Dim ValidChoice As Boolean
Dim ValidWord As Boolean
Console.WriteLine()
Console.WriteLine(PlayerName & " it is your turn.")
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
While Not ValidChoice
Choice = GetChoice()
If Choice = "1" Then
DisplayTileValues(TileDictionary, AllowedWords)
ElseIf Choice = "4" Then
TileQueue.Show()
ElseIf Choice = "7" Then
DisplayTilesInHand(PlayerTiles)
ElseIf Choice = "0" Then
ValidChoice = True
FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
Else
ValidChoice = True
If Len(Choice) = 0 Then
ValidWord = False
Else
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
End If
If ValidWord Then
ValidWord = CheckWordIsValid(Choice, AllowedWords)
If ValidWord Then
ValidWord = CheckWordIsUnused(Choice) 'the function is called that checks if the input word has already been used
If ValidWord Then
Console.WriteLine()
Console.WriteLine("Valid word")
Console.WriteLine()
UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
End If
End If
End If
If Not ValidWord Then
Console.WriteLine()
Console.WriteLine("Not a valid attempt, you lose your turn.")
Console.WriteLine()
End If
If NewTileChoice <> "4" Then
End If
Console.WriteLine()
Console.WriteLine("Your word was: " & Choice)
Console.WriteLine("Your new score is: " & PlayerScore)
Console.WriteLine("You have played " & PlayerTilesPlayed & " tiles so far in this game.")
End If
End While
End Sub
```

## Bonus points if two or more high scoring tiles are played ie JAZZ (J=5, A=1 ,Z=5, Z=5)

Description of question

C#:

```private static int GetScoreForWord(string Word, Dictionary<char, int> TileDictionary)
{
int Score = 0;
int HighScoring = 0;	//Used to record the number of high-scoring points
for (int Count = 0; Count < Word.Length; Count++)
{
Score = Score + TileDictionary[Word[Count]];
if(TileDictionary[Word[Count]] >= 5)	//If 5 points or more
{
}
}
if (Word.Length > 7)
{
Score = Score + 20;
}
else if (Word.Length > 5)
{
Score = Score + 5;
}

if (HighScoring >= 2)	//If more than two letters were high-scoring
{
Score += HighScoring * 2; //Score = Score + High-score * 2
}

return Score;
}
```

Delphi/Pascal:

```function GetScoreForWord(Word : string; TileDictionary : TTileDictionary) : integer;
var
Score : integer;
Count,value,count1: integer;
hs:string;
begin
Score := 0;
value:= 0 ;
for Count := 1 to length(Word) do
Score := Score + TileDictionary.FindTileScore(Word[Count]);
if length(Word) > 7 then
Score := Score + 20
else if length(Word) > 5 then
Score := Score + 5;
begin
hs:= 'JZ';
for count := 1 to length(hs) do
begin
for count1:= 1 to length(word) do
if word[count1] = hs[count] then
value := value + 1;
end;
end;
if value >= 2 then
begin
score := score + 1;
end;

GetScoreForWord := Score;
end;
// developed by Samuel Ajayi Graveney school.
```

Java:

```//c# translation by donald trump, president of the united states of america
int getScoreForWord(String word, Map tileDictionary) {
int score = 0;
int highScoring = 0; //for counting
for (int count = 0; count < word.length(); count++) {
score += (int) tileDictionary.get(word.charAt(count));
if ((int) tileDictionary.get(word.charAt(count)) >= 5) { //over a score of 5
highScoring++; //increment
}
}
if (word.length() > 7) {
score += 20;
} else if (word.length() > 5) {
score += 5;
}

if (highScoring >= 2) { //more than two
score += highScoring * 2;
Console.println("High Score Bonus!");
}
return score;
}
```

Python:

```def GetScoreForWord(Word, TileDictionary):
Score = 0
HighScoring = 0
for Count in range (len(Word)):
Score += TileDictionary[Word[Count]]
if TileDictionary[Word[Count]] >= 5:
HighScoring += 1
if len(Word) > 7:
Score += 20
elif len(Word) > 5:
Score += 5
if HighScoring >= 2:
Score += HighScoring * 2 # 2 extra points per high scoring letter if two or more highscoring tiles played
return Score
```

VB.NET:

```'Matthew Woods, Havant College
Function GetScoreForWord(ByVal Word As String, ByVal TileDictionary As Dictionary(Of Char, Integer)) As Integer
Dim Score, HighScoreingLetter As Integer 'The new variable for storing HighScore has been added.
Score = 0
HighScoreingLetter = 0 'The HighScore variable is initialised as 0
For Count = 0 To Len(Word) - 1
Score += TileDictionary(Word(Count))
If TileDictionary(Word(Count)) >= 5 Then 'A High score is a letter with more than 5 Points, the HighScore variable is incrimented when this is played.
HighScoreingLetter += 1
End If
Next
If Len(Word) > 7 Then
Score += 20
ElseIf Len(Word) > 5 Then
Score += 5
End If
If HighScoreingLetter >= 2 Then 'Finally, if there is more than one High Scoring letter played, the number of High Scoreing Letters is doubled and added to the score.
Score += HighScoreingLetter * 2
End If
Return Score
End Function
'Matthew Woods, Havant College
```

## Bonus points at end of game for longest and highest scored words

Description of question

C#:

Delphi/Pascal:

Java:

Python:

```#By Hammad Mehmood Herschel Grammar School, All the changes have comments on them

def PlayGame(AllowedWords, TileDictionary, RandomStart, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles):
PlayerOneScore = 50
LongestWords = ["",""] #List that will store the longest word as well as the player who played it
HighestScoreWord = ["0","",""] #List that will store the highest score, the word and the player who played it
PlayerTwoScore = 50
PlayerOneTilesPlayed = 0
PlayerTwoTilesPlayed = 0
TileQueue = QueueOfTiles(20)
if RandomStart:
PlayerOneTiles = GetStartingHand(TileQueue, StartHandSize)
PlayerTwoTiles = GetStartingHand(TileQueue, StartHandSize)
else:
PlayerOneTiles = "BTAHANDENONSARJ"
PlayerTwoTiles = "CELZXIOTNESMUAA"
while PlayerOneTilesPlayed <= MaxTilesPlayed and PlayerTwoTilesPlayed <= MaxTilesPlayed and len(PlayerOneTiles) < MaxHandSize and len(PlayerTwoTiles) < MaxHandSize:
PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileQueue = HaveTurn("Player One", PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, LongestWords, HighestScoreWord)
#The two lists and the player name are passed as parameters in HaveTurn
print()
input("Press Enter to continue")
print()
PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileQueue = HaveTurn("Player Two", PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, LongestWords, HighestScoreWord)
#The two lists and the player name are passed as parameters in HaveTurn
print("Longest Word:", LongestWords[0])#print longest word
print("Played by:", LongestWords[1])#print player of the longest word
print("Highest score word:", HighestScoreWord[1], "with a score of", HighestScoreWord[0]) #print highest score word and the score
print("Played by:", HighestScoreWord[2])#print the player of the highest score word
BonusScore = 2 #the extra bonus points
if  LongestWords[1] == "Player One": #If the longest word was playes by Player 1
PlayerOneScore += BonusScore #Add to player one score
else: #If it was player 2
PlayerTwoScore += BonusScore #Add to player two score
if HighestScoreWord[2] == "Player One":#If the highest score word was playes by Player 1
PlayerOneScore += BonusScore#Add to player one score
else:#If it was player 2
PlayerTwoScore += BonusScore#Add to player two score
DisplayWinner(PlayerOneScore, PlayerTwoScore)

#This is in HaveTurn
#Pass the lists to UpdateAfterAllowedWord
PlayerTiles, PlayerScore, PlayerTilesPlayed = UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords, LongestWords, HighestScoreWord, PlayerName)

def UpdateAfterAllowedWord(Word, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords, LongestWords, HighestScoreWord, PlayerName):
PlayerTilesPlayed += len(Word)
for Letter in Word:
PlayerTiles = PlayerTiles.replace(Letter, "", 1)
Score = GetScoreForWord(Word, TileDictionary)
PlayerScore += Score
if len(Word) > len(LongestWords[0]): #Check is the lenght of the word is greater than the lenght of previously longest word
LongestWords[0] = Word #If so then change the current longest score
LongestWords[1] = PlayerName #Add which player playes it
if Score > int(HighestScoreWord[0]): #Check is the score of the previos highest score word is greater than the score of the word played
HighestScoreWord[0] = Score #If so, then change the highest score
HighestScoreWord[1] = Word #Add the word
HighestScoreWord[2] = PlayerName #Add the player
#print statements to check
print("LongestWords", LongestWords)
print("HighestScoreWord", HighestScoreWord)
#We are not appending to the list, we just change the value of a specific position
return PlayerTiles, PlayerScore, PlayerTilesPlayed

#By Hammad Mehmood, Herschel Grammar School
```

VB.NET:

```Sub PlayGame(ByRef AllowedWords As List(Of String), ByVal TileDictionary As Dictionary(Of Char, Integer), ByVal RandomStart As Boolean, ByVal StartHandSize As Integer, ByVal MaxHandSize As Integer, ByVal MaxTilesPlayed As Integer, ByVal NoOfEndOfTurnTiles As Integer)
Dim PlayerOneScore As Integer
Dim PlayerTwoScore As Integer
Dim PlayerOneTilesPlayed As Integer
Dim PlayerTwoTilesPlayed As Integer
Dim PlayerOneTiles As String
Dim PlayerTwoTiles As String
Dim TileQueue As New QueueOfTiles(20)
Dim LongestWord As String() = New String(1) {} 'string array used to keep track of longest word + player who entered it
PlayerOneScore = 50
PlayerTwoScore = 50
PlayerOneTilesPlayed = 0
PlayerTwoTilesPlayed = 0
If RandomStart Then
PlayerOneTiles = GetStartingHand(TileQueue, StartHandSize)
PlayerTwoTiles = GetStartingHand(TileQueue, StartHandSize)
Else
PlayerOneTiles = "BTAHANDENONSARJ"
PlayerTwoTiles = "CELZXIOTNESMUAA"
End If
While PlayerOneTilesPlayed <= MaxTilesPlayed And PlayerTwoTilesPlayed <= MaxTilesPlayed And Len(PlayerOneTiles) < MaxHandSize And Len(PlayerTwoTiles) < MaxHandSize
'HaveTurn is now called with LongestWord as an extra parameter
HaveTurn("Player One", PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, LongestWord)
Console.WriteLine()
Console.Write("Press Enter to continue")
Console.WriteLine()
HaveTurn("Player Two", PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, LongestWord)
End While
If LongestWord(1) = "Player One" Then 'player who entered the longest word in the game gets an extra 10 points
Console.WriteLine("Player One: + 10 points for longest word")
PlayerOneScore += 10
Else
Console.WriteLine("Player Two: + 10 points for longest word")
PlayerTwoScore += 10
End If
DisplayWinner(PlayerOneScore, PlayerTwoScore)
End Sub

Sub HaveTurn(ByVal PlayerName As String, ByRef PlayerTiles As String, ByRef PlayerTilesPlayed As String, ByRef PlayerScore As Integer, ByVal TileDictionary As Dictionary(Of Char, Integer), ByRef TileQueue As QueueOfTiles, ByRef AllowedWords As List(Of String), ByVal MaxHandSize As Integer, ByVal NoOfEndOfTurnTiles As Integer, ByRef LongestWord As String())
Dim NewTileChoice As String
Dim Choice As String
Dim ValidChoice As Boolean
Dim ValidWord As Boolean
Console.WriteLine()
Console.WriteLine(PlayerName & " it is your turn.")
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
While Not ValidChoice
Choice = GetChoice()
If Choice = "1" Then
DisplayTileValues(TileDictionary, AllowedWords)
ElseIf Choice = "4" Then
TileQueue.Show()
ElseIf Choice = "7" Then
DisplayTilesInHand(PlayerTiles)
ElseIf Choice = "0" Then
ValidChoice = True
FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
Else
ValidChoice = True
If Len(Choice) = 0 Then
ValidWord = False
Else
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
End If
If ValidWord Then
ValidWord = CheckWordIsValid(Choice, AllowedWords)
If ValidWord Then
Console.WriteLine()
Console.WriteLine("Valid word")
Console.WriteLine()
UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
If Len(Choice) > Len(LongestWord(0)) Then 'if submitted word is longer than the current longest word then
'the longest word + player who entered it is changed in the LongestWord array (as LongestWord is taken in HaveTurn subroutine
'as ByRef, this changes the values in the array in the location in which it was initialised - in this case, PlayGame())
Console.WriteLine()
Console.WriteLine("New longest word: " & Choice)
Console.WriteLine()
LongestWord(0) = Choice
LongestWord(1) = PlayerName
End If
End If
End If
If Not ValidWord Then
Console.WriteLine()
Console.WriteLine("Not a valid attempt, you lose your turn.")
Console.WriteLine()
End If
If NewTileChoice <> "4" Then
End If
Console.WriteLine()
Console.WriteLine("Your word was: " & Choice)
Console.WriteLine("Your new score is: " & PlayerScore)
Console.WriteLine("You have played " & PlayerTilesPlayed & " tiles so far in this game.")
End If
End While
End Sub
```

## Deduct points from score if invalid word entered

Remove points from the players score if they do not enter a valid word

C#:

```private static void HaveTurn(string PlayerName, ref string PlayerTiles, ref int PlayerTilesPlayed, ref int PlayerScore, Dictionary<char, int> TileDictionary, ref QueueOfTiles TileQueue, List<string> AllowedWords, int MaxHandSize, int NoOfEndOfTurnTiles)
{
...
//All the above code did not changed, so not published; only the edited code is shown below.
if (!ValidWord)
{
Console.WriteLine();
Console.WriteLine("Not a valid attempt, you lose your turn.");
Console.WriteLine("You also lose 5 points for entering an invalid word");
Console.WriteLine();
PlayerScore -= 5;
}
```

Delphi/Pascal:

```procedure HaveTurn(PlayerName : string; var PlayerTiles : string; var PlayerTilesPlayed : integer;
var PlayerScore : integer; TileDictionary : TTileDictionary; var TileQueue : QueueOfTiles;
var AllowedWords : TStringArray; MaxHandSize : integer; NoOfEndOfTurnTiles : integer);
...
//All the above code did not changed, so not published; only the edited code is shown below.
if not ValidWord then
begin
WriteLn('Not a valid attempt, you lose your turn.');
WriteLn('You also lose 5 points for entering an invalid word');
PlayerScore := PlayerScore - 5;
end;
```

Java:

```    void haveTurn(String playerName, Tiles playerTiles,
TileCount playerTilesPlayed, Score playerScore, Map tileDictionary,
QueueOfTiles tileQueue, String[] allowedWords, int maxHandSize,
int noOfEndOfTurnTiles)
{
Console.println();
Console.println(playerName + " it is your turn.");
displayTilesInHand(playerTiles.playerTiles);
String newTileChoice = "2";
boolean validChoice = false;
boolean validWord;
while (!validChoice)
{
String choice = getChoice();
if (choice.equals("1"))
{
displayTileValues(tileDictionary, allowedWords);
}
else if (choice.equals("4"))
{
tileQueue.show();
}
else if (choice.equals("7"))
{
displayTilesInHand(playerTiles.playerTiles);
}
else if (choice.equals("0"))
{
validChoice = true;
fillHandWithTiles(tileQueue, playerTiles, maxHandSize);
}
else
{
validChoice = true;
if (choice.length() == 0)
{
validWord = false;
}
else
{
validWord = checkWordIsInTiles(choice, playerTiles.playerTiles);
}
if (validWord)
{
validWord = checkWordIsValid(choice, allowedWords);
if (validWord)
{
Console.println();
Console.println("Valid word");
Console.println();
updateAfterAllowedWord(choice, playerTiles, playerScore,
playerTilesPlayed, tileDictionary, allowedWords);
newTileChoice = getNewTileChoice();
}
}
if (!validWord)
{
Console.println();
Console.println("Not a valid attempt, you lose your turn.");
playerScore.score -= 1;
Console.println();
}
if (!newTileChoice.equals("4"))
{
}
Console.println();
Console.println("Your new score is:" + playerScore.score);
Console.println("You have played " + playerTilesPlayed.numberOfTiles + " tiles so far in this game.");
}
}
}
```

Python:

```def HaveTurn(PlayerName, PlayerTiles, PlayerTilesPlayed, PlayerScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles):
print()
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
while not ValidChoice:
Choice = GetChoice()
if Choice == "1":
DisplayTileValues(TileDictionary, AllowedWords)
elif Choice == "4":
TileQueue.Show()
elif Choice == "7":
DisplayTilesInHand(PlayerTiles)
elif Choice == "0":
ValidChoice = True
TileQueue, PlayerTiles = FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
else:
ValidChoice = True
if len(Choice) == 0:
ValidWord = False
else:
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
if ValidWord:
ValidWord = CheckWordIsValid(Choice, AllowedWords)
if ValidWord:
print()
print("Valid word")
print()
PlayerTiles, PlayerScore, PlayerTilesPlayed = UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
if not ValidWord:
# CHANGED CODE \/\/
InvalidPoints = 5
print()
print("Not a valid attempt, you lose your turn.")
print("You also lose {} points for entering an invalid word".format(InvalidPoints))
print()
PlayerScore -= InvalidPoints
# CHANGED CODE /\/\
if NewTileChoice != "4":
TileQueue, PlayerTiles = AddEndOfTurnTiles(TileQueue, PlayerTiles, NewTileChoice, Choice)
print()
print("You have played", PlayerTilesPlayed, "tiles so far in this game.")
return PlayerTiles, PlayerTilesPlayed, PlayerScore, TileQueue
```

VB.NET:

```    Sub HaveTurn(ByVal PlayerName As String, ByRef PlayerTiles As String, ByRef PlayerTilesPlayed As String, ByRef PlayerScore As Integer, ByVal TileDictionary As Dictionary(Of Char, Integer), ByRef TileQueue As QueueOfTiles, ByRef AllowedWords As List(Of String), ByVal MaxHandSize As Integer, ByVal NoOfEndOfTurnTiles As Integer)
Dim NewTileChoice As String
Dim Choice As String
Dim ValidChoice As Boolean
Dim ValidWord As Boolean
Console.WriteLine()
Console.WriteLine(PlayerName & " it is your turn.")
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
While Not ValidChoice
Choice = GetChoice()
If Choice = "1" Then
DisplayTileValues(TileDictionary, AllowedWords)
ElseIf Choice = "4" Then
TileQueue.Show()
ElseIf Choice = "7" Then
DisplayTilesInHand(PlayerTiles)
ElseIf Choice = "0" Then
ValidChoice = True
FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
Else
ValidChoice = True
If Len(Choice) = 0 Then
ValidWord = False
Else
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
End If
If ValidWord Then
ValidWord = CheckWordIsValid(Choice, AllowedWords)
If ValidWord Then
Console.WriteLine()
Console.WriteLine("Valid word")
Console.WriteLine()
UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
End If
End If
If Not ValidWord Then
Console.WriteLine()
Console.WriteLine("Not a valid attempt, you lose your turn.")
' CHANGED CODE BELOW
PlayerScore -= 5
' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Console.WriteLine()
End If
If NewTileChoice <> "4" Then
End If
Console.WriteLine()
Console.WriteLine("Your word was: " & Choice)
Console.WriteLine("Your new score is: " & PlayerScore)
Console.WriteLine("You have played " & PlayerTilesPlayed & " tiles so far in this game.")
End If
End While
End Sub
```

## Display list of words (valid and invalid) used by each player at the end of the game

Description of question

C#:

Firstly a list of strings variable called "PlayedWords" is created inside of the PlayGame Subroutine, this is used to store each of the words that our played by the player. This variable is then passed to the HaveTurn method and too the Display Winners Method.

```private static void PlayGame(List<string> AllowedWords, Dictionary<char, int> TileDictionary, bool RandomStart, int StartHandSize, int MaxHandSize, int MaxTilesPlayed, int NoOfEndOfTurnTiles)
{
List<string> PlayedWords = new List<string>();
...
...
while (PlayerOneTilesPlayed <= MaxTilesPlayed && PlayerTwoTilesPlayed <= MaxTilesPlayed && PlayerOneTiles.Length < MaxHandSize && PlayerTwoTiles.Length < MaxHandSize)
{
HaveTurn("Player One", ref PlayerOneTiles, ref PlayerOneTilesPlayed, ref PlayerOneScore, TileDictionary, ref TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, ref PlayedWords);
Console.WriteLine();
Console.WriteLine("Press Enter to continue");
Console.WriteLine();
HaveTurn("Player Two", ref PlayerTwoTiles, ref PlayerTwoTilesPlayed, ref PlayerTwoScore, TileDictionary, ref TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, ref PlayedWords);
}
DisplayWinner(PlayerOneScore, PlayerTwoScore, PlayedWords);
...
```

The HaveTurn method is then edited such it accepts the PlayedWords parameter as ref, if the user plays a word and the word is not 0 in length (blank), then it will be added to the list.

```private static void HaveTurn(string PlayerName, ref string PlayerTiles, ref int PlayerTilesPlayed, ref int PlayerScore, Dictionary<char, int> TileDictionary, ref QueueOfTiles TileQueue, List<string> AllowedWords, int MaxHandSize, int NoOfEndOfTurnTiles, ref List<string> PlayedWords)
{
...
else
{
ValidChoice = true;
if (Choice.Length == 0)
{
ValidWord = false;
}
else
{
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles);
}
```

The DisplayWinner method is also eddied such that it cycles through all the word plays and prints them to the console, using a foreach loop.

```private static void DisplayWinner(int PlayerOneScore, int PlayerTwoScore, List<string> PlayedWords)
{
...
Console.WriteLine("In this game the words played were:");
foreach (var Word in PlayedWords)
{
Console.WriteLine(Word);
}
Console.WriteLine();
...
```

Delphi/Pascal:

Java:

```//M Clarke - Thomas Adams College

void haveTurn(String playerName, Tiles playerTiles,
TileCount playerTilesPlayed, Score playerScore, Map tileDictionary,
QueueOfTiles tileQueue, String[] allowedWords, int maxHandSize,
int noOfEndOfTurnTiles, String[] disallowedWords, String wordLog[], int wordCount)
{
Scanner scan=new Scanner(System.in);
Console.println();
Console.println(playerName + ", it is your turn.");
displayTilesInHand(playerTiles.playerTiles);
String newTileChoice = "2";
boolean validChoice = false;
boolean validWord;
boolean validInput=false;
boolean validCheck=false;
String choice=null;
while (!validChoice){
while(validInput==false){
choice = getChoice();
validCheck=false;
while(validCheck==false){
System.out.println("");
System.out.println("Do you want "+choice+" to be your input? Y/N?");
try{
String res=scan.nextLine();
res=res.toUpperCase();
if(String.valueOf(res.charAt(0)).equals("Y")){
System.out.println("");
validInput=true;
validCheck=true;
}
else if(String.valueOf(res.charAt(0)).equals("N")){
validCheck=true;
}
else{
System.out.println("INVALID INPUT!");
}
}
catch(Exception e){
System.out.println("INVALID INPUT!");
}
}
}
boolean inapp=false;
validCheck=false;
validInput=false;
for(int x=0;x<40;x++){
if((choice.toUpperCase()).equals(disallowedWords[x].toUpperCase())){
inapp=true;
Console.println("**INAPPROPRIATE WORD INPUTTED**");
//from submethod above
}
}
if(inapp==false){
if (choice.equals("1"))
{
displayTileValues(tileDictionary, allowedWords);
}
else if (choice.equals("4"))
{
tileQueue.show();
}
else if(choice.equals("3")){
playerTiles.playerTiles=shuffleHand(playerTiles.playerTiles);
displayTilesInHand(playerTiles.playerTiles);
}
else if (choice.equals("7"))
{
displayTilesInHand(playerTiles.playerTiles);
}
else if (choice.equals("0"))
{
validChoice = true;
fillHandWithTiles(tileQueue, playerTiles, maxHandSize);
}
else if(choice.equals("2") || choice.equals("3") || choice.equals("5") || choice.equals("6") || choice.equals("8") || choice.equals("9") || choice.equals("1")) {
validChoice = false;
}
else
{
validChoice = true;
if (choice.length() == 0)
{
validWord = false;
}
else
{
validWord = checkWordIsInTiles(choice, playerTiles.playerTiles);
}
if (validWord)
{
validWord = checkWordIsValid(choice, allowedWords);
if (validWord)
{
Console.println();
Console.println("Valid word");
Console.println();
wordLog[wordCount]=String.valueOf(choice);
updateAfterAllowedWord(choice, playerTiles, playerScore,
playerTilesPlayed, tileDictionary, allowedWords, maxWordScore, playerName);
newTileChoice = getNewTileChoice();

}
}
if (!validWord)
{
Console.println();
playerScore.score -= 1;
wordLog[wordCount]=String.valueOf(choice);
Console.println("Not a valid attempt, you lose your turn.");
Console.println();
}
if (!newTileChoice.equals("4"))
{
}
Console.println();
Console.println("Your new score is:" + playerScore.score);
Console.println("You have played " + playerTilesPlayed.numberOfTiles + " tiles so far in this game.");
}
}
else{
Console.println();
playerScore.score -= 5;
Console.println("Not a valid attempt, you lose your turn.");
Console.println();
Console.println();
Console.println("Your new score is:" + playerScore.score);
Console.println("You have played " + playerTilesPlayed.numberOfTiles + " tiles so far in this game.");
validChoice = true;
wordLog[wordCount]="Invalid Response";
}
}
}

void displayWinner(String player1Name, String player2Name, int playerOneScore, int playerTwoScore, String wordLog[], String wordLog1[], int wordCount, int wordCount1)
{
Scanner scan=new Scanner(System.in);
Console.println();
Console.println("**** GAME OVER! ****");
Console.println();
Console.println(player1Name + " your score is " + playerOneScore);
Console.println(player2Name + " your score is " + playerTwoScore);
if (playerOneScore > playerTwoScore)
{
Console.println(player1Name + " wins!");
}
else if (playerTwoScore > playerOneScore)
{
Console.println(player2Name + " wins!");
}
else
{
Console.println("It is a draw!");
}
boolean validRes=false;
String res="";
while(validRes==false){
try{
Console.println("Do you wish to see "+player1Name+"'s log of played words? Y/N?");
res=scan.nextLine();
res=res.toUpperCase();
if(String.valueOf(res.charAt(0)).equals("Y")){
Console.println("");
for(int x=0;x<wordCount;x++){
try{
//trycatch required for null values if user inputs 0 for last input value
if(wordLog[x].equals(null)){
}
else{
System.out.println(String.valueOf(wordLog[x]));
}
}
catch(Exception e){
Console.println("");
x=999;
}
}
validRes=true;
}
else if(String.valueOf(res.charAt(0)).equals("N")){
validRes=true;
}
else{
System.out.println("INVALID INPUT!");
}
}
catch(Exception e){
Console.println("Invalid Response!");
}
}
validRes=false;
while(validRes==false){
try{
Console.println("Do you wish to see "+player2Name+"'s log of played words? Y/N?");
res=scan.nextLine();
res=res.toUpperCase();
if(String.valueOf(res.charAt(0)).equals("Y")){
Console.println("");
for(int x=0;x<wordCount1;x++){
try{
//trycatch required for null values if user inputs 0 for last input value
if(wordLog1[x].equals(null)){
}
else{
System.out.println(String.valueOf(wordLog1[x]));
}
}
catch(Exception e){
Console.println("");
x=999;
}
}
validRes=true;
}
else if(String.valueOf(res.charAt(0)).equals("N")){
validRes=true;
}
else{
System.out.println("INVALID INPUT!");
}
}
catch(Exception e){
Console.println("Invalid Response!");
}
}
}

void playGame(String[] allowedWords, Map tileDictionary, boolean randomStart,
int startHandSize, int maxHandSize, int maxTilesPlayed,
int noOfEndOfTurnTiles, String[] disallowedWords, String autoWin, String wordLog[], int wordCount, String wordLog1[], int wordCount1)
{
boolean nameVerif=false;
Scanner scan=new Scanner(System.in);
String player1Name=null;
String player2Name=null;
while(nameVerif==false){
//validation loop and trycatch for name input
try{
Console.println("Enter Name for Player 1: ");
player1Name=scan.nextLine();
nameVerif=true;
}
catch(Exception e){
System.out.println("Invalid Input Try Again!");
}
}
nameVerif=false;
while(nameVerif==false){
try{
Console.println("Enter Name for Player 2: ");
player2Name=scan.nextLine();
nameVerif=true;
}
catch(Exception e){
System.out.println("Invalid Input Try Again!");
}
}
Score playerOneScore = new Score();
playerOneScore.score = 50;
Score playerTwoScore = new Score();
playerTwoScore.score = 50;
TileCount playerOneTilesPlayed = new TileCount();
playerOneTilesPlayed.numberOfTiles = 0;
TileCount playerTwoTilesPlayed = new TileCount();
playerTwoTilesPlayed.numberOfTiles = 0;
Tiles playerOneTiles = new Tiles();
Tiles playerTwoTiles = new Tiles();
QueueOfTiles tileQueue  = new QueueOfTiles(20);
if(randomStart)
{
playerOneTiles.playerTiles = getStartingHand(tileQueue, startHandSize);
playerTwoTiles.playerTiles = getStartingHand(tileQueue, startHandSize);
}
else
{
playerOneTiles.playerTiles = "BTAHANDENONSARJ";
playerTwoTiles.playerTiles = "CELZXIOTNESMUAA";
}
while (playerOneTilesPlayed.numberOfTiles <= maxTilesPlayed &&
playerTwoTilesPlayed.numberOfTiles <= maxTilesPlayed &&
playerOneTiles.playerTiles.length() < maxHandSize &&
playerTwoTiles.playerTiles.length() < maxHandSize)
{
haveTurn(player1Name, playerOneTiles, playerOneTilesPlayed, playerOneScore,
tileDictionary, tileQueue, allowedWords, maxHandSize,
noOfEndOfTurnTiles, disallowedWords, autoWin, wordLog, wordCount);
wordCount++;
Console.println();
Console.println("Press Enter to continue");
Console.println();
haveTurn(player2Name, playerTwoTiles, playerTwoTilesPlayed, playerTwoScore,
tileDictionary, tileQueue, allowedWords, maxHandSize,
noOfEndOfTurnTiles, disallowedWords, autoWin, wordLog1, wordCount1);
wordCount1++;
}
playerOneTiles.playerTiles, tileDictionary);
playerTwoTiles.playerTiles, tileDictionary);
displayWinner(player1Name, player2Name, playerOneScore.score, playerTwoScore.score, wordLog, wordLog1, wordCount, wordCount1);
}

Main()
{
Console.println("++++++++++++++++++++++++++++++++++++++");
Console.println("+ Welcome to the WORDS WITH AQA game +");
Console.println("++++++++++++++++++++++++++++++++++++++");
Random rng=new Random();
Console.println();
Console.println();
//please view section above for inappropriate words
Map tileDictionary = createTileDictionary();
int maxHandSize = 20;
int maxTilesPlayed = 50;
int noOfEndOfTurnTiles = 3;
int startHandSize = 15;
String choice = "";
String wordLog[]=new String[200];
int wordCount=0;
String wordLog1[]=new String [200];
int wordCount1=0;
while(!choice.equals("9"))
{
if (choice.equals("1"))
{
autoWin=allowedWords[rng.nextInt(allowedWords.length)];
playGame(allowedWords, tileDictionary, true, startHandSize,
maxHandSize, maxTilesPlayed, noOfEndOfTurnTiles, disallowedWords, autoWin, wordLog, wordCount, wordLog1, wordCount1);
}
else if (choice.equals("2"))
{
autoWin=allowedWords[rng.nextInt(allowedWords.length)];
playGame(allowedWords, tileDictionary, false, 15, maxHandSize,
maxTilesPlayed, noOfEndOfTurnTiles, disallowedWords, autoWin, wordLog, wordCount, wordLog1, wordCount1);
}
}
}
```

Python:

```#By Hammad Mehmood, Herschel Grammar School. All the changes have comments on them

def PlayGame(AllowedWords, TileDictionary, RandomStart, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles):
PlayerOneScore = 50
PlayerTwoScore = 50
PlayerOneTilesPlayed = 0
PlayerTwoTilesPlayed = 0
PlayerOneValidWords = [] #List for the valid words of player 1
PlayerTwoValidWords = [] #List for the valid words of player 2
PlayerOneInvalidWords = [] #List for the invalid words of player 1
PlayerTwoInvalidWords = [] #List for the invalid words of player 2
#Pass these lists to have turn
TileQueue = QueueOfTiles(20)
if RandomStart:
PlayerOneTiles = GetStartingHand(TileQueue, StartHandSize)
PlayerTwoTiles = GetStartingHand(TileQueue, StartHandSize)
else:
PlayerOneTiles = "BTAHANDENONSARJ"
PlayerTwoTiles = "CELZXIOTNESMUAA"
while PlayerOneTilesPlayed <= MaxTilesPlayed and PlayerTwoTilesPlayed <= MaxTilesPlayed and len(PlayerOneTiles) < MaxHandSize and len(PlayerTwoTiles) < MaxHandSize:
PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileQueue = HaveTurn("Player One", PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, PlayerOneValidWords, PlayerTwoValidWords, PlayerOneInvalidWords, PlayerTwoInvalidWords)
print()
input("Press Enter to continue")
print()
PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileQueue = HaveTurn("Player Two", PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, PlayerOneValidWords, PlayerTwoValidWords, PlayerOneInvalidWords, PlayerTwoInvalidWords)
DisplayWinner(PlayerOneScore, PlayerTwoScore)
#Ask the players if they want to see the words
SeeWordsPlayed = input("Do you want to see all the words played (y/n)?").upper()
if SeeWordsPlayed == "Y": #If yes, then print all the lists
print("PlayerOneValidWords:", PlayerOneValidWords)
print("PlayerTwoValidWords:", PlayerTwoValidWords)
print("PlayerOneInvalidWords:", PlayerOneInvalidWords)
print("PlayerTwoInvalidWords:", PlayerTwoInvalidWords)
def HaveTurn(PlayerName, PlayerTiles, PlayerTilesPlayed, PlayerScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, PlayerOneValidWords, PlayerTwoValidWords, PlayerOneInvalidWords, PlayerTwoInvalidWords):
print()
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
while not ValidChoice:
Choice = GetChoice()
if Choice == "1":
DisplayTileValues(TileDictionary, AllowedWords)
elif Choice == "4":
TileQueue.Show()
elif Choice == "7":
DisplayTilesInHand(PlayerTiles)
elif Choice == "0":
ValidChoice = True
TileQueue, PlayerTiles = FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
else:
ValidChoice = True
if len(Choice) == 0:
ValidWord = False
else:
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
if ValidWord:
ValidWord = CheckWordIsValid(Choice, AllowedWords)
if ValidWord:
print()
print("Valid word")
print()
PlayerTiles, PlayerScore, PlayerTilesPlayed = UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
if not ValidWord:
print()
print("Not a valid attempt, you lose your turn.")
print()
if NewTileChoice != "4":
TileQueue, PlayerTiles = AddEndOfTurnTiles(TileQueue, PlayerTiles, NewTileChoice, Choice)
print()
print("You have played", PlayerTilesPlayed, "tiles so far in this game.")
#This is inside this else statement, because that is when the player enters a word
if PlayerName == "Player One": #If it is the player one
if ValidWord: #And the word is valid
PlayerOneValidWords.append(Choice) #Add the word to the corresponding list
else: #If the word in invalid
PlayerOneInvalidWords.append(Choice) #Add the word to the corresponding list
else: #If it is the player two
if ValidWord: #And the word is valid
PlayerTwoValidWords.append(Choice) #Add the word to the corresponding list
else: #If the word in invalid
PlayerTwoInvalidWords.append(Choice) #Add the word to the corresponding list
return PlayerTiles, PlayerTilesPlayed, PlayerScore, TileQueue
#By Hammad Mehmood, Herschel Grammar School
```

VB.NET:

```---------------------------------
'use 2d array in this format:
'[Valid/NotValid] | ["Word"]
---------------------------------
Module WordsWithAQA
Dim WordsP1(1, 0) As String 'reDim allows for the right most dimension to be increased only so this is why the orientation. (Increases y coordinate, not x)
Dim WordsP2(1, 0) As String
Sub Main()
---------------------------------
'This function increases the size of the 2D array after adding the word chosen
---------------------------------
Sub wordHistory(ByVal word As String, ByVal valid As String, ByVal playername As String)
If playername = "Player One" Then
WordsP1(0, (WordsP1.Length / 2) - 1) = word
WordsP1(1, (WordsP1.Length / 2) - 1) = valid
ReDim Preserve WordsP1(1, (WordsP1.Length / 2))
Else
WordsP2(0, (WordsP2.Length / 2) - 1) = word
WordsP2(1, (WordsP2.Length / 2) - 1) = valid
ReDim Preserve WordsP2(1, (WordsP2.Length / 2))
End If
Console.WriteLine()
End Sub
---------------------------------
---------------------------------
Sub HaveTurn(ByVal PlayerName As String, ByRef PlayerTiles As String, ByRef PlayerTilesPlayed As String, ByRef PlayerScore As Integer, ByVal TileDictionary As Dictionary(Of Char, Integer), ByRef TileQueue As QueueOfTiles, ByRef AllowedWords As List(Of String), ByVal MaxHandSize As Integer, ByVal NoOfEndOfTurnTiles As Integer)
Dim NewTileChoice As String
Dim Choice As String
Dim ValidChoice As Boolean
Dim ValidWord As Boolean
Console.WriteLine()
Console.WriteLine(PlayerName & " it is your turn.")
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
While Not ValidChoice
Choice = GetChoice()
If Choice = "1" Then
DisplayTileValues(TileDictionary, AllowedWords)
ElseIf Choice = "4" Then
TileQueue.Show()
ElseIf Choice = "7" Then
DisplayTilesInHand(PlayerTiles)
ElseIf Choice = "0" Then
ValidChoice = True
FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
Else
ValidChoice = True
If Len(Choice) = 0 Then
ValidWord = False
Else
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
End If
If ValidWord Then
ValidWord = CheckWordIsValid(Choice, AllowedWords)
If ValidWord Then
Console.WriteLine()
Console.WriteLine("Valid word")
wordHistory(Choice, "Valid", PlayerName) 'Calls Function Above
Console.WriteLine()
UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords, PlayerName)
NewTileChoice = GetNewTileChoice()
End If
End If
If Not ValidWord Then
Console.WriteLine()
Console.WriteLine("Not a valid attempt, you lose your turn.")
wordHistory(Choice, "Not Valid", PlayerName) 'Calls Function Above
Console.WriteLine()
End If
If NewTileChoice <> "4" Then
End If
Console.WriteLine()
Console.WriteLine("Your word was: " & Choice)
Console.WriteLine("Your new score is: " & PlayerScore)
Console.WriteLine("You have played " & PlayerTilesPlayed & " tiles so far in this game.")
End If
End While
End Sub
---------------------------------
'Cycle through for loop, stopping at "(WordsP1.Length / 2) - 2"
'This is probably bad practice but allows me to keep the reDim statement at the end of every wordHistory Addition
'without worrying about having a blank last record that is filled with each itteration
---------------------------------
Sub DisplayWinner(ByVal PlayerOneScore As Integer, ByVal PlayerTwoScore As Integer)
Console.WriteLine()
Console.WriteLine("**** GAME OVER! ****")
Console.WriteLine()
Console.WriteLine("****  Words Used ****")
Console.WriteLine()
Console.WriteLine("Player One's Words Used:")
If WordsP1(0, 0) <> "" Then
For WordP1 = 0 To (WordsP1.Length / 2) - 2
Console.WriteLine("     " & WordsP1(0, WordP1) & " : " & WordsP1(1, WordP1))
Next
Else
Console.WriteLine("     NO VALID WORDS")
End If
Console.WriteLine("Player Two's Words Used:")
If WordsP2(0, 0) <> "" Then
For WordP2 = 0 To (WordsP2.Length / 2) - 2 '-2 to cut off blank record that is filled with each wordHistory addition
Console.WriteLine("     " & WordsP2(0, WordP2) & " : " & WordsP2(1, WordP2))
Next
Else
Console.WriteLine("     NO VALID WORDS")
End If
```

Luke Price, Havant College

## Display the highest scored word by each player at the end of the game

Description of question

C#:

```private static void PlayGame(List<string> AllowedWords, Dictionary<char, int> TileDictionary, bool RandomStart,
int StartHandSize, int MaxHandSize, int MaxTilesPlayed, int NoOfEndOfTurnTiles) {
int PlayerOneScore = 50;
int PlayerTwoScore = 50;
int PlayerThreeScore = 50;
int PlayerOneTilesPlayed = 0;
int PlayerTwoTilesPlayed = 0;
int PlayerThreeTilesPlayed = 0;
string PlayerOneTiles = "";
string PlayerTwoTiles = "";
string PlayerThreeTiles = "";
string PlayerOneHighestScoringWord = "";   //
string PlayerTwoHighestScoringWord = "";   // 3 Basic variables to store Words
string PlayerThreeHighestScoringWord = ""; //

QueueOfTiles TileQueue = new QueueOfTiles(20);
if (RandomStart) {
PlayerOneTiles = GetStartingHand(TileQueue, StartHandSize);
PlayerTwoTiles = GetStartingHand(TileQueue, StartHandSize);
PlayerThreeTiles = GetStartingHand(TileQueue, StartHandSize);
}
else {
PlayerOneTiles = "--AHANDENONSARJ";
PlayerTwoTiles = "CELZXIOTNESMUAA";
PlayerThreeTiles = "ABCDEFGHIJKLMNO";
}
while (PlayerOneTilesPlayed <= MaxTilesPlayed && PlayerTwoTilesPlayed <= MaxTilesPlayed && PlayerThreeTilesPlayed <= MaxTilesPlayed
&& PlayerOneTiles.Length < MaxHandSize && PlayerTwoTiles.Length < MaxHandSize && PlayerThreeTiles.Length < MaxHandSize) {
HaveTurn("Player One", ref PlayerOneTiles, ref PlayerOneTilesPlayed, ref PlayerOneScore, TileDictionary,
ref TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, ref PlayerOneHighestScoringWord); //
Console.WriteLine();
Console.WriteLine("Press Enter to continue");
Console.WriteLine();
HaveTurn("Player Two", ref PlayerTwoTiles, ref PlayerTwoTilesPlayed, ref PlayerTwoScore, TileDictionary,
ref TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, ref PlayerTwoHighestScoringWord); //
Console.WriteLine();
Console.WriteLine("Press Enter to continue");
Console.WriteLine();
HaveTurn("Player Three", ref PlayerThreeTiles, ref PlayerThreeTilesPlayed, ref PlayerThreeScore, TileDictionary,
ref TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, ref PlayerThreeHighestScoringWord); //
}

DisplayWinner(PlayerOneScore, PlayerOneHighestScoringWord, PlayerTwoScore, PlayerTwoHighestScoringWord,
PlayerThreeScore, PlayerThreeHighestScoringWord); //
}

//Edited Portion of HaveTurn
private static void HaveTurn(string PlayerName, ref string PlayerTiles, ref int PlayerTilesPlayed, ref int PlayerScore,
Dictionary<char, int> TileDictionary, ref QueueOfTiles TileQueue, List<string> AllowedWords, int MaxHandSize,
int NoOfEndOfTurnTiles, ref string HighestScoringWord) {
.
.
if (ValidWord) {
string AmendedChoice = ResolveBlanks(Choice);
ValidWord = CheckWordIsValid(AmendedChoice, AllowedWords);
if (ValidWord) {
int WordScore = GetScoreForWord(AmendedChoice, TileDictionary);
if (WordScore > GetScoreForWord(HighestScoringWord, TileDictionary))
HighestScoringWord = AmendedChoice; //Updates variable if new word is more points than current highest scoring word
Console.WriteLine();
Console.WriteLine(\$"Valid word. {AmendedChoice} scored {WordScore} points.");
Console.WriteLine();
UpdateAfterAllowedWord(Choice, AmendedChoice, ref PlayerTiles, ref PlayerScore, ref PlayerTilesPlayed, TileDictionary,
AllowedWords);
NewTileChoice = GetNewTileChoice();
}
}
.
.
}

private static void DisplayWinner(int PlayerOneScore, string PlayerOneHighestScoringWord, int PlayerTwoScore, //
string PlayerTwoHighestScoringWord, int PlayerThreeScore, string PlayerThreeHighestScoringWord) {         //
Console.WriteLine();
Console.WriteLine("**** GAME OVER! ****");
Console.WriteLine();
Console.WriteLine(\$"Player One your score is {PlayerOneScore} and you best word was {PlayerOneHighestScoringWord}");      //
Console.WriteLine(\$"Player Two your score is {PlayerTwoScore} and you best word was {PlayerTwoHighestScoringWord}");      //Edited Code
Console.WriteLine(\$"Player Three your score is {PlayerThreeScore} and you best word was {PlayerThreeHighestScoringWord}");//
if (PlayerOneScore > PlayerTwoScore && PlayerOneScore > PlayerThreeScore) {
Console.WriteLine("Player One wins!");
}
else if (PlayerTwoScore > PlayerOneScore && PlayerTwoScore > PlayerThreeScore) {
Console.WriteLine("Player Two wins!");
}
else if (PlayerThreeScore > PlayerOneScore && PlayerThreeScore > PlayerTwoScore) {
Console.WriteLine("Player Three wins!");
}
else {
Console.WriteLine("No clear winner");
}
Console.WriteLine();
}
```

Delphi/Pascal:

Java:

Python:

```#This code also works perfectly with the player names code lower down
# code compares player name to an empty dictionary, I used a list instead
# Idris Khan Oak Academy (edit)

def HaveTurn(PlayerName, PlayerTiles, PlayerTilesPlayed, PlayerScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, BestWords):
print()
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
while not ValidChoice:
Choice = GetChoice()
if Choice == "1":
DisplayTileValues(TileDictionary, AllowedWords)
elif Choice == "4":
TileQueue.Show()
elif Choice == "7":
DisplayTilesInHand(PlayerTiles)
elif Choice == "0":
ValidChoice = True
TileQueue, PlayerTiles = FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
else:
ValidChoice = True
if len(Choice) == 0:
ValidWord = False
else:
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
if ValidWord:
ValidWord = CheckWordIsValid(Choice, AllowedWords)
if ValidWord:
WordScore = GetScoreForWord(Choice,TileDictionary)
# edit
word_score = get_score_for_word(choice, tile_dictionary) # get the score for the word
if player_name in BestWords[0][0]: # access the first item in the list, and access the first item in the second list
if word_score > BestWords[0][2]: # compare the int score values, if word score is greater then
BestWords[0][1] = choice # set player one's best word as the word they just played
BestWords[0][2] = word_score # set the new highest score for player one
else:
pass
if player_name in BestWords[1][0]:
if word_score > BestWords[1][2]:
BestWords[1][1] = choice
BestWords[1][2] = word_score
else:
pass
# edit

# orignial below
if PlayerName in BestWords.keys():
if WordScore > BestWords[PlayerName][0]:
BestWords[PlayerName] = [WordScore,Choice]
else:
BestWords[PlayerName] = [WordScore,Choice]
if PlayerName in BestWords.keys():
if WordScore > BestWords[PlayerName][0]:
BestWords[PlayerName] = [WordScore,Choice]
else:
BestWords[PlayerName] = [WordScore,Choice]
# orginal above
print()
print("Valid word")
print()
PlayerTiles, PlayerScore, PlayerTilesPlayed = UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords)
NewTileChoice = GetNewTileChoice()
if not ValidWord:
print()
print("Not a valid attempt, you lose your turn.")
print()
if NewTileChoice != "4":
TileQueue, PlayerTiles = AddEndOfTurnTiles(TileQueue, PlayerTiles, NewTileChoice, Choice)
print()
print("You have played", PlayerTilesPlayed, "tiles so far in this game.")
return PlayerTiles, PlayerTilesPlayed, PlayerScore, TileQueue, BestWords

def DisplayWinner(PlayerOneScore, PlayerTwoScore, BestWords):
print()
print("**** GAME OVER! ****")
print()
print("Player One your score is", PlayerOneScore)
print("Player Two your score is", PlayerTwoScore)
print()
# edit
# print each item in the nested list for each player
print('player one your best word was ' + best_words[0][1] +
' scoring ' + str(best_words[0][2])
)
print('player two your best word was ' + BestWords[1][1] +
' scoring ' + str(BestWords[1][2])
)
# edit

# original
for Name in BestWords.keys():
print("{} your best word was {}, scoring {} points".format(Name,BestWords[Name][1],BestWords[Name][0]))
# original
if PlayerOneScore > PlayerTwoScore:
print("Player One wins!")
elif PlayerTwoScore > PlayerOneScore:
print("Player Two wins!")
else:
print("It is a draw!")
print()

def PlayGame(AllowedWords, TileDictionary, RandomStart, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles):
#edit
# create a nested list, one being for player one and the other for being player two, each storing their best word and score with it
BestWords = [
['player one', '', 0]
['player two', '', 0]
]
# edit

# original code
BestWords = {}
# original code
PlayerOneScore = 50
PlayerTwoScore = 50
PlayerOneTilesPlayed = 0
PlayerTwoTilesPlayed = 0
TileQueue = QueueOfTiles(20)
if RandomStart:
PlayerOneTiles = GetStartingHand(TileQueue, StartHandSize)
PlayerTwoTiles = GetStartingHand(TileQueue, StartHandSize)
else:
PlayerOneTiles = "BTAHANDENONSARJ"
PlayerTwoTiles = "CELZXIOTNESMUAA"
while PlayerOneTilesPlayed <= MaxTilesPlayed and PlayerTwoTilesPlayed <= MaxTilesPlayed and len(PlayerOneTiles) < MaxHandSize and len(PlayerTwoTiles) < MaxHandSize:
PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileQueue, BestWords = HaveTurn("Player One", PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, BestWords)
print()
input("Press Enter to continue")
print()
PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileQueue, BestWords = HaveTurn("Player Two", PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, BestWords)
DisplayWinner(PlayerOneScore, PlayerTwoScore, BestWords)
```

VB.NET:

```--------------------------------------
'Define simple array structure to store HS, looks nice and does the job.
'# should be removed before compiling else it will be displayed in the highscore display at the end of a game if no valid words are given all game; leave it blank...
--------------------------------------
Module WordsWithAQA
Sub Main()
Dim TopScoreP1() As String = {"#", 0}
Dim TopScoreP2() As String = {"#", 0}
--------------------------------------
'Check the scores as they are updated. This is done in this module to keep all update procedures together
--------------------------------------
Sub UpdateAfterAllowedWord(ByVal Word As String, ByRef PlayerTiles As String, ByRef PlayerScore As Integer, ByRef PlayerTilesPlayed As Integer, ByVal TileDictionary As Dictionary(Of Char, Integer), ByRef AllowedWords As List(Of String), ByVal CurrentPlayer As String)
'note the currentplayer is also passed
Dim TurnScore As New Integer 'as new initialises the variable with the default value, 0, rather than this having to be done on a separate line
PlayerTilesPlayed += Len(Word)
For Each Letter In Word
PlayerTiles = Replace(PlayerTiles, Letter, "", , 1)
Next
TurnScore = GetScoreForWord(Word, TileDictionary) 'used another variable to improve efficiency as it only requires the GetScoreForWord function to be run once
PlayerScore += TurnScore
If CurrentPlayer = "Player One" Then 'check to ensure the program updates the correct person's highscore
If TopScoreP1(1) < TurnScore Then
TopScoreP1(1) = TurnScore
TopScoreP1(0) = Word
Console.WriteLine("New Highscore! Player 1 increased their highscore with:") 'new highscore info is displayed
Console.WriteLine(Word & " : " & TurnScore)
End If
Else
If TopScoreP2(1) < TurnScore Then
TopScoreP2(1) = TurnScore
TopScoreP2(0) = Word
Console.WriteLine("New Highscore! Player 2 increased their highscore with:")
Console.WriteLine(Word & " : " & TurnScore)
End If
End If
End Sub
--------------------------------------
'As the program ends, it displays the high scores
--------------------------------------
Sub DisplayWinner(ByVal PlayerOneScore As Integer, ByVal PlayerTwoScore As Integer)
Console.WriteLine()
Console.WriteLine("**** GAME OVER! ****")
Console.WriteLine()
Console.WriteLine("****  Highscore ****")
If TopScoreP1(1) > TopScoreP2(1) Then
Console.WriteLine("Player One had the highest score of " & TopScoreP1(1) & " with " & TopScoreP1(0))
ElseIf TopScoreP1(1) < TopScoreP2(1) Then
Console.WriteLine("Player Two had the highest score of " & TopScoreP2(1) & " with " & TopScoreP2(0))
Else 'the scores match
Console.WriteLine("Both players scored the joint highest score of " & TopScoreP1(1))
Console.WriteLine("Player 1" & TopScoreP1(0))
Console.WriteLine("Player 2" & TopScoreP2(0))
End If
Console.WriteLine()
--------------------------------------
Luke Price, Havant College
```

## Wild card / blank tile added

Description of question

C#:

```public void Add()
{
int RandNo = 0;
if (Rear < MaxSize - 1)
{
/* The exclusive upper bound of the random int has been increased by 1 so there is a chance of rolling
* the new Wildcard character */
RandNo = Rnd.Next(0, 27);
Rear++;
/* We don't actually want to add the character after 'Z' ('[')
* so RandNo is updated so 65 + Rando == '_' */
if (RandNo == 26) { RandNo = 30; }
Contents[Rear] = Convert.ToChar(65 + RandNo).ToString(); /* Now we can add the character as normal */
}
}
private static void CreateTileDictionary(ref Dictionary<char, int> TileDictionary)
{
int[] Value1 = { 0, 4, 8, 13, 14, 17, 18, 19};
int[] Value2 = { 1, 2, 3, 6, 11, 12, 15, 20 };
int[] Value3 = { 5, 7, 10, 21, 22, 24 };
/* Add the wildcard character to the dictionary seperately.
*  I have chosen the underscore character '_' but this is an arbitrary
*  decision */
TileDictionary.Add((char)(65 + 30), 0); /* I chose a point value of 0 for the wildcard character*/
for (int Count = 0; Count < 26; Count++)
{
if (Array.IndexOf(Value1, Count) > -1)
{
}
else if (Array.IndexOf(Value2, Count) > -1)
{
}
else if (Array.IndexOf(Value3, Count) > -1)
{
}
else
{
}
}
}
private static bool CheckWordIsValid(string Word, List<string> AllowedWords)
{
bool ValidWord = false;
int Count = 0;
while (Count < AllowedWords.Count && !ValidWord)
{
/* The
* If the two words don't have any letters difference, they must be the same */
if (LettersDiff(AllowedWords[Count], Word) == 0)
{
/* This line isn't necessary, but I thought it would be cool to see what word the wildcards matched to*/
Console.WriteLine("Matching word {0}", AllowedWords[Count]);
ValidWord = true;
}
Count++;
}
return ValidWord;
}
/* LettersDiff() is a method that returns the number of letters between two strings that do not match */
private static int LettersDiff(string s1, string s2)
{
/* If s1 is longer than s2, the maximum difference in letters between them is the length of s1.
* Likewise, if s2 is longer than s1, the maximum difference is the length of s2.
*
* diff = (condition)?(value1):(value2) is another way of writing:
* if((condition))
*  {
*      diff = (value1)
*  }
*  else
*  {
*      diff = (value2)
*  }
*/
int diff = s1.Length > s2.Length ? s1.Length : s2.Length;
for(int i = 0; i < s1.Length && i < s2.Length; i++) /* Loop until one of the words has ended */
{
/* This condition checks to see if the letters in both strings at index i are the same.
* If either word has a wildcard at index i, it will be considered equal to any other
* character */
if(s1[i] == s2[i] || s2[i]=='_'|| s2[i]=='_')
{
diff--; /* If the letters are the same, that is one less letter that is different */
}
}
return diff;
}
```

C#: Another Idea:

This method is also a 'blank tile' however this works as in Scrabble, where it allows user to choose which letter the blank may represent.
```//This works like the previous idea, but directly adds an underscore, instead of using the ASCII code
{
int RandNo = 0;
if (Rear < MaxSize - 1)
{
RandNo = Rnd.Next(0, 27);
Rear++;
if (RandNo == 26)
{
Contents[Rear] = "_";
}
else
{
Contents[Rear] = Convert.ToChar(65 + RandNo).ToString();
}
}
}

// This goes within HaveTurn in the while loop.
else if (Choice.Contains("_")) //if the word contains a blank tile
{
ValidChoice = true;
if (Choice.Count(c => c == '_') != 1) //only allows for 1 blank to be used at a time
{
ValidWord = false;
}
else
{
char userInput = ' ';
while (!validBlank)
{
bool validChar = false;
while (!validChar)
{
Console.Write(\$"Enter blank letter: "); //takes in the users choice of letter for the blank
try
{
userInput = Convert.ToChar(Console.ReadLine().ToUpper()); //validates it is a singular character
validChar = true;
}
catch
{
Console.WriteLine("Invalid blank, try again.");
}
}
if (char.IsLetter(userInput)) //makes sure its a letter
{
Choice = Choice.Replace('_', userInput); //replaces the blank with the letter
validBlank = true;
ValidWord = true;
}
else
{
Console.WriteLine("That was not a letter, please try again.");
}
}
}
if (ValidWord) //just a repeat of the Else statement from this, couldn't find a way of running it afterwards without copy/paste
{
ValidWord = CheckWordIsValid(Choice, AllowedWords);
if (ValidWord)
{
Console.WriteLine();
Console.WriteLine("Valid word");
Console.WriteLine();
UpdateAfterAllowedWord(Choice, ref PlayerTiles, ref PlayerScore, ref PlayerTilesPlayed, TileDictionary, AllowedWords);
NewTileChoice = GetNewTileChoice();
}
}
if (!ValidWord)
{
Console.WriteLine();
Console.WriteLine("Not a valid attempt, you lose your turn.");
Console.WriteLine();
}
if (NewTileChoice != "4")
{
AddEndOfTurnTiles(ref TileQueue, ref PlayerTiles, NewTileChoice, Choice);
}
Console.WriteLine();
Console.WriteLine("Your new score is:" + PlayerScore);
Console.WriteLine("You have played " + PlayerTilesPlayed + " tiles so far in this game.");
}
```

Delphi/Pascal:

Java:

```    String resolveBlanks(String word)
{
String newLetter;
for(int x = 0; x < word.length(); x++)
{
if(word.charAt(x) == '-')
{
Console.print("Enter value of blank tile: ");
word = word.substring(0, x) + newLetter + word.substring(1, x);
}
}
return word;
}
```

Python:

```import re

class QueueOfTiles():
def __init__(self, MaxSize):
self._Contents = []
self._Rear = -1
self._MaxSize = MaxSize
for Count in range(self._MaxSize):
self._Contents.append("")

def IsEmpty(self):
if self._Rear == -1:
return True
else:
return False

def Remove(self):
if self.IsEmpty():
return None
else:
Item = self._Contents[0]
for Count in range (1, self._Rear + 1):
self._Contents[Count - 1] = self._Contents[Count]
self._Contents[self._Rear] = ""
self._Rear -= 1
return Item

if self._Rear < self._MaxSize - 1:
RandNo = random.randint(0, 26)
self._Rear += 1
if RandNo == 26:
self._Contents[self._Rear] = '#'
else:
self._Contents[self._Rear] = chr(65 + RandNo)

def Show(self):
if self._Rear != -1:
print()
print("The contents of the queue are: ", end="")
for Item in self._Contents:
print(Item, end="")
print()

def CreateTileDictionary():
TileDictionary = dict()
for Count in range(26):
if Count in [0, 4, 8, 13, 14, 17, 18, 19]:
TileDictionary[chr(65 + Count)] = 1
elif Count in [1, 2, 3, 6, 11, 12, 15, 20]:
TileDictionary[chr(65 + Count)] = 2
elif Count in [5, 7, 10, 21, 22, 24]:
TileDictionary[chr(65 + Count)] = 3
else:
TileDictionary[chr(65 + Count)] = 5
TileDictionary['#'] = 1
return TileDictionary

def DisplayTileValues(TileDictionary, AllowedWords):
print()
print("TILE VALUES")
print()
for Letter, Points in TileDictionary.items():
print("Points for " + Letter + ": " + str(Points))
print("Points for #: 1")
print()

def CheckWordIsInTiles(Word, PlayerTiles):
InTiles = True
CopyOfTiles = PlayerTiles
for Count in range(len(Word)):
if Word[Count] in CopyOfTiles:
CopyOfTiles = CopyOfTiles.replace(Word[Count], "", 1)
elif '#' in CopyOfTiles:
CopyOfTiles = CopyOfTiles.replace('#', "", 1)
else:
InTiles = False
return InTiles

def CheckWordIsValid(Word, AllowedWords):
if '#' in Word: return CheckWordWildcard(Word,AllowedWords)
ValidWord = False
Count = 0
while Count < len(AllowedWords) and not ValidWord:
if AllowedWords[Count] == Word:
ValidWord = True
Count += 1
return ValidWord

def CheckWordWildcard(Word, AllowedWords):
ValidWord = False
reWord = "^"+Word.replace("#",".")+"\$"
for AllowedWord in AllowedWords:
if len(Word) != len(AllowedWord):
continue
if re.match(reWord,AllowedWord):
return True
return False
```

VB.NET:

```'HASNAIN
Sub HaveTurn(ByVal PlayerName As String, ByRef PlayerTiles As String, ByRef PlayerTilesPlayed As String, ByRef PlayerScore As Integer, ByVal TileDictionary As Dictionary(Of Char, Integer), ByRef TileQueue As QueueOfTiles, ByRef AllowedWords As List(Of String), ByVal MaxHandSize As Integer, ByVal NoOfEndOfTurnTiles As Integer)
Dim NewTileChoice As String
Dim Choice As String
Dim ValidChoice As Boolean
Dim ValidWord As Boolean
Dim CopyOfChoice As String = ""
Console.WriteLine()
Console.WriteLine(PlayerName & " it is your turn.")
DisplayTilesInHand(PlayerTiles)
NewTileChoice = "2"
ValidChoice = False
While Not ValidChoice
Choice = GetChoice()
If Choice = "1" Then
DisplayTileValues(TileDictionary, AllowedWords)
ElseIf Choice = "4" Then
TileQueue.Show()
ElseIf Choice = "7" Then
DisplayTilesInHand(PlayerTiles)
ElseIf Choice = "0" Then
ValidChoice = True
FillHandWithTiles(TileQueue, PlayerTiles, MaxHandSize)
Else
ValidChoice = True
If Len(Choice) = 0 Then
ValidWord = False
Else
ValidWord = CheckWordIsInTiles(Choice, PlayerTiles)
If ValidWord Then
CopyOfChoice = Choice
Choice = ResolveBlanks(Choice)
End If
End If
If ValidWord Then
ValidWord = CheckWordIsValid(Choice, AllowedWords)
If ValidWord Then
Console.WriteLine()
Console.WriteLine("Valid word")
Console.WriteLine()
UpdateAfterAllowedWord(Choice, PlayerTiles, PlayerScore, PlayerTilesPlayed, TileDictionary, AllowedWords, CopyOfChoice)
NewTileChoice = GetNewTileChoice()
End If
End If
If Not ValidWord Then
Console.WriteLine()
Console.WriteLine("Not a valid attempt, you lose your turn.")
Console.WriteLine()
End If
If NewTileChoice <> "4" Then
End If
Console.WriteLine()
Console.WriteLine("Your word was: " & Choice)
Console.WriteLine("Your new score is: " & PlayerScore)
Console.WriteLine("You have played " & PlayerTilesPlayed & " tiles so far in this game.")
End If
End While
End Sub

Function ResolveBlanks(word As String) As String
Dim NewLetter As Char
Dim NewWord As String = ""
For count = 0 To Len(word) - 1
If word(count) = "-" Then
Console.WriteLine("Enter value of blank tile")
NewWord += NewLetter
Else
NewWord += word(count)
End If
Next

Return NewWord
End Function

Sub UpdateAfterAllowedWord(ByVal Word As String, ByRef PlayerTiles As String, ByRef PlayerScore As Integer, ByRef PlayerTilesPlayed As Integer, ByVal TileDictionary As Dictionary(Of Char, Integer), ByRef AllowedWords As List(Of String), CopyOfChoice As String)
PlayerTilesPlayed += Len(Word)

For Each Letter In CopyOfChoice
PlayerTiles = Replace(PlayerTiles, Letter, "", , 1)
Next
PlayerScore += GetScoreForWord(Word, TileDictionary)
End Sub
'HASNAIN
```

## The player that has the letter that is closest to “A” will begin the game. A blank tile will win the start of the game

Description of question

C#:

Delphi/Pascal:

Java:

Python:

```# In comments, * denotes a wildcard in the variable name, eg PlayerFirst*
# could be PlayerFirstScore, PlayerFirstName etc.
#
# PlayerOne* and PlayerTwo* variables get renamed into PlayerFirst*
# and PlayerSecond* variables depending on order of play.
#
# PlayerOne DOES NOT ALWAYS BECOME PlayerFirst
# and likewise,
# PlayerTwo DOES NOT ALWAYS BECOME PlayerSecond
#
# Four ~new~ variables, PlayerOneName, PlayerTwoName, PlayerFirstName &
# PlayerSecondName, have been introduced to keep the naming constant
# at the end of the game regardless of who went first.
#
# This works with blank cards as long as the blank card ASCII value is < A.
# This also works with the player name code.

def DisplayWinner(PlayerFirstScore, PlayerSecondScore,PlayerFirstName,PlayerSecondName):
print()
print("**** GAME OVER! ****")
print()
if PlayerFirstScore > PlayerSecondScore:
print(PlayerFirstName+" wins!")
elif PlayerSecondScore > PlayerFirstScore:
print(PlayerSecondName+" wins!")
else:
print("It is a draw!")
print()

def PlayGame(AllowedWords, TileDictionary, RandomStart, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles):
PlayerFirstScore = 50
PlayerSecondScore = 50
PlayerFirstTilesPlayed = 0
PlayerSecondTilesPlayed = 0
TileQueue = QueueOfTiles(20)
PlayerOneName = "Player One"
PlayerTwoName = "Player Two"
if RandomStart:
PlayerOneTiles = GetStartingHand(TileQueue, StartHandSize)
PlayerTwoTiles = GetStartingHand(TileQueue, StartHandSize)
else:
PlayerOneTiles = "BTAHANDENONSARJ"
PlayerTwoTiles = "CELZXIOTNESMUAA"

# Obtain lowest tiles
PlayerOneLowestTile = min([ord(c) for c in PlayerOneTiles])
PlayerOneLowestAmount = PlayerOneTiles.count(chr(PlayerOneLowestTile))
PlayerTwoLowestTile = min([ord(c) for c in PlayerTwoTiles])
PlayerTwoLowestAmount = PlayerTwoTiles.count(chr(PlayerTwoLowestTile))

if PlayerOneLowestTile <= PlayerTwoLowestTile and PlayerOneLowestAmount >= PlayerTwoLowestAmount:
# If player one has the lowest tile, make PlayerOne into PlayerFirst and PlayerTwo into PlayerSecond
PlayerFirstName = PlayerOneName
PlayerFirstTiles = PlayerOneTiles
PlayerSecondName = PlayerTwoName
PlayerSecondTiles = PlayerTwoTiles
print("\n{} gets to go first as they had the lowest tile with '{}'".format(PlayerFirstName,chr(PlayerOneLowestTile)))
else:
# If player two has the lowest tile, make PlayerTwo into PlayerFirst and PlayerOne into PlayerSecond
PlayerFirstName = PlayerTwoName
PlayerFirstTiles = PlayerTwoTiles
PlayerSecondName = PlayerOneName
PlayerSecondTiles = PlayerOneTiles
print("\n{} gets to go first as they had the lowest tile with '{}'".format(PlayerFirstName,chr(PlayerTwoLowestTile)))

# All Player* variables past this point are now PlayerFirst* and PlayerSecond*

while PlayerFirstTilesPlayed <= MaxTilesPlayed and PlayerSecondTilesPlayed <= MaxTilesPlayed and len(PlayerFirstTiles) < MaxHandSize and len(PlayerSecondTiles) < MaxHandSize:
PlayerFirstTiles, PlayerFirstTilesPlayed, PlayerFirstScore, TileQueue = HaveTurn(PlayerFirstName, PlayerFirstTiles, PlayerFirstTilesPlayed, PlayerFirstScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles)
print()
input("Press Enter to continue")
print()
PlayerSecondTiles, PlayerSecondTilesPlayed, PlayerSecondScore, TileQueue = HaveTurn(PlayerSecondName, PlayerSecondTiles, PlayerSecondTilesPlayed, PlayerSecondScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles)
DisplayWinner(PlayerFirstScore, PlayerSecondScore,PlayerFirstName,PlayerSecondName)
```

VB.NET:

```Public Sub Add()
Dim RandNo As Integer = 0
If Rear < MaxSize - 1 Then
RandNo = Rnd.[Next](0, 27)
Rear += 1
If RandNo = 26 Then
RandNo = 30
End If

Contents(Rear) = Convert.ToChar(65 + RandNo).ToString()
End If
End Sub

Private Shared Sub CreateTileDictionary(ByRef TileDictionary As Dictionary(Of Char, Integer))
Dim Value1 As Integer() = {0, 4, 8, 13, 14, 17, 18, 19}
Dim Value2 As Integer() = {1, 2, 3, 6, 11, 12, 15, 20}
Dim Value3 As Integer() = {5, 7, 10, 21, 22, 24}
For Count As Integer = 0 To 26 - 1
If Array.IndexOf(Value1, Count) > -1 Then
ElseIf Array.IndexOf(Value2, Count) > -1 Then
ElseIf Array.IndexOf(Value3, Count) > -1 Then
Else
End If
Next
End Sub

Private Shared Function CheckWordIsValid(ByVal Word As String, ByVal AllowedWords As List(Of String)) As Boolean
Dim ValidWord As Boolean = False
Dim Count As Integer = 0
While Count < AllowedWords.Count AndAlso Not ValidWord
If LettersDiff(AllowedWords(Count), Word) = 0 Then
Console.WriteLine("Matching word {0}", AllowedWords(Count))
ValidWord = True
End If

Count += 1
End While

Return ValidWord
End Function

Private Shared Function LettersDiff(ByVal s1 As String, ByVal s2 As String) As Integer
Dim diff As Integer = If(s1.Length > s2.Length, s1.Length, s2.Length)
While i < s1.Length AndAlso i < s2.Length
If s1(i) = s2(i) OrElse s2(i) = "_"c OrElse s2(i) = "_"c Then
diff -= 1
End If

i += 1
End While

Return diff
End Function
```

## Vowel dump scores, words with multiple vowels ie AEON, AERO gain bonus points

Description of question

C#:

```private static int GetScoreForWord(string Word, Dictionary<char, int> TileDictionary)
{
int Score = 0;
char[] Vowels = { 'A', 'E', 'I', 'O', 'U' };	//Declares all the vowels
int VowelCount = 0;		//Used to record the number of vowels used
for (int Count = 0; Count < Word.Length; Count++)
{
Score = Score + TileDictionary[Word[Count]];
if (Vowels.Contains(Word[Count]))	//If the letter is a vowel
{
VowelCount++;	//Increment vowel count
}
}
if (Word.Length > 7)
{
Score = Score + 20;
}
else if (Word.Length > 5)
{
Score = Score + 5;
}

if(VowelCount >=3)	//If more then three vowels were used
{
Score += VowelCount * 2;	//Score = score + number of vowels * 2
}

return Score;
}
```

Delphi/Pascal:

Java:

```//by vriska serket of alternia sixth form college
//directish translation of the c#
int getScoreForWord(String word, Map tileDictionary) {
int score = 0;
List vowels = Arrays.asList('A', 'E', 'I', 'O', 'U'); //make a list which contains vowels
int vowelCount = 0; //also count the vowels

for (int count = 0; count < word.length(); count++) {
score += (int) tileDictionary.get(word.charAt(count));
if (vowels.contains(word.charAt(count))) {
vowelCount++; //increment vowel count if a vowel is found
}
}
if (word.length() > 7) {
score += 20;
} else if (word.length() > 5) {
score += 5;
}
if (vowelCount >= 3) //if 3 or more vowels are found
{
score += vowelCount * 2; //score + number of vowels * 2;
}
return score;
}
```

Python:

```def GetScoreForWord(Word, TileDictionary):
Vowels = "AEIOU"
Score = 0
VowelCount = 0
for Count in range (len(Word)):
Score += TileDictionary[Word[Count]]
if Word[Count] in Vowels:
VowelCount += 1
if len(Word) > 7:
Score += 20
elif len(Word) > 5:
Score += 5
if VowelCount >= 3:
Score += VowelCount * 2 # 2 extra points per vowel if three or more vowels played
return Score
```

VB.NET:

## In queue class definition, make use of the IsEmpty method in Show method

In queue class definition, make use of the IsEmpty method in Show method.

C#:

``` public void Show()
{
if (!IsEmpty())
{
Console.WriteLine();
Console.Write("The contents of the queue are: ");
foreach (var item in Contents)
{
Console.Write(item);
}
Console.WriteLine();
}
}
```

Delphi/Pascal:

Java:

Python:

```class QueueOfTiles():
def __init__(self, MaxSize):
self._Contents = []
self._Rear = -1
self._MaxSize = MaxSize
for Count in range(self._MaxSize):
self._Contents.append("")

def IsEmpty(self):
if self._Rear == -1:
return True
else:
return False

def Remove(self):
if self.IsEmpty():
return None
else:
Item = self._Contents[0]
for Count in range (1, self._Rear + 1):
self._Contents[Count - 1] = self._Contents[Count]
self._Contents[self._Rear] = ""
self._Rear -= 1
return Item

if self._Rear < self._MaxSize - 1:
RandNo = random.randint(0, 25)
self._Rear += 1
self._Contents[self._Rear] = chr(65 + RandNo)

def Show(self):
if self.IsEmpty():
print()
print("The queue is empty!")
print()
else:
print()
print("The contents of the queue are: ", end="")
for Item in self._Contents:
print(Item, end="")
print()
```

VB.NET:

```'another absolute work of genius by kam pokesie on twitter dot com forward slash actuallypokesie, your fav egirl
'give me a follow i need 1k
Public Sub Show()
If Not IsEmpty() Then
Console.WriteLine()
Console.Write("The contents of the queue are: ")
For Each Item In Contents
Console.Write(Item)
Next
Console.WriteLine()
Else
Console.WriteLine("The queue is empty!")
End If
End Sub
```

## Add the ability to set the player names

Add the ability to set the player names

C#:

``` private static void PlayGame(List<string> AllowedWords, Dictionary<char, int> TileDictionary, bool RandomStart, int StartHandSize, int MaxHandSize, int MaxTilesPlayed, int NoOfEndOfTurnTiles)
{
int PlayerOneScore = 50;
int PlayerTwoScore = 50;
int PlayerOneTilesPlayed = 0;
int PlayerTwoTilesPlayed = 0;
string PlayerOneTiles = "";
string PlayerTwoTiles = "";
QueueOfTiles TileQueue = new QueueOfTiles(20);

if (RandomStart)
{
PlayerOneTiles = GetStartingHand(TileQueue, StartHandSize);
PlayerTwoTiles = GetStartingHand(TileQueue, StartHandSize);
}
else
{
PlayerOneTiles = "BTAHANDENONSARJ";
PlayerTwoTiles = "CELZXIOTNESMUAA";
}
while (PlayerOneTilesPlayed <= MaxTilesPlayed && PlayerTwoTilesPlayed <= MaxTilesPlayed && PlayerOneTiles.Length < MaxHandSize && PlayerTwoTiles.Length < MaxHandSize)
{
HaveTurn(PlayerOneName, ref PlayerOneTiles, ref PlayerOneTilesPlayed, ref PlayerOneScore, TileDictionary, ref TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles);
Console.WriteLine();
Console.WriteLine("Press Enter to continue");
Console.WriteLine();
HaveTurn(PlayerTwoName, ref PlayerTwoTiles, ref PlayerTwoTilesPlayed, ref PlayerTwoScore, TileDictionary, ref TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles);
}
DisplayWinner(PlayerOneScore, PlayerTwoScore, PlayerOneName, PlayerTwoName);
}

private static void DisplayWinner(int PlayerOneScore, int PlayerTwoScore, string PlayerOneName, string PlayerTwoName)
{
Console.WriteLine();
Console.WriteLine("**** GAME OVER! ****");
Console.WriteLine();
Console.WriteLine(PlayerOneName + " your score is " + PlayerOneScore);
Console.WriteLine(PlayerTwoName + " your score is " + PlayerTwoScore);
if (PlayerOneScore > PlayerTwoScore)
{
Console.WriteLine(PlayerOneName + " wins!");
}
else if (PlayerTwoScore > PlayerOneScore)
{
Console.WriteLine(PlayerTwoName + " wins!");
}
else
{
Console.WriteLine("It is a draw!");
}
Console.WriteLine();
}
```

Delphi/Pascal:

```procedure HaveTurn(PlayerName : string; var PlayerTiles : string; var PlayerTilesPlayed : integer;
var PlayerScore : integer; TileDictionary : TTileDictionary; var TileQueue : QueueOfTiles;
var AllowedWords : TStringArray; MaxHandSize : integer; NoOfEndOfTurnTiles : integer);
var
NewTileChoice : string;
ValidChoice : boolean;
ValidWord : boolean;
Choice : string;
begin
writeln;
//Display input player names instead of Player One or Player Two
if PlayerName = 'Player One' then
writeln(Player1Name, ' it is your turn.')
Else
writeln(Player2Name, ' it is your turn.');
DisplayTilesInHand(PlayerTiles);
NewTileChoice := '2';
ValidChoice := False;
while not ValidChoice do

procedure DisplayWinner(PlayerOneScore : integer; PlayerTwoScore : integer);
begin
writeln;
writeln('**** GAME OVER! ****');
writeln;
writeln(Player1Name + ' your score is ', PlayerOneScore);
//Replaced Player One with Player1Name
writeln(Player2Name + ' your score is ', PlayerTwoScore);
//Replaced Player Two With Player2Name
if PlayerOneScore > PlayerTwoScore then
writeln(Player1Name + ' wins!')
//Replaced Player One with Player1Name
else if PlayerTwoScore > PlayerOneScore then
writeln(Player2Name + ' wins!')
//Replaced Player Two With Player2Name
else
writeln('It is a draw!');
writeln;
end;

//Procedure to input players names called from choice 1 in Main()
Procedure InputPlayerNames;
Begin
Write('Enter First Player Name: ');
Write('Enter Second Player Name: ');
End;
```

Java:

```void displayWinner(int playerOneScore, int playerTwoScore, String PlayerOneName, String PlayerTwoName) // Added playerone and playertwo to the function
{
Console.println();
Console.println("**** GAME OVER! ****");
Console.println();
Console.println(PlayerOneName +" your score is " + playerOneScore); // Change from string to variable.
Console.println(PlayerTwoName +"Player Two your score is " + playerTwoScore);
if (playerOneScore > playerTwoScore)
{
Console.println(PlayerOneName+ "wins!");
}
else if (playerTwoScore > playerOneScore)
{
Console.println( PlayerTwoName +"wins!");
}
else
{
Console.println("It is a draw!");
}
Console.println()  ;
}

void playGame(String[] allowedWords, Map tileDictionary, boolean randomStart,
int startHandSize, int maxHandSize, int maxTilesPlayed,
int noOfEndOfTurnTiles)
{
Score playerOneScore = new Score();
playerOneScore.score = 50;
Score playerTwoScore = new Score();
playerTwoScore.score = 50;
TileCount playerOneTilesPlayed = new TileCount();
playerOneTilesPlayed.numberOfTiles = 0;
TileCount playerTwoTilesPlayed = new TileCount();
playerTwoTilesPlayed.numberOfTiles = 0;
Tiles playerOneTiles = new Tiles();
Tiles playerTwoTiles = new Tiles();
QueueOfTiles tileQueue  = new QueueOfTiles(20);
String PlayerOneName = "";
String PlayerTwoName = "";

PlayerOneName  = Console.readLine(); // Gets the nameof the players
if(randomStart)
{
playerOneTiles.playerTiles = getStartingHand(tileQueue, startHandSize);
playerTwoTiles.playerTiles = getStartingHand(tileQueue, startHandSize);
}
else
{
playerOneTiles.playerTiles = "BTAHANDENONSARJ";
playerTwoTiles.playerTiles = "CELZXIOTNESMUAA";
}
while (playerOneTilesPlayed.numberOfTiles <= maxTilesPlayed &&
playerTwoTilesPlayed.numberOfTiles <= maxTilesPlayed &&
playerOneTiles.playerTiles.length() < maxHandSize &&
playerTwoTiles.playerTiles.length() < maxHandSize)
{
haveTurn(PlayerOneName, playerOneTiles, playerOneTilesPlayed, playerOneScore,
tileDictionary, tileQueue, allowedWords, maxHandSize,
noOfEndOfTurnTiles);
Console.println();
Console.println("Press Enter to continue");
Console.println();
haveTurn(PlayerTwoName, playerTwoTiles, playerTwoTilesPlayed, playerTwoScore,
tileDictionary, tileQueue, allowedWords, maxHandSize,
noOfEndOfTurnTiles);
}
playerOneTiles.playerTiles, tileDictionary);
playerTwoTiles.playerTiles, tileDictionary);
displayWinner(playerOneScore.score, playerTwoScore.score, PlayerOneName, PlayerTwoName);
}
```

Python:

```def DisplayWinner(PlayerOneScore, PlayerTwoScore, PlayerOneName, PlayerTwoName):
print()
print("**** GAME OVER! ****")
print()
print("{} your score is {}".format(PlayerOneName, PlayerOneScore))
print("{} your score is {}".format(PlayerTwoName, PlayerTwoScore))
if PlayerOneScore > PlayerTwoScore:
print```