Button Masher Game in WPF and C#

I’ve been trying to learn WPF with C# as the backend instead of PowerShell. Since there’s a lot more information on using C# over PowerShell, I decided I would take the plunge and learn as much as I could to create some apps.

This is the first app that I completed. In all honesty, it only took me around 2 hours to get the functionality completed. I did this whilst feeling ill and waiting for the wife to get back from work. I was really surprised by how easy it was for me to understand and write in C# and I was quite proud of the final outcome.

The app will probably look really different on your screen but it looks really nice on my computer. This is what the app looks like once it’s loaded:

The goal of the game is for one person to mash the A button as fast as possible and for another person to mash the B button as fast as possible. The first person to mash their respective buttons 100 times is the winner. It then displays a winning screen and allows the users to play again:

Here is a little GIF of what the game looks and feels like:

And here is the download for the game’s exe file:

ButtonMasher

Now for the nitty gritty stuff. I have included the XML and C# code used for the project below and will also include them as downloads:

XML

<Window x:Class="ButtonMasher.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ButtonMasher"
        mc:Ignorable="d"
        Title="Button Masher" Width="450" MinHeight="145" MinWidth="300" KeyDown="WindowKeyDown" SizeToContent="Height" Icon="Icon.ico">
    <Window.Background>
        <LinearGradientBrush StartPoint="-1,-1" EndPoint="1.5,1.5" >
            <GradientStop Color="#FF018A8F" Offset="0.41" />
            <GradientStop Color="#FF00FFD6" Offset="1" />
        </LinearGradientBrush>
    </Window.Background>
    <Grid Name="Grid">
        <Grid.Background>
            <ImageBrush ImageSource="Winner_Background.jpg" Stretch="UniformToFill" Opacity="0" />
        </Grid.Background>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Label Visibility="Visible" Name="PlayerOneLabel" Content="0" FontSize="46" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" FontFamily="Arial"  />
        <Label Visibility="Visible" Name="PlayerTwoLabel" Content="0" FontSize="46" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="1" Foreground="White" FontFamily="Arial"/>
        <ProgressBar Visibility="Visible" Name="ProgressBar1" Margin="10,5" Background="Transparent" BorderBrush="White" BorderThickness="2" Minimum="0" Maximum="100" Value="0" HorizontalAlignment="Stretch" Height="20"  Grid.Row="1" VerticalAlignment="Center" >
            <ProgressBar.Foreground>
                <LinearGradientBrush EndPoint="0,0.5" StartPoint="1,0.5">
                    <GradientStop Color="#83EAF1" Offset="0"/>
                    <GradientStop Color="#63A4FF" Offset="1"/>
                </LinearGradientBrush>
            </ProgressBar.Foreground>
        </ProgressBar>
        <ProgressBar Visibility="Visible" Name="ProgressBar2" Margin="10,5" Background="Transparent" BorderBrush="White" BorderThickness="2" Minimum="0" Maximum="100" Value="0" HorizontalAlignment="Stretch" Height="20" Grid.Row="1" Grid.Column="1" VerticalAlignment="Center" RenderTransformOrigin="0.5,0.5"  >
            <ProgressBar.Foreground>
                <LinearGradientBrush EndPoint="0,0.5" StartPoint="1,0.5">
                    <GradientStop Color="#83EAF1" Offset="0"/>
                    <GradientStop Color="#63A4FF" Offset="1"/>
                </LinearGradientBrush>
            </ProgressBar.Foreground>
            <ProgressBar.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="180"/>
                    <TranslateTransform/>
                </TransformGroup>
            </ProgressBar.RenderTransform>
        </ProgressBar>
        <TextBlock Name="RulesTextBlock" MouseUp="ToggleRules" Visibility="Visible" Grid.Row="2" VerticalAlignment="Bottom" HorizontalAlignment="Left" FontFamily="Arial" Foreground="White" FontSize="10" Cursor="Hand" >
            See Rules
        </TextBlock>
        <TextBlock Name="WonLabel" Text="Winner" Padding="0,40,0,0" Visibility="Collapsed" Grid.ColumnSpan="2" FontSize="46" HorizontalAlignment="Center" VerticalAlignment="Bottom" FontWeight="Bold" TextDecorations="{x:Null}" Foreground="#FFFECE26" FontFamily="Arial">
            <TextBlock.Effect>
                <DropShadowEffect BlurRadius="1" Direction="320" ShadowDepth="2"/>
            </TextBlock.Effect>
        </TextBlock>
        <Border Name="PlayAgainBorder" Visibility="Collapsed" Grid.Row="1" Cursor="Hand" Grid.ColumnSpan="2" CornerRadius="10" Margin="0,0,0,10" HorizontalAlignment="Center" VerticalAlignment="Center" MouseUp="PlayAgain">
            <Border.Style>
                <Style>
                    <Setter Property="Border.Background" Value="#FF494949" />
                    <Setter Property="Border.BorderThickness" Value="3"/>
                    <Style.Triggers>
                        <Trigger Property="Border.IsMouseOver" Value="True" >
                            <Setter Property="Border.Background" Value="#2ecc71"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Border.Style>
            <Label Content="Play Again" VerticalAlignment="Center" Foreground="White" HorizontalAlignment="Center" VerticalContentAlignment="Center" FontSize="16" FontFamily="Arial"/>
        </Border>
        <TextBlock Name="RulesSection" Foreground="White" Grid.Row="3" Grid.ColumnSpan="2" TextWrapping="Wrap" TextAlignment="Center" Padding="20" Visibility="Collapsed" FontFamily="Arial" FontSize="14">
            The rules are simple, player one (left side) has to mash the 'A' button as fast as possible while player two (right side) has to mash the 'B' button as fast as possible. The first one to reach 100 button "mashes" wins the game!
        </TextBlock>
    </Grid>
</Window>

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ButtonMasher
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //player one score
        int player1Score = 0;
        int player2Score = 0;

        //LOAD FORM
        public MainWindow()
        {
            InitializeComponent();
        }

        //UPDATE PLAYER ONE SCORE
        void UpdatePlayerOneScore()
        {
            player1Score++;
            PlayerOneLabel.Content = player1Score;
        }

        //UPDATE PLAYER TWO SCORE
        void UpdatePlayerTwoScore()
        {
            player2Score++;
            PlayerTwoLabel.Content = player2Score;
        }

        //SET WON SCREEN VISIBILITY
        void WonScreenVisibility(bool visible)
        {
            if (visible)
            {
                //show won screen
                PlayerOneLabel.Visibility = Visibility.Collapsed;
                PlayerTwoLabel.Visibility = Visibility.Collapsed;
                ProgressBar1.Visibility = Visibility.Collapsed;
                ProgressBar2.Visibility = Visibility.Collapsed;
                RulesTextBlock.Visibility = Visibility.Collapsed;
                RulesSection.Visibility = Visibility.Collapsed;
                WonLabel.Visibility = Visibility.Visible;
                PlayAgainBorder.Visibility = Visibility.Visible;
                Grid.Background.Opacity = 100;
                MinWidth = 350;
                MinHeight = 170;
            }
            else
            {
                //hide won screen
                PlayerOneLabel.Visibility = Visibility.Visible;
                PlayerTwoLabel.Visibility = Visibility.Visible;
                ProgressBar1.Visibility = Visibility.Visible;
                ProgressBar2.Visibility = Visibility.Visible;
                RulesTextBlock.Visibility = Visibility.Visible;
                RulesSection.Visibility = Visibility.Collapsed;
                WonLabel.Visibility = Visibility.Collapsed;
                PlayAgainBorder.Visibility = Visibility.Collapsed;
                Grid.Background.Opacity = 0;
                MinWidth = 300;
                MinHeight = 145;
            }
            //switch "show" or "hide" in rules textblock
            if (RulesSection.Visibility == Visibility.Visible)
            {
                RulesTextBlock.Text = "Hide Rules";
            }
            else
            {
                RulesTextBlock.Text = "Show Rules";
            }
        }

        //WON SCREEN
        void WonScreen(string player)
        {
            if(player == "1")
            {
                WonScreenVisibility(true);
                WonLabel.Text = "Player 1 won!";
            }else if(player == "2")
            {
                WonScreenVisibility(true);
                WonLabel.Text = "Player 2 won!";
            }
        }

        //RESET SCORES AND BARS
        void Reset()
        {
            player1Score = 0;
            player2Score = 0;
            PlayerOneLabel.Content = player1Score;
            PlayerTwoLabel.Content = player2Score;
            ProgressBar1.Value = player1Score;
            ProgressBar2.Value = player2Score;
        }

        //USER PRESSES BUTTON FORM
        private void WindowKeyDown(object sender, KeyEventArgs e)
        {
            //checking which key was pressed
            if (e.Key == Key.A)
            {
                UpdatePlayerOneScore(); 
            }else if(e.Key == Key.L)
            {
                UpdatePlayerTwoScore();
            }

            //calculating progress bar value
            ProgressBar1.Value = player1Score;
            ProgressBar2.Value = player2Score;

            //checking if anyone won
            if (ProgressBar1.Value > 99)
            {
                //player one has won
                WonScreen("1");

            }
            else if (ProgressBar2.Value > 99)
            {
                //player two has won
                WonScreen("2");
            }            
        }        

        //PLAY AGAIN
        private void PlayAgain(object sender, RoutedEventArgs e)
        {
            WonScreenVisibility(false);
            Reset();
        }

        //TOGGLE RULES
        void ToggleRules(object sender, RoutedEventArgs e)
        {
            if (RulesSection.Visibility == Visibility.Collapsed)
            {
                //show rules
                RulesSection.Visibility = Visibility.Visible;
                RulesTextBlock.Text = "Hide Rules";
                SizeToContent = SizeToContent.Height;
                MinHeight = 265;
            }
            else
            {
                //hide rules
                RulesSection.Visibility = Visibility.Collapsed;
                RulesTextBlock.Text = "Show Rules";
                SizeToContent = SizeToContent.Height;
                MinHeight = 145;
            }
        }
    }
}

I really hope you enjoy this little game that I created. Please feel free to use it, change it and distribute your own version at will 🙂

Enjoy!

FizzBuzz in C++

Something really out of my comfort zone here. I completed the C++ course on codecademy and did what I normally do when I’m learning a new programming language. I try to make the FizzBuzz game in as many different ways as I can to get used to the syntax and different operations.

This is was the first attempt at it and I think the easiest to do. It’s not clean but I like learning and you need to make mistakes in order to really learn something:

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 101; i++){
        if (i % 5 == 0 & i % 3 == 0){
            std::cout << "FizzBuzz\n";
        }else if (i % 5 == 0){
            std::cout << "Fizz\n";
        }else if (i % 3 == 0){
            std::cout << "Buzz\n";
        }else{
            std::cout << i << "\n";
        }
    }
}

My second iteration was a little more sophisticated and would make any alterations to the rules of FizzBuzz easier to account for:

#include <iostream>
#include <string>
using namespace std;

int main() {
    for (int i = 0; i < 101; i++){
        string output;
        output = "";
        
        if ( i % 5 == 0 ){ output += "Fizz"; }
        if ( i % 3 == 0 ){ output += "Buzz"; }
        if ( output == "" ){ output = to_string(i); }
        cout << output << "\n";
    }
}

No doubt that I will be jumping back to create new ways when I have the time. Let me know what you come up with.

Enjoy!

Blackjack in PowerShell

This is a little function that mimics a simplified version of blackjack. I have wrapped it in a function for cleanliness and so that it can be called again.

The rules are below:

  • Get a higher total than the dealer
  • Keep your total under 21 or you will be bust
  • That’s it

Here is the code for you to try this out yourself, hope you enjoy!

function blackjack{

    #CHANGING NAME OF WINDOW
    $pshost = Get-Host
    $pswindow = $pshost.UI.RawUI
    $pswindow.WindowTitle = "Blackjack" 

    #RESETTING GAME OVER VARIABLE
    $blackjack_game_over = $false

    #GENERATING A RANDOM TOTAL FOR THE DEALER
    $blackjack_dealer_total = Get-Random -Minimum 14 -Maximum 22

    #CREATING AN ARRAY FOR THE USERS CARD NUMBERS
    $blackjack_user_card_array = [System.Collections.ArrayList]::new("")

    #GENERATING A RANDOM NUMBER FOR THE USERS FIRST CARD
    $blackjack_user_first_card = Get-Random -Minimum 1 -Maximum 11

    #ADDING USERS FIRST CARD TO ARRAY
    $blackjack_user_card_array.Add($blackjack_user_first_card)

    #CREATING A VARIABLE TO COUNT USERS TOTAL
    $blackjack_user_total = $blackjack_user_first_card

    Clear-Host

    Write-Host "Your first card is $blackjack_user_first_card"

    #DO THIS (PLAY GAME) UNTIL THE GAMEOVER VARIABLE IS TRUE
    do {
        #GET USER INPUT
        do {$blackjack_input = Read-Host "Take another card? (Y or N)"}while (("y","n") -notcontains $blackjack_input)

        #IF USER INPUT IS VALID AND ISN'T BUST AND WANTS ANOTHER CARD
        if ($blackjack_input -eq "y" -and $blackjack_user_total -le 21){

            #GENERATE A NEW CARD FOR THE USER
            $blackjack_user_new_card = Get-Random -Minimum 1 -Maximum 11

            #ADD NEW CARD TO CARD ARRAY
            $blackjack_user_card_array.Add($blackjack_user_new_card)

            #ADD NEW CARD TO CARD TOTAL
            $blackjack_user_total = $blackjack_user_total + $blackjack_user_new_card

            Clear-Host

            Write-Host "You have $blackjack_user_card_array"

            #IF THE USER IS BUST
            if ($blackjack_user_total -gt 21){
                Write-Host "You went bust! The dealer won with " -ForegroundColor Red -NoNewline
                Write-Host $blackjack_dealer_total 
                $blackjack_game_over = $true
            }
            
        #IF THE USER DOESNT WANT ANOTHER CARD
        }else{

            Clear-Host
            
            #OUTPUTTING THE FINAL SCORE
            #Write-Host "You had $blackjack_user_total and the dealer had $blackjack_dealer_total"

            #SWITCH TO SEE WHO WON
            switch ($blackjack_user_total){
                {$_ -gt 21}{Write-Host "You went bust! The dealer won with " -ForegroundColor Red -NoNewline; Write-Host $blackjack_dealer_total; $blackjack_game_over = $true; break}
                {$_ -eq $blackjack_dealer_total}{Write-Host "It's a draw, the dealer also had $blackjack_dealer_total"; $blackjack_game_over = $true; break}
                {$_ -gt $blackjack_dealer_total}{Write-Host "You win! The dealer only had " -ForegroundColor Green -NoNewline; Write-Host $blackjack_dealer_total; $blackjack_game_over = $true; break}
                {$_ -lt $blackjack_dealer_total}{Write-Host "You lose! The dealer won with " -ForegroundColor Red -NoNewline; Write-Host $blackjack_dealer_total; $blackjack_game_over = $true; break}
                default {Write-Host "Something happeneds that wasn't accounted for!" -ForegroundColor Red; break}
            }
        }
    }until ($blackjack_game_over)

    #ASK USER IF THEY WANT TO REPLAY UNTIL INPUT IS A Y OR N
    do {$blackjack_play_again = Read-Host "Do you want to play again? Y or N"} while (("y","n") -notcontains $blackjack_play_again)

    #SWITCH TO EITHER PLAY AGAIN OR GO TO MAIN MENU
    switch ($blackjack_play_again){
        "y" {blackjack}
        "n" {exit}
        default {exit}
    }   
}

 

Rock, Paper, Scissors In PowerShell

Another game today, I’ll be adding this to my big Games Project soon. Just need to implement it into the script.

First I started off by making the PowerShell window the correct size. I did this by adding:

$pshost = get-host
$pswindow = $pshost.ui.rawui
$newsize = $pswindow.buffersize
$newsize.height = 500
$newsize.width = 500
$pswindow.buffersize = $newsize
$newsize = $pswindow.windowsize
$newsize.height = 22
$newsize.width = 85
$pswindow.windowsize = $newsize
$pswindow.WindowTitle = "Rock, Paper, Scissors"

to the start of the function.

Next I created the meat of the game, here its just a simple do statement until either the score of the user or the score of the computer has reached or exceeded 3. Best of three sort of thing. Heres that part:

do {
 $options = @("Rock","Paper","Scissors")
 $option = $options | Get-Random -Count 1
 Clear-Host
 Write-Host "Your Score - $score" -ForegroundColor Green
 Write-Host "Computer's Score - $computerscore" -ForegroundColor Red
 do {$selection = Read-Host "Selection"}while (("Rock","Paper","Scissors") -notcontains $selection)
  if ($selection -eq "rock" -and $option -eq "paper"){
   Write-Host "You lose, the computer chose $option";
   Start-Sleep -Seconds 1
   $computerscore = $computerscore + 1
  }elseif($selection -eq "paper" -and $option -eq "scissors"){
   Write-Host "You lose, the computer chose $option"
   Start-Sleep -Seconds 1
   $computerscore = $computerscore + 1
  }elseif($selection -eq "scissors" -and $option -eq "rock"){
   write-host "You lose, the computer chose $option"
   Start-Sleep -Seconds 1
   $computerscore = $computerscore + 1
  }elseif ($selection -eq $option){
   Write-Host "Its a draw"
   Start-Sleep -Seconds 1
  }else{
   Write-Host "You won, the computer chose $option"
   Start-Sleep -Seconds 1
   $score = $score + 1
  }
 }until (($score -eq 3) -or ($computerscore -eq 3))
 if ($computerscore -gt $score){
  Clear-Host
  Write-Host "You lost, the computer scored $computerscore points whilst you only scored $score points" -ForegroundColor Red
 }else{
  Clear-Host
  Write-Host "You won, you got $score points. More than the computer's $computerscore" -ForegroundColor Green
 }
}

Finally, I ended the code of by showing the user who won and giving then the option to exit the game or play again. Here is the code for that:

do {$playagain = Read-Host "Do you want to play again? Y or N"} while (("Y","N") -notcontains $playagain)
if ($playagain -eq "y"){
 RPS
}elseif ($playagain -eq "n"){
 exit
}

===================================================================================================

Hopefully you can see how this all comes together. Here is the entire script for the game:

function RPS{
 $pshost = get-host
 $pswindow = $pshost.ui.rawui
 $newsize = $pswindow.buffersize
 $newsize.height = 500
 $newsize.width = 500
 $pswindow.buffersize = $newsize
 $newsize = $pswindow.windowsize
 $newsize.height = 22
 $newsize.width = 85
 $pswindow.windowsize = $newsize
 $pswindow.WindowTitle = "Rock, Paper, Scissors"

 [int]$score = 0
 [int]$computerscore = 0

 do {
  $options = @("Rock","Paper","Scissors")
  $option = $options | Get-Random -Count 1
  Clear-Host
  Write-Host "Your Score - $score" -ForegroundColor Green
  Write-Host "Computer's Score - $computerscore" -ForegroundColor Red
  do {$selection = Read-Host "Selection"}while (("Rock","Paper","Scissors") -notcontains $selection)
  if ($selection -eq "rock" -and $option -eq "paper"){
   Write-Host "You lose, the computer chose $option";
   Start-Sleep -Seconds 1
   $computerscore = $computerscore + 1
  }elseif($selection -eq "paper" -and $option -eq "scissors"){
   Write-Host "You lose, the computer chose $option"
   Start-Sleep -Seconds 1
   $computerscore = $computerscore + 1
  }elseif($selection -eq "scissors" -and $option -eq "rock"){
   write-host "You lose, the computer chose $option"
   Start-Sleep -Seconds 1
   $computerscore = $computerscore + 1
  }elseif ($selection -eq $option){
   Write-Host "Its a draw"
   Start-Sleep -Seconds 1
  }else{
   Write-Host "You won, the computer chose $option"
   Start-Sleep -Seconds 1
   $score = $score + 1
  }
 }until (($score -eq 3) -or ($computerscore -eq 3)) 
 if ($computerscore -gt $score){
  Clear-Host
  Write-Host "You lost, the computer scored $computerscore points whilst you only scored $score points" -ForegroundColor Red
 }else{
  Clear-Host
  Write-Host "You won, you got $score points. More than the computer's $computerscore" -ForegroundColor Green
 }

 do {$playagain = Read-Host "Do you want to play again? Y or N"} while (("Y","N") -notcontains $playagain)
 if ($playagain -eq "y"){
  RPS
 }elseif ($playagain -eq "n"){
  exit
 }
}

I was quite surprised at how short I got the script to be, I think I may try to make the Blackjake game shorter as, lets me honest. Its barbaric in its construction.

Games In PowerShell – Version 4

Quite a large update to my Games in PowerShell project, adding a new game, changing some of the styling of the game and changing the loading screen of the game.

You’ll be pleased and proud to know that the games code is now over a thousand lines long…At least fake being proud then.

As mentioned earlier, I have added a new game. This one is different from my other games because it is a text based adventure game about a dino that needs capturing. The player only successfully completes the game once they have captured the dino and also not been killed by it. Tall order, I know.

I also changed how the Quick Fire Character Counting game works. It now starts by giving the player a full second to see the word and guess how many characters it contains, then, each time the user gets a correct answer reduces the viewing time of the word by 30 miliseconds. That way the game gradually gets more difficult instead of being stuck at the same length, which is boring.

Here is the link to my code for the game

I will be updating my project page with this update as well. Enjoy!

Verb Guessing Game in PowerShell

Verb guesser Featured image

Another game today. In PowerShell of all things. Who would have thought?

Anyway, in this blog post I will be showing you the code I used to create a random word guessing in PowerShell. The script works by taking all the verb information from the

Get-Verb

command and selecting only the verb part of each one.

The script then selects on at random, does some formatting and removes the vowels. That part is important. Pretty much is the single defining feature that makes this thing a game. With the vowels now removed, the user has to guess the verb. If they get it correct then a point is added to their score. If they get it wrong then the game resets and they start again from 0 points. (Well, 1 point if you’re being technical)

Here the code:

function verbguessinggame{
 $getverbs = Get-Verb | select verb
 [int]$verbamount = $getverbs.count
 $score = 0
 do{
  $random = Get-Random -Minimum 0 -Maximum $verbamount
  $selectedword = $getverbs[$random] -replace "@{verb=","" -replace "}",""
  $selectedwordlength = $selectedword.length
  $vowelsremoved = $selectedword -replace '[aeiou]',""

  $score = $score + 1
  Clear-Host
  Write-Host $vowelsremoved -ForegroundColor Red -BackgroundColor Black
  $guess = Read-Host "What is the word?"
 }until($guess -ne $selectedword)
 Clear-Host
 Write-Host "incorrect, the verb was $selectedword"
 Write-Host "Your score was $score"
 Start-Sleep -Seconds 1.5
 Clear-Host

 do {$playagainselection = Read-Host "Do you want to play again? (Y or N)"} while (("y","n") -notcontains $playagainselection)
 if ($playagainselection -eq "y"){
  verbguessinggame
 }elseif ($playagainselection -eq "n"){
  exit
 }
}

verbguessinggame

I will be updating my Games in PowerShell project with this game as well as making some custom changes to this game and others in the project.

Quick Fire Character Counting Game In PowerShell

Another pointless activity in PowerShell. The premis of this game is that you have a short amount of time to look at a word, you then have to guess how many letters are in the word.

If you get the number correct, the game continues and your score increases. If you input and incorrect number, then the game ends, shows your score and exits.

As always I have added this to my “Games In PowerShell” project. Below is the code for the game:

function quickfirecounting{
 $getverbs = Get-Verb | select verb
 [int]$verbamount = $getverbs.count
 $scoreforquickfire = 0
 do{
  $random = Get-Random -Minimum 0 -Maximum $verbamount
  $selectedword = $getverbs[$random] -replace "@{verb=","" -replace "}",""
  $selectedwordlength = $selectedword.Length

  $scoreforquickfire = $scoreforquickfire + 1
  Clear-Host
  Write-Host "$selectedword"
  Start-Sleep -Milliseconds 550
  Clear-Host
  $guess = Read-Host "how many letters are in the word?"
 }until ($guess -ne $selectedwordlength)
 Clear-Host
 Write-Host "Incorrect! There were $selectedwordlength letters"
 Start-Sleep -Seconds 1
 Clear-Host
 Write-Host "Your score was $scoreforquickfire"
 Start-Sleep -Seconds 1
 Clear-Host

 do {$playagainselection = Read-Host "do you want to play again? (Y or N)"} while (("y","n") -notcontains $playagainselection)
 if ($playagainselection -eq "y"){
  ####GO TO GAME FUNCTION TO PLAY AGAIN####
 }elseif ($playagainselection -eq "n"){
  ####GO TO THE MAIN MENU####
 }
}

As you can probably see, I am using the verb section of PowerShell to get the random words. This is better and easier than inputting my own words individually.

Enjoy!

More Games In PowerShell

This is, yet again, another improvement to a script I created earlier, you can find this here.

What I have done is added some new games (3 to be exact) and also created some unnecessary “fancy” bits such as a loading screen and a “Goodbye” exiting message. I have also changed the menu to be a single “echo” command instead of the multiple “write-host” which makes the code look cleaner.

The three games I have added are pretty much all the same game. I was getting sick of guessing games and since making actual games in PowerShell is VERY complex. I decided to make a math game. Specifically one that give the user a math question and the user has to work out the correct answer. An example would be “4 * ? = 12”. Where the user would have to work out “?”.

I made three difficulties of this, easy (1-10), medium (1-20) and hard (1-50). This means that the answers in the easy section are from 1 to 10, the answers in the medium are from 1 to 20 and so on…

I also added a function to change the size of the window to something more appropriate and changed the window title to something more…fun.

Anyway, below is the code for this. Unfortunately, I didn’t break the “300 lines of code” achievement I had set for myself:

function changescreensizeforgames{
 $pshost = get-host
 $pswindow = $pshost.ui.rawui
 $newsize = $pswindow.buffersize
 $newsize.height = 500
 $newsize.width = 500
 $pswindow.buffersize = $newsize
 $newsize = $pswindow.windowsize
 $newsize.height = 15
 $newsize.width = 51
 $pswindow.windowsize = $newsize
 $pswindow.WindowTitle = "Games Galore!"
}
changescreensizeforgames

function fakeloadingbar{
 cls
 echo "-....."
 Start-Sleep -Milliseconds 150
 cls
 echo ".-...."
 Start-Sleep -Milliseconds 150
 cls
 echo "..-..."
 Start-Sleep -Milliseconds 150
 cls
 echo "...-.."
 Start-Sleep -Milliseconds 150
 cls
 echo "....-."
 Start-Sleep -Milliseconds 150
 cls
 echo ".....-"
 Start-Sleep -Milliseconds 150
 cls
 echo "....-."
 Start-Sleep -Milliseconds 150
 cls
 echo "...-.."
 Start-Sleep -Milliseconds 150
 cls
 echo "..-..."
 Start-Sleep -Milliseconds 150
 cls
 echo ".-...."
 Start-Sleep -Milliseconds 150
 cls
 echo "-....."
 Start-Sleep -Milliseconds 150
 cls
}
fakeloadingbar

function exitscreenforgames{
 cls
 echo @"
####   #    # #####  ##
#   #   #  #  #      ##
#####    ##   ####   ##
#    #   ##   #      ##
#    #   ##   #
#####    ##   #####  ##
"@
 Start-Sleep -Seconds 1
 exit
}

#Window size change

#INTRO (Start Menu)
function menu2{

function Show-Menu{
 param (
 [string]$Title = 'My Menu'
 )
 Clear-Host
 write-host @"
================ $Title ================

Guessing Games------------
1: Press '1' to play 1-10 with 1 guess
2: Press '2' for 1-100 with unlimited guesses

Multiplication Games------
3: Press '3' for easy mulitplication game (1-10)
4: Press '4' for medium multiplication game (1-20)
5: Press '5' for hard multiplication game (1-50)

Q: Press 'Q' to quit.
"@
 }

 Show-Menu -Title 'Select an option'
 $selection = read-host "please make a selection"

 if ($selection -eq "1"){
  write-host "You chose option one" (1to10guessgame)
 }elseif ($selection -eq "2"){
 Write-Host "you chose option two" (1to100guessgame)
 }elseif ($selection -eq "3"){
  write-host "You chose option three" (easymathgame)
 }elseif ($selection -eq "4"){
  write-host "You chose option four" (mediummathgame)
 }elseif ($selection -eq "5"){
  write-host "You chose option four" (hardmathgame)
 }elseif ($selection -eq "q"){
  clear-host
 Do {$areyousuremessage = Read-Host "Are you sure you want to quit? Y or N?"} while (("y","n") -notcontains $areyousuremessage)
  switch ($areyousuremessage){

   "y" {exitscreenforgames}
   "n" {menu2}

  }

 }else {
  (menu2)
 }
}

#Single guess game
function 1to10guessgame{

 clear-host
 Write-Host "You only have one guess!"
 Start-Sleep -Seconds 1
 Write-Host "Are you ready?"
 start-sleep -Seconds 1

 $random =  Get-Random -Minimum 1 -Maximum 11

 do {
  try {
   $numOk = $true
   [int]$input1 = Read-host "Make a guess between 1 and 10"
  }catch {$numOK = $false}
 }until (($input1 -ge 1 -and $input1 -lt 11) -and $numOK)

 if ($input1 -eq $random){
  Write-Host "You got it right!"
 }else{
  Write-Host "You got it wrong! the number was $random"
 }

 Start-Sleep -Seconds 2

 do {$playagain1 = Read-Host "Do you want to play again? Y or N"} while (("y","n") -notcontains $playagain1)

 if ($playagain1 -eq "y"){
  (1to10guessgame)
 }elseif ($playagain1 -eq "n"){
  (menu2)
 }

}

#1-100 Guess game
function 1to100guessgame{

 clear-host

 [int]$random100 = Get-Random -Minimum 1 -Maximum 101

 Write-Host "Try and guess my number between 1 and 100"

 while ($input100 -ne $random100){
  Write-Host "enter your guess below"
  $input100 = [int] (Read-Host)

  $option1 = if ($input100 -gt $random100) {Write-Host "$input100 was too high"}
  $option2 = if ($input100 -lt $random100) {Write-Host "$input100 was too low"}
  $option3 = if ($input100 -gt [int](100) -or $input -lt [int](0)) {Write-Host 'between 1 and 100!'}

 } Write-Host "Correct! the number was $input100"

 do {$playagain1 = Read-Host "Do you want to play again? Y or N"} while (("y","n") -notcontains $playagain1)

 if ($playagain1 -eq "y"){
  (1to100guessgame)
 }elseif ($playagain1 -eq "n"){
  (menu2)
 }
}

#easy math game 1-10
function easymathgame{
 $easynewnumber1 = get-random -minimum 1 -maximum 11
 $easynewnumber2 = Get-Random -Minimum 1 -Maximum 11

 $easynumbermultiplied = $easynewnumber1 * $easynewnumber2
 Clear-Host
 Write-Host "Here is your question, can you work out '?'"
 write-host "$easynewnumber2 * ? = $easynumbermultiplied"

 do{
  try{
   $numOk = $true
   [int]$easynewnumberinput = Read-Host "Enter your answer here..."
  }catch {$numOk = $false}
 }until (($easynewnumberinput -ge 1 -and $easynewnumberinput -lt 11) -and $numOk)

 if ($easynewnumberinput -eq $easynewnumber1){
  Write-Host "You got it right!"
 }elseif ($easynewnumberinput -ne $easynewnumber1){
  Write-Host "You got it wrong, the answer was $easynewnumber1"
 } Start-Sleep -Seconds 1

 do {$playagain1 = Read-Host "Do you want to play again? Y or N"} while (("y","n") -notcontains $playagain1)

 if ($playagain1 -eq "y"){
  easymathgame
 }elseif ($playagain1 -eq "n"){
  (menu2)
 }
}

#medium math game 1-20
function mediummathgame{ 
 $mediumnewnumber1 = get-random -minimum 1 -maximum 20
 $mediumnewnumber2 = Get-Random -Minimum 1 -Maximum 20

 $mediumnumbermultiplied = $mediumnewnumber1 * $mediumnewnumber2
 Clear-Host
 Write-Host "Here is your question, can you work out '?'"
 write-host "$mediumnewnumber2 * ? = $mediumnumbermultiplied"

 do{
  try{
   $numOk = $true
   [int]$mediumnewnumberinput = Read-Host "Enter your answer here..."
  }catch {$numOk = $false}
 }until (($mediumnewnumberinput -ge 1 -and $mediumnewnumberinput -lt 20) -and $numOk)

 if ($mediumnewnumberinput -eq $mediumnewnumber1){
  Write-Host "You got it right!"
 }elseif ($mediumnewnumberinput -ne $mediumnewnumber1){
  Write-Host "You got it wrong, the answer was $mediumnewnumber1"
 } Start-Sleep -Seconds 1
 do {$playagain1 = Read-Host "Do you want to play again? Y or N"} while (("y","n") -notcontains $playagain1)

 if ($playagain1 -eq "y"){
  mediummathgame
 }elseif ($playagain1 -eq "n"){
  (menu2)
 }
}

#Difficult math game 1-50
function hardmathgame{
 $hardnewnumber1 = get-random -minimum 1 -maximum 50
 $hardnewnumber2 = Get-Random -Minimum 1 -Maximum 50

 $hardnumbermultiplied = $hardnewnumber1 * $hardnewnumber2
 Clear-Host
 Write-Host "Here is your question, can you work out '?'"
 write-host "$hardnewnumber2 * ? = $hardnumbermultiplied"

 do{
  try{
   $numOk = $true
   [int]$hardnewnumberinput = Read-Host "Enter your answer here..."
  }catch {$numOk = $false}
 }until (($hardnewnumberinput -ge 1 -and $hardnewnumberinput -lt 51) -and $numOk)

 if ($hardnewnumberinput -eq $hardnewnumber1){
  Write-Host "You got it right!"
 }elseif ($hardnewnumberinput -ne $hardnewnumber1){
  Write-Host "You got it wrong, the answer was $hardnewnumber1"
 } Start-Sleep -Seconds 1
 do {$playagain1 = Read-Host "Do you want to play again? Y or N"} while (("y","n") -notcontains $playagain1)

 if ($playagain1 -eq "y"){
  hardmathgame
 }elseif ($playagain1 -eq "n"){
  (menu2)
 } 
}
menu2

Hopefully you’re as happy with this code as I am, if you have any improvements please let me know 🙂

Enjoy!

Number Guessing Games in PowerShell

CLICK HERE TO SEE THESE GAMES AND A MENU IN A SINGLE FILE.

This guide will show you how to make a two types of number guessing games in the coding language of PowerShell.

——————–1-10 With A Single Guess———————

Below is my code for a 1 to 10 guessing game in which the player has a single try to guess the number correctly:

function single-guess{

 clear
 Write-Host "You only have one guess!"
 Start-Sleep -Seconds 1
 Write-Host "Are you ready?"
 start-sleep -Seconds 1

 $random1to10 =  Get-Random -Minimum 1 -Maximum 11

 do {
  try {
   $numOk = $true
   [int]$input1 = Read-host "Make a guess between 1 and 10"
   }catch {$numOK = $false}
 }until (($input1 -ge 1 -and $input1 -lt 11) -and $numOK)

 if ($input1 -eq $random1to10){
  Write-Host "You got it right!"
 }elseif ($input1 -ne $random1to10){
  Write-Host "You got it wrong! the number was $random1to10"

 Start-Sleep -Seconds 2
 }
}

From this you can see that I start with a little intro of “Are you ready?” and other various starting lines. I then create a random number between 1 and 11 (Actually between 1 and 10 as the -maximum in this case signifies the highest amount the number cannot be), and then put that into  a variable. I then ask the user for a number (guess) between 1 and 10 and then use an if statement to test whether the guess was the same as the randomly generated number.

Now that you have the basic 1 to 10 game, we will move onto a 1 to 100 guess game with unlimited guesses.

——————1-100 With Unlimited Guesses——————

This code is a bit different since the user can have unlimited guesses. You can see how I made this possible in the code below:

function 1to100guessgame{

 clear

 [int]$random100 = Get-Random -Minimum 1 -Maximum 101

 Write-Host "Try and guess my number between 1 and 100"

 while ($input100 -ne $random100){
  Write-Host "enter your guess below"
  $input100 = [int] (Read-Host)

  $option1 = if ($input100 -gt $random100) {Write-Host "$input100 was too high"}
  $option2 = if ($input100 -lt $random100) {Write-Host "$input100 was too low"}
  $option3 = if ($input100 -gt [int](100) -or $input -lt [int](0)) {Write-Host 'between 1 and 100!'}

 } Write-Host "Correct! the number was $input100"
}

In this code I still created a random number and put it into a variable. But I used a “while” statement instead of an “if” statement, meaning that it loops until the user has guessed the correct number. I still haven’t figured out how to make sure that the user inputted date is an actual number, which if it’s not then it will output an error.

The 1 to 100 guessing game also informs the user whether the number they entered is too high or too low, this helps the user guess the number quicker.

——————————–CONCLUSION——————————–

These games a fun and all but they aren’t very well accessible or re-run-able (if that’s even a word). So I think I will create a menu for these and any future games I make so that they can all be played in one place and in one file. Till then!

Remember! If you want to be able to run scripts then you need to change you execution policy. You can see how to do that here!