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

From Wikibooks, open books for an open world
Jump to: navigation, search

This is for the new Computer Science Specification.

This is where suggestions can be made about what some of the questions might be and how we can solve them.

Please be respectful and do not vandalise or tamper with the page, as this would affect students' preparation for their exams!

Contents

Have more vowels[edit]

Change the distribution of letters so that there are 50% vowels and 50% consonants

C#:


Delphi/Pascal:


Java:


Python:

#By HAMMAD MEHMOOD, HERSCHEL GRAMMAR SCHOOL
  def Add(self):
    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

Change the distribution of letters[edit]

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;
                string letters = null;
                char NewLet;
                if (Rear < MaxSize - 1)
                {
                    letters = "aaaaaaaabbcccddddeeeeeeeeeeeefffggghhhhhhiiiiiijkllllmmnnnnnnooooooopqrrrrrsssssstttttttttuuvvwwxyyz";
                    RandNo = Rnd.Next(0, letters.Length);
                    NewLet = letters[RandNo];
                    Rear++;
                    Contents[Rear] = char.ToUpper(NewLet).ToString();
                }
            }

Delphi/Pascal:


Java:


Python:

def Add(self):
    if self._Rear < self._MaxSize - 1:
      letters = "aaaaaaaabbcccddddeeeeeeeeeeeefffggghhhhhhiiiiiijkllllmmnnnnnnooooooopqrrrrrsssssstttttttttuuvvwwxyyz"
      self._Rear += 1
      self._Contents[self._Rear] = random.choice(letters.upper())

OR:

def Add(self): 
    if self._Rear < self._MaxSize - 1:
      vowels = [0,4,8,14,20]
      consonants = [1,2,3,5,6,7,9,10,11,12,13,15,16,17,18,19,21,22,23,24,25]
      vowelChance = random.randint(0,1)
      if(vowelChance == 1):
        RandNo = random.choice(vowels)
      else:
        RandNo = random.choice(consonants)
      self._Rear += 1
      self._Contents[self._Rear] = chr(65 + RandNo)

VB.NET:

  Public Sub Add()
        Dim RandNo As Integer
        Dim letters As String
        Dim NewLet As String
        If Rear < MaxSize - 1 Then
            letters = "aaaaaaaabbcccddddeeeeeeeeeeeefffggghhhhhhiiiiiijkllllmmnnnnnnooooooopqrrrrrsssssstttttttttuuvvwwxyyz"
            RandNo = Int(Rnd() * (letters.Length - 1))
            NewLet = letters.Substring(RandNo, 1)
            Rear += 1
            Contents(Rear) = Char.ToUpper(NewLet)
        End If
    End Sub

Shuffle letter in hand[edit]

An option to shuffle the letter in the hand of the player, if they are in a different order it might help to find a word.

C#:


Delphi/Pascal:


Java:


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()
  print(PlayerName, "it is your turn.")
  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("Your word was:", Choice)
      print("Your new score is:", PlayerScore)
      print("You have played", PlayerTilesPlayed, "tiles so far in this game.")
  return PlayerTiles, PlayerTilesPlayed, PlayerScore, TileQueue  
#By HAMMAD MEHMOOD, HERSCHEL GRAMMAR SCHOOL

Allow players to skip and end their turn[edit]

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();
        TileQueue.Add();
    }
}

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("> ");
    Choice = Console.ReadLine();
    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 word was:" + Choice);
            Console.WriteLine("Your new score is:" + PlayerScore);
            Console.WriteLine("You have played " + PlayerTilesPlayed + " tiles so far in this game.");
        }
    }
}

Delphi/Pascal:


Java:

	int RandomNumber = 3;

    void addEndOfTurnTiles(QueueOfTiles tileQueue, Tiles playerTiles,
            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();
            tileQueue.add();
        }
    }

    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("> ");
        String choice = Console.readLine();
        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 ");
            addEndOfTurnTiles(tileQueue, playerTiles, "99", choice);
        }
        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"))
          {
            addEndOfTurnTiles(tileQueue, playerTiles, newTileChoice, choice);
          }
          Console.println();
          Console.println("Your word was:" + choice);
          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()
    TileQueue.Add()
  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()
  print(PlayerName, "it is your turn.")
  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)
      DisplayTilesInHand(PlayerTiles)
    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("Your word was:", Choice)
      print("Your new score is:", PlayerScore)
      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()
            TileQueue.Add()
        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("> ")
        Choice = Console.ReadLine()
        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 
                AddEndOfTurnTiles(TileQueue, PlayerTiles, "9", Choice)

                ' text output to alart the player of the penalty
                Console.WriteLine("You have skipped your turn. Penalty tiles have been added")
                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
                    AddEndOfTurnTiles(TileQueue, PlayerTiles, NewTileChoice, Choice)
                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[edit]

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

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("> ");
                Choice = Console.ReadLine();
                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:


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"))
          {
            addEndOfTurnTiles(tileQueue, playerTiles, newTileChoice, choice);
          }
          Console.println();
          Console.println("Your word was:" + choice);
          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:  
        print "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("> ")
            Choice = Console.ReadLine()
            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
                Console.WriteLine("Invalid Entry. Please Try Again")
            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
                    Console.WriteLine("Invalid Entry. Please Try Again")
                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
                        AddEndOfTurnTiles(TileQueue, PlayerTiles, NewTileChoice, Choice)
                    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

Save Game Feature[edit]

A feature that allows the user to save the game

C#:


Delphi/Pascal:


Java:


Python:

def LoadGame():
  SaveFile = open("save.txt",'r')
  lines = SaveFile.readlines()
  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):
  if not Load:
    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,PlayerOneTilesPlayed,PlayerOneTiles),(PlayerTwoScore,PlayerTwoTilesPlayed,PlayerTwoTiles),TileQueue = LoadGame()
      PlayerOneScore = int(PlayerOneScore)
      PlayerTwoScore = int(PlayerTwoScore)
      PlayerOneTilesPlayed = int(PlayerOneTilesPlayed)
      PlayerTwoTilesPlayed = int(PlayerTwoTilesPlayed)
    except:
      print()
      print("Save file not found")
      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)

  PlayerOneScore = UpdateScoreWithPenalty(PlayerOneScore, PlayerOneTiles, TileDictionary)
  PlayerTwoScore = UpdateScoreWithPenalty(PlayerTwoScore, PlayerTwoTiles, TileDictionary)
  DisplayWinner(PlayerOneScore, PlayerTwoScore)

def DisplayMenu():
  print()
  print("=========")
  print("MAIN MENU")
  print("=========")
  print()
  print("1. Play game with random start hand")
  print("2. Play game with training start hand")
  print("3. Load saved game")
  print("9. Quit")
  print()
  
def Main():
  print("++++++++++++++++++++++++++++++++++++++")
  print("+ Welcome to the WORDS WITH AQA game +")
  print("++++++++++++++++++++++++++++++++++++++")
  print()
  print()
  AllowedWords = LoadAllowedWords()
  TileDictionary = CreateTileDictionary()
  MaxHandSize = 20
  MaxTilesPlayed = 50
  NoOfEndOfTurnTiles = 3
  StartHandSize = 15
  Choice = ""
  while Choice != "9":
    DisplayMenu()
    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()

VB.NET:


Improve the searching algorithm[edit]

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

C#:


Delphi/Pascal:


Java:


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 ValidWord == False:
    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

Alert the User if aqawords.txt File is Missing[edit]

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

C#:

private static void LoadAllowedWords(ref List<string> AllowedWords)
{
    try
    {
        StreamReader FileReader = new StreamReader("aqawords.txt");
        while (!FileReader.EndOfStream)
        {
            AllowedWords.Add(FileReader.ReadLine().Trim().ToUpper());
        }
        FileReader.Close();
    }
    catch (FileNotFoundException)
    {
        Console.WriteLine("**** FILE NOT FOUND : aqawords.txt");
        Console.WriteLine("**** aqawords.txt does not exist. Please download.");
        Console.ReadKey();
        Environment.Exit(0);
        // AllowedWords.Clear();
    }
}

Delphi/Pascal:


Java:


Python:

def LoadAllowedWords():
  AllowedWords = []
  try:
    WordsFile = open("aqawords.txt", "r")
    for Word in WordsFile:
      AllowedWords.append(Word.strip().upper()) 
    WordsFile.close()
  except FileNotFoundError:
    print("The aqawords.txt file is missing, please download it")
    exit()

VB.NET:

    Sub LoadAllowedWords(ByRef AllowedWords As List(Of String))
        Try
            Dim FileReader As New System.IO.StreamReader("aqawords.txt")
            While FileReader.EndOfStream <> True
                AllowedWords.Add(FileReader.ReadLine().Trim().ToUpper())
            End While
            FileReader.Close()
        Catch
            ' AllowedWords.Clear()
            MsgBox("WARNING: aqawords.txt is missing. Please download it!", MsgBoxStyle.Exclamation)
            Environment.Exit(0)
        End Try
    End Sub

Allow players to add new words to the game[edit]

Ask the players to add new word(s) to be added to the valid word list.

C#:

private static void DisplayMenu()
{
    Console.WriteLine();
    Console.WriteLine("=========");
    Console.WriteLine("MAIN MENU");
    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. Add Words to Dictionary");
    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("");
    LoadAllowedWords(ref AllowedWords);
    CreateTileDictionary(ref TileDictionary);
    while (Choice != "9")
    {
        DisplayMenu();
        Console.Write("Enter your choice: ");
        Choice = Console.ReadLine();
        if (Choice == "1")
        {
            PlayGame(AllowedWords, TileDictionary, true, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles);
        }
        else if (Choice == "2")
        {
            PlayGame(AllowedWords, TileDictionary, false, 15, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles);
        }
        else if (Choice == "3")
        {
            Console.WriteLine("Enter word to be added");
            AddWords(ref AllowedWords);
        }
        else
            Console.WriteLine("\n \n invalid Choice \n");
    }
}

private static void AddWords(ref List<string> AllowedWords)
{
    string WordToBeAdded = Console.ReadLine();
    AllowedWords.Add(WordToBeAdded);
    Console.WriteLine(WordToBeAdded + " successfully added to dictionary");
}

Delphi/Pascal:


Java:


Python:

def LoadAllowedWords():                         
  AllowedWords = []
  try:
    WordsFile = open("aqawords.txt", "r")
    for Word in WordsFile:
      AllowedWords.append(Word.strip().upper())
    WordsFile.close()
    choice = "yes"
    while(choice == "yes" or choice == "Yes"):
      choice = input("Do you want to add any custom words? ")
      if(choice == "yes" or choice == "Yes"):
        newWord = input("Enter the new word to add : ")
        AllowedWords.append(newWord)
  except:
    pass
  return AllowedWords

VB.NET:

Sub Main()
        Dim Word As String
        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()
        LoadAllowedWords(AllowedWords)
        TileDictionary = CreateTileDictionary()
        MaxHandSize = 20
        MaxTilesPlayed = 50
        NoOfEndOfTurnTiles = 3
        StartHandSize = 15
        Choice = ""
        While Choice <> "9"
            DisplayMenu()
            Console.Write("Enter your choice: ")
            Choice = Console.ReadLine()
            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
                Console.Write("Word:")
                Word = Console.ReadLine().ToUpper
                AddWordToList(Word)
            End If
-----------------------------------------------------------------------------------------------------------------------------------
        End While
    End Sub
-----------------------------------------------------------------------------------------------------------------------------------
Sub AddWordToList(ByVal Word As String)
        Dim FileWriter As New System.IO.StreamWriter("(Insert your file path)\aqawords.txt", True)
        FileWriter.Write("")
        FileWriter.WriteLine(Word)
        FileWriter.Close()
        Console.WriteLine()
        Console.WriteLine("Word Successfully added")
        Console.WriteLine()
    End Sub
--------------------------------------------------------------------------------------------------------------------------------------
Sub DisplayMenu()
        Console.WriteLine()
        Console.WriteLine("=========")
        Console.WriteLine("MAIN MENU")
        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. Add a word")
----------------------------------------------------------------------------------------------------------------------------------------
        Console.WriteLine("9. Quit")
        Console.WriteLine()
    End Sub

Michael Slater - Jumeirah College

High score table feature[edit]

Add a high score table

C#:


Delphi/Pascal:


Java:


Python:

def SaveHighscore(Name,Score):
  ScoreFile = open("highscores.csv","a")
  ScoreFile.write(Name+","+str(Score)+"\n")
  ScoreFile.close()
  
def LoadHighscores():
  try:
    ScoreFile = open("highscores.csv","r")
  except: return []
  Highscores = []
  for Line in ScoreFile.read().split("\n"):
    if ',' in Line:
      Highscores.append(Line.split(","))
  return Highscores
  
def DisplayHighscores():
  Highscores = LoadHighscores()
  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":
    SaveHighscore(input("Please enter your name: "),PlayerOneScore)
  if input("Player Two would you like to save your score? (Y/N)").upper() == "Y":
    SaveHighscore(input("Please enter your name: "),PlayerTwoScore)
  print()

def DisplayMenu():
  print()
  print("=========")
  print("MAIN MENU")
  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()
  AllowedWords = LoadAllowedWords()
  TileDictionary = CreateTileDictionary()
  MaxHandSize = 20
  MaxTilesPlayed = 50
  NoOfEndOfTurnTiles = 3
  StartHandSize = 15
  Choice = ""
  while Choice != "9":
    DisplayMenu()
    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:


Time limit when entering choice[edit]

Add a time limit for turns

C#:


Delphi/Pascal:


Java:


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
  
  print()
  Choice = Choice.upper()
  return Choice

VB.NET:


Inappropriate word filter[edit]

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("> ");
            Choice = Console.ReadLine();
            Console.WriteLine();
            Choice = Choice.ToUpper();

            if(filteredWords.Contains(Choice))
            {
                Console.WriteLine();
                Console.WriteLine("Your word has been filtered, please try again");
                return GetChoice();
            }

            return Choice;
        }

Delphi/Pascal:


Java:


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()
    print("Your word has been filtered, please try again")
    return GetChoice()
  
  return Choice

VB.NET:


Ask user to confirm their word choice[edit]

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)");
                            strConfirm = Console.ReadLine().ToUpper();
                            if(strConfirm == "NO")
                            {
                                Console.WriteLine("Re-Input Word");
                                Choice = Console.ReadLine().ToUpper();
                            }
                        }
--------------------------------------------------------------------------------------
                        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 word was:" + Choice);
                    Console.WriteLine("Your new score is:" + PlayerScore);
                    Console.WriteLine("You have played " + PlayerTilesPlayed + " tiles so far in this game.");
                }
            }
        }

Delphi/Pascal:


Java:


Python:

def HaveTurn(PlayerName, PlayerTiles, PlayerTilesPlayed, PlayerScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles): 
  print()
  print(PlayerName, "it is your turn.") 
  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>")
        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("Your word was:", Choice)
    print("Your new score is:", PlayerScore)
    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)")
                        Confirm = Console.ReadLine().ToUpper
                        If Confirm = "NO" Then
                            Console.WriteLine("Re-Input Word")
                            Choice = Console.ReadLine().ToUpper
                        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
                    AddEndOfTurnTiles(TileQueue, PlayerTiles, NewTileChoice, Choice)
                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[edit]

Description of question

C#:


Delphi/Pascal:


Java:


Python:

#BY HAMMAD MEHMOOD, HERSCHEL GRAMMAR SCHOOL
#All the changes have comments
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)
  PlayerOneScore = UpdateScoreWithPenalty(PlayerOneScore, PlayerOneTiles, TileDictionary)
  PlayerTwoScore = UpdateScoreWithPenalty(PlayerTwoScore, PlayerTwoTiles, TileDictionary)
  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()
  print(PlayerName, "it is your turn.")
  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("Your word was:", Choice)
      print("Your new score is:", PlayerScore)
      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:


Bonus points if two or more high scoring tiles are played ie JAZ (J=5, A=1 ,Z=5)[edit]

Description of question

C#:


Delphi/Pascal:


Java:


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:


Bonus points at end of game for longest and highest scored words[edit]

Description of question

C#:


Delphi/Pascal:


Java:


Python:


VB.NET:


Deduct points from score if invalid word entered[edit]

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

C#:


Delphi/Pascal:


Java:


Python:

def HaveTurn(PlayerName, PlayerTiles, PlayerTilesPlayed, PlayerScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles):
  print()
  print(PlayerName, "it is your turn.")
  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("Your word was:", Choice)
      print("Your new score is:", PlayerScore)
      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
                    AddEndOfTurnTiles(TileQueue, PlayerTiles, NewTileChoice, Choice)
                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[edit]

Description of question

C#:


Delphi/Pascal:


Java:


Python:


VB.NET:


Display the highest scored word by each player at the end of the game[edit]

Description of question

C#:


Delphi/Pascal:


Java:


Python:

#This code also works perfectly with the player names code lower down

def HaveTurn(PlayerName, PlayerTiles, PlayerTilesPlayed, PlayerScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles, BestWords):
  print()
  print(PlayerName, "it is your turn.")
  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)
          if PlayerName in BestWords.keys():
            if WordScore > BestWords[PlayerName][0]:
              BestWords[PlayerName] = [WordScore,Choice]
          else:
            BestWords[PlayerName] = [WordScore,Choice]
          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("Your word was:", Choice)
      print("Your new score is:", PlayerScore)
      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()
  for Name in BestWords.keys():
    print("{} your best word was {}, scoring {} points".format(Name,BestWords[Name][1],BestWords[Name][0]))
  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):
  BestWords = {}
  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)
  PlayerOneScore = UpdateScoreWithPenalty(PlayerOneScore, PlayerOneTiles, TileDictionary)
  PlayerTwoScore = UpdateScoreWithPenalty(PlayerTwoScore, PlayerTwoTiles, TileDictionary)
  DisplayWinner(PlayerOneScore, PlayerTwoScore, BestWords)

VB.NET:


Wild card / blank tile added[edit]

Description of question

C#:


Delphi/Pascal:


Java:


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("")
      self.Add()
      
  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

  def Add(self):
    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:


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[edit]

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()
  print(PlayerFirstName+" your score is", PlayerFirstScore)
  print(PlayerSecondName+" your score is", PlayerSecondScore)
  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)
  PlayerFirstScore = UpdateScoreWithPenalty(PlayerFirstScore, PlayerFirstTiles, TileDictionary)
  PlayerSecondScore = UpdateScoreWithPenalty(PlayerSecondScore, PlayerSecondTiles, TileDictionary)
  DisplayWinner(PlayerFirstScore, PlayerSecondScore,PlayerFirstName,PlayerSecondName)

VB.NET:


Identification of Acronyms and abbreviations, user given option to enter word/acronym/abbreviation - different points awarded for each[edit]

Description of question

C#:


Delphi/Pascal:


Java:


Python:


VB.NET:


Vowel dump scores, words with multiple vowels ie AEON, AERO gain bonus points[edit]

Description of question

C#:


Delphi/Pascal:


Java:


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[edit]

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

C#:


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("")
      self.Add()
      
  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

  def Add(self):
    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:


Add the ability to set the player names[edit]

Add the ability to set the player names

C#:


Delphi/Pascal:


Java:


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("{} wins!".format(PlayerOneName))
  elif PlayerTwoScore > PlayerOneScore:
    print("{} wins!".format(PlayerTwoName))
  else:
    print("It is a draw!")
  print()
  
def PlayGame(AllowedWords, TileDictionary, RandomStart, StartHandSize, MaxHandSize, MaxTilesPlayed, NoOfEndOfTurnTiles):
  PlayerOneName = input("Player One, enter your name: ")
  PlayerTwoName = input("Player Two, enter your name: ")
  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 = HaveTurn(PlayerOneName, PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles)
    print()
    input("Press Enter to continue")
    print()
    PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileQueue = HaveTurn(PlayerTwoName, PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles)
  PlayerOneScore = UpdateScoreWithPenalty(PlayerOneScore, PlayerOneTiles, TileDictionary)
  PlayerTwoScore = UpdateScoreWithPenalty(PlayerTwoScore, PlayerTwoTiles, TileDictionary)
  DisplayWinner(PlayerOneScore, PlayerTwoScore, PlayerOneName, PlayerTwoName)

VB.NET:

    Sub DisplayWinner(ByVal PlayerOneScore As Integer, ByVal PlayerTwoScore As Integer, ByVal PlayerOneName As String, ByVal PlayerTwoName As String)
        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 Then
            Console.WriteLine(PlayerOneName & " wins!")
        ElseIf PlayerTwoScore > PlayerOneScore Then
            Console.WriteLine(PlayerTwoName & " wins!")
        Else
            Console.WriteLine("It is a draw!")
        End If
        Console.WriteLine()
    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)
        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)
        ' CHANGED \/
        Dim PlayerOneName As String
        Dim PlayerTwoName As String
        Console.Write("Player one, enter your name: ")
        PlayerOneName = Console.ReadLine()
        Console.Write("Player two, enter your name: ")
        PlayerTwoName = Console.ReadLine()
        ' CHANGED /\
        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
            ' CHANGED \/
            HaveTurn(PlayerOneName, PlayerOneTiles, PlayerOneTilesPlayed, PlayerOneScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles)
            Console.WriteLine()
            Console.Write("Press Enter to continue")
            Console.ReadLine()
            Console.WriteLine()
            HaveTurn(PlayerTwoName, PlayerTwoTiles, PlayerTwoTilesPlayed, PlayerTwoScore, TileDictionary, TileQueue, AllowedWords, MaxHandSize, NoOfEndOfTurnTiles)
            ' CHANGED /\
        End While
        UpdateScoreWithPenalty(PlayerOneScore, PlayerOneTiles, TileDictionary)
        UpdateScoreWithPenalty(PlayerTwoScore, PlayerTwoTiles, TileDictionary)
        ' CHANGED \/
        DisplayWinner(PlayerOneScore, PlayerTwoScore, PlayerOneName, PlayerTwoName)
    End Sub

Identification of Acronyms and abbreviations, user given option to enter word/acronym/abbreviation - different points awarded for each[edit]

Description of question

C#:


Delphi/Pascal:


Java:


Python:


VB.NET: