Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Certainly! Here is the full translation from Polish to English:
- ---
- ### Guessing Game
- **Lesson Objective:**
- The goal of this lesson is to reinforce knowledge through the practical example of a guessing game.
- ---
- ### Agenda:
- 1. Preliminary questions and concept review.
- 2. Using AI to generate drawings from characters.
- 3. Creating the Guessing Game (Hangman, Gallows).
- 4. Summary.
- ---
- ### Preliminary Questions and Review:
- - What are arrays?
- - How do methods work?
- - What is the difference between the `char` and `string` types?
- ---
- ### Task 1: Conversations with AI (max 20 minutes of class time)
- Encourage artificial intelligence to draw a series of simple ASCII drawings for you. The drawings should represent an animation of a loss in the Hangman game, consisting of 7 frames/stages. It can be a figure on a gallows or a breaking raft, an exploding bomb, a tree or flower losing leaves, or a melting snowman.
- **Hint:** Use popular AI chats like Microsoft Copilot, Google Gemini, or OpenAI’s ChatGPT for this task.
- **Interesting drawing suggestions:**
- - Melting snowman
- - Christmas tree losing needles
- - Flower losing petals
- - Figure on a breaking raft
- **Pre-made set of 7 Hangman drawings for the trainer (and for less advanced students if needed):**
- [Link to Hangman drawings](https://drive.google.com/file/d/1IFNUR2Kvjb6ERPPWDrS0unaipe5drHUh/view?usp=drive_link)
- ---
- ### Task 2: Hangman Project
- Create a Hangman game by expanding the previously prepared template. Your project should include the implementation of the `Main` method below unchanged, and also define the methods used in it to create a playable game mechanic.
- Student link:
- [OnlineGDB link for students](https://onlinegdb.com/JHkCKnb7_)
- ```csharp
- // Main method of the program, executed at startup
- static void Main()
- {
- string[] hangmanDrawings = CreateHangmanDrawings();
- string[] wordArray = CreateWordList();
- string selectedWord = DrawRandomWord(wordArray);
- (string wordToDisplay, int nonLetterCount) = HideWord(selectedWord);
- GuessWord(selectedWord, wordToDisplay, nonLetterCount, hangmanDrawings);
- }
- ```
- ---
- ### Step 1: Declaring Methods
- We begin by creating a project and pasting the implementation of the `Main` method above. We will immediately receive errors indicating that the invoked methods do not exist. We need to analyze and declare them according to the return types and parameters.
- We spend time walking through their usage cases together with the students. They should recognize the types of data to be used. We write one method manually, while for the remaining methods we use the IDE suggestions (`Lightbulb -> Generate Method...`).
- **Using Visual Studio’s help**
- Declare the methods `CreateHangmanDrawings()`, `CreateWordList()`, `DrawRandomWord()`, `HideWord()`, and `GuessWord()`, taking into account the parameters they should accept and return. In their definitions, we add an empty `return` so that the program can compile without errors when executed. Pay attention to the `HideWord()` method, as it can return more than one item thanks to the use of parentheses.
- ```csharp
- // Main method of the program, executed at startup
- static void Main()
- {
- string[] hangmanDrawings = CreateHangmanDrawings();
- string[] wordArray = CreateWordList();
- string selectedWord = DrawRandomWord(wordArray);
- (string wordToDisplay, int nonLetterCount) = HideWord(selectedWord);
- GuessWord(selectedWord, wordToDisplay, nonLetterCount, hangmanDrawings);
- }
- // Method to create an array of words that can be guessed
- static string[] CreateWordList()
- {
- return new string[] {};
- }
- // Method to create hangman drawings for different stages of the game
- static string[] CreateHangmanDrawings()
- {
- return new string[] {};
- }
- // Method to randomly select a word from the list of words
- static string DrawRandomWord(string[] wordArray)
- {
- return "";
- }
- // Method to hide letters in the word using '_' and count non-letter characters
- static (string hiddenWord, int nonLetterCount) HideWord(string selectedWord)
- {
- return ("", 0);
- }
- // Method implementing the main game logic where the user guesses letters of the word
- static void GuessWord(string selectedWord, string wordToDisplay, int nonLetterCount, string[] hangmanDrawings)
- {
- }
- ```
- ---
- ### Step 2: Implementing the Hangman Drawings and Word List
- We test to ensure the program compiles. We won’t see anything in the console just yet.
- We implement the methods `CreateHangmanDrawings()` and `CreateWordList()`. Both are similar since they only return arrays with text defined by us. For the drawings, we paste 7 different stages of the Hangman drawing, generated earlier by AI (each stage as a separate string in the array). Make sure they start from the left edge of the editor. For the words, input any number of your own words that players will guess.
- ```csharp
- // Method creating an array of words that can be guessed
- static string[] CreateWordList()
- {
- return new string[] { "programmer", "camp", "environment", "programming language", "giant" };
- }
- // Method creating hangman drawings for different stages of the game + an initial empty one
- static string[] CreateHangmanDrawings()
- {
- return new string[] {
- "",
- @"
- +---+
- | |
- |
- |
- |
- |
- =========",
- @"
- +---+
- | |
- O |
- |
- |
- |
- =========",
- @"
- +---+
- | |
- O |
- | |
- |
- |
- =========",
- @"
- +---+
- | |
- O |
- /| |
- |
- |
- =========",
- @"
- +---+
- | |
- O |
- /|\ |
- |
- |
- =========",
- @"
- +---+
- | |
- O |
- /|\ |
- / |
- |
- =========",
- @"
- +---+
- | |
- O |
- /|\ |
- / \ |
- |
- ========="
- };
- }
- ```
- ---
- ### Step 3: Drawing the Word to Guess
- We implement the `DrawRandomWord()` method, which returns a randomly selected word from the previously defined list of words.
- ```csharp
- static string DrawRandomWord(string[] wordArray)
- {
- Random randomMachine = new Random();
- int drawnWordIndex = randomMachine.Next(0, wordArray.Length);
- return wordArray[drawnWordIndex];
- }
- ```
- We test with breakpoints to check the drawn words.
- ---
- ### Step 4: Hiding the Word from the Player
- We implement the `HideWord()` method. It should convert the previously drawn word into a string of underscores that will be displayed later in the game. In the case of a word consisting of more than one word, the algorithm should account for spaces. Additionally, for the correct functioning of the core game mechanics, we need to count how many characters in the word are not letters.
- We implement the algorithm in such a way that it loops through each character in the drawn word and appropriately converts or adds it to the counter. Checking if a character is a letter is done using the built-in `IsLetter()` method available for `char` types.
- ```csharp
- // Method to hide letters in the word using '_' and count non-letter characters
- static (string hiddenWord, int nonLetterCount) HideWord(string selectedWord)
- {
- int nonLetterCount = 0; // Counter for non-letter characters (e.g. spaces, commas)
- string wordToDisplay = "";
- for (int i = 0; i < selectedWord.Length; i++)
- {
- char character = selectedWord[i];
- if (char.IsLetter(character)) // Check if the character is a letter and replace it with '_'
- {
- wordToDisplay += '_';
- }
- else
- {
- wordToDisplay += character; // Keep the character unchanged if it's not a letter and increase the counter
- nonLetterCount++;
- }
- }
- return (wordToDisplay, nonLetterCount); // Return the hidden word and number of non-letter characters
- }
- ```
- ---
- ### Step 5: Core Game Mechanics
- We implement the final and most important method, `GuessWord()`. It accepts all the variables we created earlier, so before proceeding, make sure the code works by testing with breakpoints to ensure that no invalid data is passed.
- The gameplay is based on the main game loop, which repeatedly prompts the user for letters. The loop continues until all letters are revealed. If the player runs out of guesses and loses, the method will terminate prematurely with a loss message.
- ```csharp
- // Method implementing the main game logic where the user guesses letters of the word
- static void GuessWord(string selectedWord, string wordToDisplay, int nonLetterCount, string[] hangmanDrawings)
- {
- // Create a counter for user mistakes, a counter for revealed letters, and a storage for used letters
- int mistakeCount = 0;
- int revealedLetterCount = 0;
- string usedLetters = "";
- while (revealedLetterCount < selectedWord.Length - nonLetterCount)
- {
- // At the start of each round, clear the console, display the current state of the word, drawing, and used letters
- Console
- .Clear();
- Console.WriteLine(wordToDisplay);
- Console.WriteLine(hangmanDrawings[mistakeCount]);
- Console.WriteLine($"Used letters: {usedLetters}");
- Console.Write("Enter a letter: ");
- char enteredLetter = Console.ReadLine()[0]; // Get the first character entered by the user
- // -> Here, the game logic will continue
- }
- Console.WriteLine($"Congratulations, you won! The word was '{selectedWord}'");
- Console.ReadLine();
- }
- ```
- After getting the letter from the user, we implement a mechanism to check if the letter has already been used. If it hasn't, we check if it appears in the word. If it has, we notify the player and skip the iteration without consequences.
- ```csharp
- char enteredLetter = Console.ReadLine()[0]; // Read the first character entered by the user
- if (!usedLetters.Contains(enteredLetter)) // Check if the letter hasn't been used yet
- {
- usedLetters += enteredLetter; // Add the letter to the used ones
- if (selectedWord.Contains(enteredLetter) && !wordToDisplay.Contains(enteredLetter)) // Check if the letter is in the word
- {
- // -> Here, the correct letter logic will continue
- }
- else
- {
- // -> Here, the incorrect letter logic will continue
- }
- }
- else
- {
- Console.WriteLine("This letter has already been used. Try again.");
- }
- ```
- We proceed to expand the letter analysis mechanism. If the letter appears in the word, we loop through each character of the word and reveal the guessed positions. If the letter doesn't appear, it means the player made a mistake, and we subtract a life point and draw the next part of the hangman. If the player runs out of guesses, the game should terminate with a loss message.
- ```csharp
- if (selectedWord.Contains(enteredLetter) && !wordToDisplay.Contains(enteredLetter)) // Check if the letter is in the word
- {
- for (int i = 0; i < selectedWord.Length; i++)
- {
- // If the entered letter matches the letter in the selected word
- if (selectedWord[i] == enteredLetter)
- {
- // Replace the corresponding position in the word to display with the guessed letter
- wordToDisplay = wordToDisplay.Remove(i, 1);
- wordToDisplay = wordToDisplay.Insert(i, enteredLetter.ToString());
- revealedLetterCount++; // Increase the revealed letters count
- }
- }
- }
- else
- {
- mistakeCount++; // Increase the mistake count
- if (mistakeCount == hangmanDrawings.Length - 1) // Check if the mistake count has reached the maximum value
- {
- Console.WriteLine(hangmanDrawings[mistakeCount]); // Display the final hangman drawing
- Console.WriteLine($"Unfortunately, you lost! The word was '{selectedWord}'"); // Display loss message
- return;
- }
- }
- ```
- ---
- ### Full `GuessWord` Method:
- ```csharp
- // Method implementing the main game logic where the user guesses letters of the word
- static void GuessWord(string selectedWord, string wordToDisplay, int nonLetterCount, string[] hangmanDrawings)
- {
- // Create a counter for user mistakes, a counter for revealed letters, and a storage for used letters
- int mistakeCount = 0;
- int revealedLetterCount = 0;
- string usedLetters = "";
- while (revealedLetterCount < selectedWord.Length - nonLetterCount) // The loop continues until all letters are revealed
- {
- Console.Clear(); // Clear the console at the start of each round
- Console.WriteLine(wordToDisplay); // Display the current state of the word
- Console.WriteLine(hangmanDrawings[mistakeCount]); // Display the corresponding hangman drawing
- Console.WriteLine($"Used letters: {usedLetters}"); // Display used letters
- Console.Write("Enter a letter: ");
- char enteredLetter = Console.ReadLine()[0]; // Read the first character entered by the user
- if (!usedLetters.Contains(enteredLetter)) // Check if the letter hasn't been used yet
- {
- usedLetters += enteredLetter; // Add the letter to the used ones
- if (selectedWord.Contains(enteredLetter) && !wordToDisplay.Contains(enteredLetter)) // Check if the letter is in the word
- {
- for (int i = 0; i < selectedWord.Length; i++)
- {
- // If the entered letter matches the letter in the selected word
- if (selectedWord[i] == enteredLetter)
- {
- // Replace the corresponding position in the word to display with the guessed letter
- wordToDisplay = wordToDisplay.Remove(i, 1);
- wordToDisplay = wordToDisplay.Insert(i, enteredLetter.ToString());
- revealedLetterCount++; // Increase the revealed letters count
- }
- }
- }
- else
- {
- mistakeCount++; // Increase the mistake count
- if (mistakeCount == hangmanDrawings.Length - 1) // Check if the mistake count has reached the maximum value
- {
- Console.WriteLine(hangmanDrawings[mistakeCount]); // Display the final hangman drawing
- Console.WriteLine($"Unfortunately, you lost! The word was '{selectedWord}'"); // Display loss message
- return;
- }
- }
- }
- else
- {
- Console.WriteLine("This letter has already been used. Try again."); // Display message that the letter has been used
- }
- }
- Console.WriteLine($"Congratulations, you won! The word was '{selectedWord}'"); // Display win message
- Console.ReadLine(); // Wait for user to press a key before closing the program
- }
- ```
- Full program: [Link to full code](https://onlinegdb.com/hD6RTVhZ4)
- ---
- ### Suggestions for Code Refactoring:
- After completing the program, it’s a good idea to talk with the students and ask them where separate methods could be extracted from the code. It’s helpful to suggest which mechanics could be moved to separate modules. Consider which parts of the code are repeated and how extracting them could improve the program's readability.
- **Hint:** The most potential is in the `GuessWord` method. Examples of methods to extract: `wasLetterAlreadyUsed`, `isLetterInWord`, `checkRemainingLives`.
- ---
- ### Possible Extensions:
- - Adding a hint mechanic to reveal one random letter.
- - Adding the option to play again after finishing the game.
- - Displaying a game summary with statistics about guessed letters in a given number of attempts.
- ---
- ### Summary:
- - Can artificial intelligence be helpful in programming?
- - Can a method return more than one variable?
- - How do you check if the letter entered by the user is a character? (Answer: `char.IsLetter`)
- - What built-in methods of the `string` class can be useful for manipulating and analyzing strings? (Answer: `Contains`, `Length`, `Remove`, `Insert`).
- ---
- Let me know if you need any further modifications or clarifications!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement