Initial Commit

This commit is contained in:
kougyokugentou 2022-03-15 21:16:45 -07:00
parent 14960a7fc6
commit 666687a47f
38 changed files with 5189 additions and 3 deletions

6
.gitignore vendored
View File

@ -1,6 +1,6 @@
*/bin/*
*/obj/*
*/.vs/*
*\bin\*
*\obj\*
*\.vs\*
Cs*Apps/*/bin/*
Cs*Apps/*/obj/*
Cs*Apps/*/.vs/*

View File

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{204522AA-27C2-49AC-BA28-BE82547473C9}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Airline</RootNamespace>
<AssemblyName>Airline</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

254
Cs3Apps/Airline/Program.cs Normal file
View File

@ -0,0 +1,254 @@
/* Shaun Marquardt
* TINFO 200
* CS3: Airline
* ****************************************************
* Change History
* Date Developer Description
* 2020-02-18 marqusa File creation and initial implementation.
* I decided to split PurchaseFirstClassTicket
* and PurchaseEconomyTicket into two seperate functions to make it easier to call
* if one class of ticket was full and it was acceptable to buy the other seats.
* Created a SeatsRemaining function to inform the
* user if the flight's all booked up and check seats remaining in a given class
* if one type is full.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airline
{
class Program
{
//Make the seating chart a more globally available variable.
//REQ 1: Use a one-dimensional array of type bool
//to represent the 10 seats of the plane
static bool[] seatingChart = new bool[10];
/* This is a program for a small airline to manage its new
* reservation system. This program assigns seats on each
* flight of the airline's only plane (capacity: 10 seats).
* The user will be presented with a menu to choose
* first class (seats 1-5) or economy (seats 6-10).
*
* Requirements:
* 1) Use a one-dimensional array of type bool to represent
* the seating chart of the plane, initialized to false to
* indicate all seats are empty.
* 2) As each seat is assigned, set the corresponding element
* to true to indicate the seat is no longer available.
* 3) The program should never assign a seat that is already
* assigned.
* 4) When the economy section is full, the app should ask the
* person if it's acceptable to sit in first class or vice/versa.
* 4a) If acceptable, make the seat assignment. If not acceptable
* then display the message "Next flight leaves in 3 hours".
*/
static void Main(string[] args)
{
string mainMenuChoice;
//Initialize each seat to false.
for (int i = 0; i < seatingChart.Length; i++)
{
seatingChart[i] = false;
}
// user interface
// 1 - sell the user of the software to the user
// 2 - instructions (basic) on how to use the software
Console.WriteLine(@"
****************************************************
**** Welcome to the Airline Reservation System *****
****************************************************
This is a program for Small Airlines Incorporated
to assign seats for all flights on the airline's
only plane (capacity, 10 seats -- book now!).
You will be presented with a menu if you would like
to fly First Class or Economy. After choosing, you
will be assigned a seat if it is available. If no
seat is available, you will be asked if you would
like a seat in the other class of seats. If that is
still not satisfactory for your flying needs or all
seats are taken, we will inform you of our next flight
departure time.
Please watch the printed warnings about input types
carefully so that you don't crash the program!
****************************************************
");
//Enter main program loop to keep purchasing tickets
//like a ticketing agent.
do
{
//Input
//Display the menu.
Console.WriteLine("1) First Class");
Console.WriteLine("2) Economy");
Console.WriteLine("3) Exit Program");
Console.Write("What tickets would you like to purchase (1, 2, or 3): ");
//Get the input from the user and store it as a string
//as C# allows us to switch on a string, and does not
//risk crashing the program on int.Parse()
mainMenuChoice = Console.ReadLine();
switch (mainMenuChoice)
{
case "1":
PurchaseFirstClassTicket();
break;
case "2":
PurchaseEconomyTicket();
break;
case "3":
break;
default:
Console.WriteLine("Sorry, that's not a valid selection.");
break;
} //end switch mainMenuChoice
} //end do... while
while (mainMenuChoice != "3");
//salutation
Console.WriteLine("\nThank you for using this program! Good bye!");
} //END main
private static void PurchaseEconomyTicket()
{
string userAcceptsSeatClassChange = String.Empty;
//If there are seats remaining in the Economy class.
if (SeatsRemaining("Economy") > 0)
{
for (int i = 5; i < seatingChart.Length; i++)
{
/* Assign the next empty seat.
* Unfortunately I use break here because
* I don't know where the next index of False is
* in the range of seating area. Normally this is
* done with while, but since I am working in the
* middle of an array, it can't be done like that.
*/
if (!seatingChart[i])
{
seatingChart[i] = true;
break;
}
}
Console.WriteLine("Thank you for booking an Economy class ticket with us.");
}
else if(SeatsRemaining("First Class") > 0) //Economy is full, but First Class has seats.
{
Console.Write("Sorry, Economy section is full. " +
"Is it acceptable to be seated in First Class? (Y/N): ");
userAcceptsSeatClassChange = Console.ReadLine();
if(userAcceptsSeatClassChange.ToUpper() == "Y" )
{
PurchaseFirstClassTicket();
}
else //User does not want first class seats.
{
Console.WriteLine("Next flight leaves in 3 hours.");
}
}
else //The flight is full.
{
Console.WriteLine("Sorry, we're all booked up. Next flight leaves in 3 hours.");
}
} //END PurchaseEconomyTicket
private static void PurchaseFirstClassTicket()
{
string userAcceptsSeatClassChange = String.Empty;
//If there are seats remaining in First Class.
if (SeatsRemaining("First Class") > 0)
{
for (int i = 0; i < 5; i++)
{
/* Assign the next empty seat.
* Unfortunately I use break here because
* I don't know where the next index of False is
* in the range of seating area. Normally this is
* done with while, but since I am working in the
* middle of an array, it can't be done like that.
*/
if (!seatingChart[i])
{
seatingChart[i] = true;
break;
}
}
Console.WriteLine("Thank you for booking a First Class ticket with us.");
}
else if (SeatsRemaining("Economy") > 0) //First Class is full, but economy has seats.
{
Console.Write("Sorry, First Class section is full. " +
"Is it acceptable to be seated in Economy? (Y/N): ");
userAcceptsSeatClassChange = Console.ReadLine();
if (userAcceptsSeatClassChange.ToUpper() == "Y")
{
PurchaseEconomyTicket();
}
else
{
Console.WriteLine("Next flight leaves in 3 hours.");
}
}
else //The flight is full.
{
Console.WriteLine("Sorry, we're all booked up. Next flight leaves in 3 hours.");
}
} //END PurchaseFirstClassTicket
/* Gets the number of seats remaining in
* a given seating class, "Economy" or "First Class"
*
* Preconditions: not yet
* Inputs: string seatClass as "Economy" or "First Class"
* Outputs: integer
* Postconditions: not yet
*/
private static int SeatsRemaining(string seatClass)
{
//Setup variables.
int countOfSeatsRemaining = 0;
int start_index = 0;
int end_index = 0;
//Depending on seat class, we change where we
//start and end our for-loop to count the
//number of seats remaining in a given class.
switch(seatClass)
{
case "Economy":
start_index = 5;
end_index = 9;
break;
case "First Class":
start_index = 0;
end_index = 4;
break;
}
//For loop to count the number of seats remaining, seatClass agnostic.
for(int i=start_index; i<=end_index; i++)
{
if (!seatingChart[i])
countOfSeatsRemaining++;
}
//Return the number of seats remaining.
return countOfSeatsRemaining;
} //END SeatsRemaining
} //END class Program
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Airline")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Airline")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("204522aa-27c2-49ac-ba28-be82547473c9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

37
Cs3Apps/Cs3Apps.sln Normal file
View File

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29728.190
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Elimination", "Elimination\Elimination.csproj", "{6C32EC6B-CF2B-4032-B536-28900D5D52F0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Airline", "Airline\Airline.csproj", "{204522AA-27C2-49AC-BA28-BE82547473C9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TicTacToe", "TicTacToe\TicTacToe.csproj", "{6DA041E1-08F7-4FEB-8201-252D03BE5D34}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6C32EC6B-CF2B-4032-B536-28900D5D52F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6C32EC6B-CF2B-4032-B536-28900D5D52F0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6C32EC6B-CF2B-4032-B536-28900D5D52F0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6C32EC6B-CF2B-4032-B536-28900D5D52F0}.Release|Any CPU.Build.0 = Release|Any CPU
{204522AA-27C2-49AC-BA28-BE82547473C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{204522AA-27C2-49AC-BA28-BE82547473C9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{204522AA-27C2-49AC-BA28-BE82547473C9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{204522AA-27C2-49AC-BA28-BE82547473C9}.Release|Any CPU.Build.0 = Release|Any CPU
{6DA041E1-08F7-4FEB-8201-252D03BE5D34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6DA041E1-08F7-4FEB-8201-252D03BE5D34}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6DA041E1-08F7-4FEB-8201-252D03BE5D34}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6DA041E1-08F7-4FEB-8201-252D03BE5D34}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {01C3A74D-113A-49E8-9AC1-D323643747A6}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

View File

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{6C32EC6B-CF2B-4032-B536-28900D5D52F0}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Elimination</RootNamespace>
<AssemblyName>Elimination</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,162 @@
/* Shaun Marquardt
* TINFO 200
* CS3: Elimination
* ****************************************************
* Change History
* Date Developer Description
* 2020-02-18 marqusa File creation and initial implementation, Microsoft
*
* REFERENCES
* https://docs.microsoft.com/en-us/dotnet/api/system.array.resize?view=netframework-4.8
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Elimination
{
class Program
{
/* This is a program that asks the user for five numbers
* between 1 and 100 inclusive to be input.
* It uses a one-dimensional array, and as the number is read,
* the program will display the number only if it's not a duplicate
* of a number already read.
*
* This program has the following requirements:
* 1) There must be 5 input values that are ultimately accepted
* by the program before it is halted.
* 2) To be accepted, the value must be between 10-100 inclusive.
* 3) To be accepted, the value must be unique having never been
* entered BEFORE that point in time.
* 4) As each value is accepted, the program displays the contents
* of the unique set of values gathered so far.
*/
static void Main(string[] args)
{
//Initialize variables.
int[] eliminationArray = new int[0];
int userInputNumber;
// user interface
// 1 - sell the user of the software to the user
// 2 - instructions (basic) on how to use the software
Console.WriteLine(@"
****************************************************
********** Welcome to the Elimination App **********
****************************************************
This program will ask you, the user, for five numbers
to be input and display only the unique values that
were provided. It can be used to deduplicate
PIN numbers, combination locks, or anywhere where
a sequence of 1 to 5 unique values is required.
You will be asked to provide five whole numbers between
1 and 100 inclusively, such as 12, 42, 39, 98, etc.
Please watch the printed warnings about input types
carefully so that you don't crash the program!
****************************************************
");
/* This for loop will prompt and ask the user for
* input a total of five times.
*
* Implements Requirement 1:
* There must be 5 input values that are ultimately accepted
* by the program before it is halted.
*/
for (int i = 0; i < 5; i++)
{
//INPUT
//Requirement 2 (10-100 inclusive)
//is implemented in GetNumber.
userInputNumber = GetNumber();
//PROCESSING
/* If-check to implement requirement 3:
* To be accepted, the value must be unique having never been
* entered BEFORE that point in time.
* So if the eliminationArray DOES NOT contain the
* input number, add it to the array.
*/
if (!eliminationArray.Contains(userInputNumber))
{
//Add one more element to the elimination array
//ensuring we use the smallest possible array for each
//run of the program.
//Ref: Microsoft
Array.Resize(ref eliminationArray, eliminationArray.Length + 1);
//Insert the unique number into the end of the array.
eliminationArray[eliminationArray.Length - 1] = userInputNumber;
}
//OUTPUT
/* Implement Requirement 4: As each value is accepted,
* the program displays the contents of the unique set
* of values gathered so far.
*/
Console.Write($"The current unique values are: ");
//Instead of writing a standard loop, I can write it
//as an expression-bodied lamda statement.
//Convert the eliminationArray ToList, and iterate using ForEach method.
//"item" goes to "console.write <current unique integer in the array>"
eliminationArray.ToList().ForEach(item => Console.Write($"{item.ToString()} "));
//Insert some space bewtween the output and our next prompt.
Console.WriteLine();
} //end for
//salutation
Console.WriteLine("\nThank you for using this program! Good bye!");
} //end main
/* Gets a number from the user on the console.
* Implements Requirement 2: To be accepted, the
* value must be between 10-100 inclusive.
*
* Preconditions: not yet
* Inputs: no args
* Outputs: integer
* Postconditions: not yet
* Ref: marqusa / cs2 barchart
*/
private static int GetNumber()
{
//PROCESSING SECTION
//setup variables
bool isValidNumber = false;
int userInputNumber;
//Loop to check for valid input between 10-100.
do
{
//Prompt the user for input.
Console.Write("Please enter a whole number from 10-100: ");
//Store the input as an integer in the userInputNumber variable.
userInputNumber = int.Parse(Console.ReadLine());
//If the number is between 10 and 100 inclusive
//the input is valid. Set the isValidNumber boolean value
//to true to break out of the while loop.
if (userInputNumber >= 10 && userInputNumber <= 100)
isValidNumber = true;
//If the number is not valid, inform the user and return to the start of do..while
if (!isValidNumber)
Console.WriteLine("Sorry, that's not a valid number.");
}
while (!isValidNumber);
//Return the valid input number, between 10 and 100 inclusive.
return userInputNumber;
} //END GetNumber
} // END class Program
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Elimination")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Elimination")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6c32ec6b-cf2b-4032-b536-28900d5d52f0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="TicTacToe.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<userSettings>
<TicTacToe.Properties.Settings>
<setting name="PlayVsCPU" serializeAs="String">
<value>False</value>
</setting>
<setting name="CPUAsPlayer" serializeAs="String">
<value>2</value>
</setting>
</TicTacToe.Properties.Settings>
</userSettings>
</configuration>

332
Cs3Apps/TicTacToe/Form1.Designer.cs generated Normal file
View File

@ -0,0 +1,332 @@
/* The 'codebehind' the Form1.cs GUI interface.
* This is Microsoft Visual Studio generated code.
* It has not been mucked with by hand, all the code
* seen here was generated by Visual Studio.
*/
namespace TicTacToe
{
partial class frmTicTacToe
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.tlpProgramControls = new System.Windows.Forms.TableLayoutPanel();
this.mainMenuStrip = new System.Windows.Forms.MenuStrip();
this.gameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newGameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.playVsCPUToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cPUAsPlayer1ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cPUAsPlayer2ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.quitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lblPlayerTurn = new System.Windows.Forms.Label();
this.tlpMainGame = new System.Windows.Forms.TableLayoutPanel();
this.lbl22 = new System.Windows.Forms.Label();
this.lbl21 = new System.Windows.Forms.Label();
this.lbl12 = new System.Windows.Forms.Label();
this.lbl11 = new System.Windows.Forms.Label();
this.lbl20 = new System.Windows.Forms.Label();
this.lbl10 = new System.Windows.Forms.Label();
this.lbl02 = new System.Windows.Forms.Label();
this.lbl01 = new System.Windows.Forms.Label();
this.lbl00 = new System.Windows.Forms.Label();
this.CPUTurnTimer = new System.Windows.Forms.Timer(this.components);
this.tlpProgramControls.SuspendLayout();
this.mainMenuStrip.SuspendLayout();
this.tlpMainGame.SuspendLayout();
this.SuspendLayout();
//
// tlpProgramControls
//
this.tlpProgramControls.ColumnCount = 2;
this.tlpProgramControls.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tlpProgramControls.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tlpProgramControls.Controls.Add(this.mainMenuStrip, 0, 0);
this.tlpProgramControls.Controls.Add(this.lblPlayerTurn, 1, 0);
this.tlpProgramControls.Dock = System.Windows.Forms.DockStyle.Top;
this.tlpProgramControls.Location = new System.Drawing.Point(0, 0);
this.tlpProgramControls.Name = "tlpProgramControls";
this.tlpProgramControls.RowCount = 1;
this.tlpProgramControls.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tlpProgramControls.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 41F));
this.tlpProgramControls.Size = new System.Drawing.Size(800, 41);
this.tlpProgramControls.TabIndex = 2;
//
// mainMenuStrip
//
this.mainMenuStrip.GripMargin = new System.Windows.Forms.Padding(2, 2, 0, 2);
this.mainMenuStrip.ImageScalingSize = new System.Drawing.Size(24, 24);
this.mainMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.gameToolStripMenuItem});
this.mainMenuStrip.Location = new System.Drawing.Point(0, 0);
this.mainMenuStrip.Name = "mainMenuStrip";
this.mainMenuStrip.Size = new System.Drawing.Size(400, 36);
this.mainMenuStrip.TabIndex = 0;
this.mainMenuStrip.Text = "mainMenuStrip";
//
// gameToolStripMenuItem
//
this.gameToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newGameToolStripMenuItem,
this.playVsCPUToolStripMenuItem,
this.quitToolStripMenuItem});
this.gameToolStripMenuItem.Name = "gameToolStripMenuItem";
this.gameToolStripMenuItem.Size = new System.Drawing.Size(74, 32);
this.gameToolStripMenuItem.Text = "&Game";
//
// newGameToolStripMenuItem
//
this.newGameToolStripMenuItem.Name = "newGameToolStripMenuItem";
this.newGameToolStripMenuItem.Size = new System.Drawing.Size(213, 34);
this.newGameToolStripMenuItem.Text = "&New Game";
this.newGameToolStripMenuItem.Click += new System.EventHandler(this.newGameToolStripMenuItem_Click);
//
// playVsCPUToolStripMenuItem
//
this.playVsCPUToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.cPUAsPlayer1ToolStripMenuItem,
this.cPUAsPlayer2ToolStripMenuItem});
this.playVsCPUToolStripMenuItem.Name = "playVsCPUToolStripMenuItem";
this.playVsCPUToolStripMenuItem.Size = new System.Drawing.Size(213, 34);
this.playVsCPUToolStripMenuItem.Text = "Play vs &CPU";
this.playVsCPUToolStripMenuItem.Click += new System.EventHandler(this.playVsCPUToolStripMenuItem_Click);
//
// cPUAsPlayer1ToolStripMenuItem
//
this.cPUAsPlayer1ToolStripMenuItem.Name = "cPUAsPlayer1ToolStripMenuItem";
this.cPUAsPlayer1ToolStripMenuItem.Size = new System.Drawing.Size(236, 34);
this.cPUAsPlayer1ToolStripMenuItem.Text = "CPU as Player 1";
this.cPUAsPlayer1ToolStripMenuItem.Click += new System.EventHandler(this.cPUAsPlayer1ToolStripMenuItem_Click);
//
// cPUAsPlayer2ToolStripMenuItem
//
this.cPUAsPlayer2ToolStripMenuItem.Name = "cPUAsPlayer2ToolStripMenuItem";
this.cPUAsPlayer2ToolStripMenuItem.Size = new System.Drawing.Size(236, 34);
this.cPUAsPlayer2ToolStripMenuItem.Text = "CPU as Player 2";
this.cPUAsPlayer2ToolStripMenuItem.Click += new System.EventHandler(this.cPUAsPlayer2ToolStripMenuItem_Click);
//
// quitToolStripMenuItem
//
this.quitToolStripMenuItem.Name = "quitToolStripMenuItem";
this.quitToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F4)));
this.quitToolStripMenuItem.Size = new System.Drawing.Size(213, 34);
this.quitToolStripMenuItem.Text = "&Quit";
this.quitToolStripMenuItem.Click += new System.EventHandler(this.quitToolStripMenuItem_Click);
//
// lblPlayerTurn
//
this.lblPlayerTurn.AutoSize = true;
this.lblPlayerTurn.Dock = System.Windows.Forms.DockStyle.Fill;
this.lblPlayerTurn.Location = new System.Drawing.Point(403, 0);
this.lblPlayerTurn.Name = "lblPlayerTurn";
this.lblPlayerTurn.Size = new System.Drawing.Size(394, 41);
this.lblPlayerTurn.TabIndex = 1;
this.lblPlayerTurn.Text = "Player Turn: **GAME OVER **\nClick to Start";
this.lblPlayerTurn.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// tlpMainGame
//
this.tlpMainGame.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Outset;
this.tlpMainGame.ColumnCount = 3;
this.tlpMainGame.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tlpMainGame.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tlpMainGame.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tlpMainGame.Controls.Add(this.lbl22, 2, 2);
this.tlpMainGame.Controls.Add(this.lbl21, 1, 2);
this.tlpMainGame.Controls.Add(this.lbl12, 2, 1);
this.tlpMainGame.Controls.Add(this.lbl11, 1, 1);
this.tlpMainGame.Controls.Add(this.lbl20, 0, 2);
this.tlpMainGame.Controls.Add(this.lbl10, 0, 1);
this.tlpMainGame.Controls.Add(this.lbl02, 2, 0);
this.tlpMainGame.Controls.Add(this.lbl01, 1, 0);
this.tlpMainGame.Controls.Add(this.lbl00, 0, 0);
this.tlpMainGame.Dock = System.Windows.Forms.DockStyle.Fill;
this.tlpMainGame.Location = new System.Drawing.Point(0, 41);
this.tlpMainGame.Name = "tlpMainGame";
this.tlpMainGame.RowCount = 3;
this.tlpMainGame.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tlpMainGame.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tlpMainGame.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tlpMainGame.Size = new System.Drawing.Size(800, 409);
this.tlpMainGame.TabIndex = 3;
//
// lbl22
//
this.lbl22.AutoSize = true;
this.lbl22.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbl22.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl22.Location = new System.Drawing.Point(537, 272);
this.lbl22.Name = "lbl22";
this.lbl22.Size = new System.Drawing.Size(258, 135);
this.lbl22.TabIndex = 8;
this.lbl22.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lbl22.Click += new System.EventHandler(this.GameBoardLbl_Click);
//
// lbl21
//
this.lbl21.AutoSize = true;
this.lbl21.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbl21.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl21.Location = new System.Drawing.Point(271, 272);
this.lbl21.Name = "lbl21";
this.lbl21.Size = new System.Drawing.Size(258, 135);
this.lbl21.TabIndex = 7;
this.lbl21.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lbl21.Click += new System.EventHandler(this.GameBoardLbl_Click);
//
// lbl12
//
this.lbl12.AutoSize = true;
this.lbl12.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbl12.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl12.Location = new System.Drawing.Point(537, 137);
this.lbl12.Name = "lbl12";
this.lbl12.Size = new System.Drawing.Size(258, 133);
this.lbl12.TabIndex = 6;
this.lbl12.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lbl12.Click += new System.EventHandler(this.GameBoardLbl_Click);
//
// lbl11
//
this.lbl11.AutoSize = true;
this.lbl11.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbl11.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl11.Location = new System.Drawing.Point(271, 137);
this.lbl11.Name = "lbl11";
this.lbl11.Size = new System.Drawing.Size(258, 133);
this.lbl11.TabIndex = 5;
this.lbl11.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lbl11.Click += new System.EventHandler(this.GameBoardLbl_Click);
//
// lbl20
//
this.lbl20.AutoSize = true;
this.lbl20.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbl20.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl20.Location = new System.Drawing.Point(5, 272);
this.lbl20.Name = "lbl20";
this.lbl20.Size = new System.Drawing.Size(258, 135);
this.lbl20.TabIndex = 4;
this.lbl20.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lbl20.Click += new System.EventHandler(this.GameBoardLbl_Click);
//
// lbl10
//
this.lbl10.AutoSize = true;
this.lbl10.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbl10.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl10.Location = new System.Drawing.Point(5, 137);
this.lbl10.Name = "lbl10";
this.lbl10.Size = new System.Drawing.Size(258, 133);
this.lbl10.TabIndex = 3;
this.lbl10.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lbl10.Click += new System.EventHandler(this.GameBoardLbl_Click);
//
// lbl02
//
this.lbl02.AutoSize = true;
this.lbl02.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbl02.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl02.Location = new System.Drawing.Point(537, 2);
this.lbl02.Name = "lbl02";
this.lbl02.Size = new System.Drawing.Size(258, 133);
this.lbl02.TabIndex = 2;
this.lbl02.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lbl02.Click += new System.EventHandler(this.GameBoardLbl_Click);
//
// lbl01
//
this.lbl01.AutoSize = true;
this.lbl01.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbl01.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl01.Location = new System.Drawing.Point(271, 2);
this.lbl01.Name = "lbl01";
this.lbl01.Size = new System.Drawing.Size(258, 133);
this.lbl01.TabIndex = 1;
this.lbl01.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lbl01.Click += new System.EventHandler(this.GameBoardLbl_Click);
//
// lbl00
//
this.lbl00.AutoSize = true;
this.lbl00.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbl00.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl00.Location = new System.Drawing.Point(5, 2);
this.lbl00.Name = "lbl00";
this.lbl00.Size = new System.Drawing.Size(258, 133);
this.lbl00.TabIndex = 0;
this.lbl00.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lbl00.Click += new System.EventHandler(this.GameBoardLbl_Click);
//
// CPUTurnTimer
//
this.CPUTurnTimer.Tick += new System.EventHandler(this.CPUTurnTimer_Tick);
//
// frmTicTacToe
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.tlpMainGame);
this.Controls.Add(this.tlpProgramControls);
this.Name = "frmTicTacToe";
this.Text = "Tic Tac Toe";
this.Load += new System.EventHandler(this.frmTicTacToe_Load);
this.tlpProgramControls.ResumeLayout(false);
this.tlpProgramControls.PerformLayout();
this.mainMenuStrip.ResumeLayout(false);
this.mainMenuStrip.PerformLayout();
this.tlpMainGame.ResumeLayout(false);
this.tlpMainGame.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tlpProgramControls;
private System.Windows.Forms.MenuStrip mainMenuStrip;
private System.Windows.Forms.ToolStripMenuItem gameToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newGameToolStripMenuItem;
private System.Windows.Forms.TableLayoutPanel tlpMainGame;
private System.Windows.Forms.Label lbl10;
private System.Windows.Forms.Label lbl02;
private System.Windows.Forms.Label lbl01;
private System.Windows.Forms.Label lbl00;
private System.Windows.Forms.Label lbl22;
private System.Windows.Forms.Label lbl21;
private System.Windows.Forms.Label lbl12;
private System.Windows.Forms.Label lbl11;
private System.Windows.Forms.Label lbl20;
private System.Windows.Forms.ToolStripMenuItem playVsCPUToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem quitToolStripMenuItem;
private System.Windows.Forms.Label lblPlayerTurn;
private System.Windows.Forms.ToolStripMenuItem cPUAsPlayer1ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cPUAsPlayer2ToolStripMenuItem;
private System.Windows.Forms.Timer CPUTurnTimer;
}
}

472
Cs3Apps/TicTacToe/Form1.cs Normal file
View File

@ -0,0 +1,472 @@
/* Shaun Marquardt
* TINFO 200
* CS3: TicTacToe
* ****************************************************
* Change History
* Date Developer Description
* 2020-02-18 marqusa File creation and initial implementation,
* Martyr2 (Coders Lexicon), Microsoft, Chuck Costarella L5Life
* 2020-02-22 marqusa Add functionality to clear the game board labels.
* Implement Winner and Draw Game.
* Completed program, add documentation.
* 2020-02-23 marqusa Add functionality to have CPU play as player 1 or player 2.
* Moved winner stuff out of GameLbl_Click
* 2020-02-24 marqusa Fixed the form menu system for Play vs CPU checkboxes,
* they were acting funky. Split PlayVsCPU(int turn) into new function.
* Also updated the CPUTimer_Tick to do nothing
* if the game is over.
*
* The Form1.cs class acts as the primary driver for the TicTacToe class
* which actually plays the game proper. Most of my comments regarding how
* the game actually works will be in the TicTacToe.cs file.
*
* Recieves a delegate event from TicTacToe to update the label in the cell
* that was clicked after the 3x3 2d array called 'gameBoard' in the
* TicTacToe class gets updated
*
* REFERENCES
* https://www.coderslexicon.com/passing-data-between-forms-using-delegates-and-events/
* https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.controlcollection.find?view=netframework-4.8
* https://docs.microsoft.com/en-us/dotnet/api/system.eventargs?view=netframework-4.8
*
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TicTacToe
{
public partial class frmTicTacToe : Form
{
/* This is a program to play the classic game,
* Tic-Tac-Toe. The form you see displayed (and this class)
* is primarily a driver for the TicTacToe class
* which actually plays the game behind the scenes.
*
* Requirements:
* 1) Class TicTacToe enables us to create a complete app to play
* the game of Tic-Tac-Toe.
* 2) This class contains a private 3x3 rectangular array of integers.
* 3) The constructor initializes the empty board.
* 4) Each move should be in an empty square.
* 5) Determine win, lose, or draw.
*
* Extra Credit:
* The app is developed using a Windows Form application.
* It is possible to play vs CPU with CPU as Player 1 or Player 2.
*
* Extra Fun Stuff:
* The game actively tracks the current player's turn.
* I used an enum for both player turn and X and O.
* I included a delegate and custom event args to pass
* data from the TicTacToe class and update the correct label.
* The game is really handled by basically everything in the
* TicTacToe class with the form as a GUI frontend.
*/
//Create a new instance of the TicTacToe class
// and store it as a new object called 'game'.
TicTacToe game;
//Visual studio generated code.
public frmTicTacToe()
{
InitializeComponent();
}
/* Update the label in a given row/column with X or O
* according to what XorO enum value was placed using a delegate.
* Ref: Martyr2, Coders Lexicon'
* Preconditions: not yet
* Inputs: object sender, TicTacToe.RowColumnEventArgs e
* Outputs: void return
* Postconditions: not yet
*/
public void MessageReceived(object sender, EventArgs e)
{
//Ref: Microsoft, EventArgs
TicTacToe.RowColumnEventArgs args = (TicTacToe.RowColumnEventArgs)e;
//DEBUGGING:
//MessageBox.Show($"row: {args.row} col: {args.col}");
//Construct the label name we need.
string lblName = $"lbl{args.row}{args.col}";
//Get the label by constructed name.
//ref: microsoft, Controls.Find
Label theLabel = (Label)this.Controls.Find(lblName, true)[0];
//Place an X or an O in the square.
//Not playing against CPU is the easy case.
//Player 1 is always X. Player 2 is O
if (!Properties.Settings.Default.PlayVsCPU)
{
if (game.CurrentPlayerTurn == TicTacToe.PlayerTurn.Player1)
theLabel.Text = TicTacToe.XorO.x.ToString();
else
theLabel.Text = TicTacToe.XorO.o.ToString();
}
else //We are playing against CPU.
{
//If it's the CPU turn, place the CPU move.
if (game.CurrentPlayerTurn == TicTacToe.PlayerTurn.CPU)
{
if (Properties.Settings.Default.CPUAsPlayer == 1)
{
theLabel.Text = TicTacToe.XorO.x.ToString();
}
else //CPU as player 2.
{
theLabel.Text = TicTacToe.XorO.o.ToString();
}
}
else //It's the player's turn
{
//The CPU is player 1, place an O for human's move.
if (Properties.Settings.Default.CPUAsPlayer == 1)
theLabel.Text = TicTacToe.XorO.o.ToString();
else //The CPU is player 2, place an X for human's move.
theLabel.Text = TicTacToe.XorO.x.ToString();
}
}
}
/* Visual studio generated delegate
* on form load. Instansiates a new TicTacToe class
* and stores it into the game object.
* Preconditions: not yet
* Inputs: object sender, EventArgs e
* Outputs: void return
* Postconditions: not yet
*/
private void frmTicTacToe_Load(object sender, EventArgs e)
{
//Pass the current TicTacToe form into the TicTacToe class
//so the event handler delegate can be hooked in and we
//can change the label in the tableGridView from the TicTacToe class.
game = new TicTacToe(this);
//If we are playing as CPU
if (Properties.Settings.Default.PlayVsCPU)
{
playVsCPUToolStripMenuItem.Checked = true;
//Check the CPU as player 1 tool strip menu item
if (Properties.Settings.Default.CPUAsPlayer == 1)
{
cPUAsPlayer1ToolStripMenuItem.Checked = true;
}
else //Check the CPU as player 2 tool strip menu item.
{
cPUAsPlayer2ToolStripMenuItem.Checked = true;
}
}
/* Start the timer to watch for CPU Turn.
* This must be outside the if statement
* as "Play vs CPU" can be checked (or unchecked) anytime
* there is a "Game Over" status.
*/
CPUTurnTimer.Start();
}
/* Starts a new game on Game > New Game click.
* Visual Studio Generated Delegate.
* Preconditions: not yet
* Inputs: object sender, EventArgs e
* Outputs: void return
* Postconditions: not yet
*/
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
game.StartNewGame();
ClearGameLabels();
//Must set GameOver to true here
//so if the user clicks the new game menu item
//it is also possible to click the "Play vs CPU"
//menu item/option.
game.GameOver = true;
}
/* Clear all the labels on the board of X or O.
* Preconditions: not yet
* Inputs: no args
* Outputs: void return
* Postconditions: not yet
*/
private void ClearGameLabels()
{
//Loop through each control docked in the
//table main game layout panel that holds all
//the labels for Xs and Os to go into.
foreach (var tlpControl in tlpMainGame.Controls)
{
Label label = (Label)tlpControl;
label.Text = string.Empty;
}
//Reset the player turn to Game Over.
lblPlayerTurn.Text = "Player Turn: **GAME OVER **\nClick to Start";
}
/* Quit the game and exits the application.
* Visual Studio generated delegate.
* Preconditions: not yet
* Inputs: object sender, EventArgs e
* Outputs: void return
* Postconditions: not yet
*/
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
//Salutation
MessageBox.Show("Thank you for playing! Good bye!");
Environment.Exit(0);
}
/* This is the main delegate that is called when a player
* clicks a position on the game board to play the game.
* Visual Studio generated delegate.
* Preconditions: not yet
* Inputs: object sender, EventArgs e
* Outputs: void return
* Postconditions: not yet
*/
private void GameBoardLbl_Click(object sender, EventArgs e)
{
//If the game is over, start a new game.
if (game.GameOver)
{
game.StartNewGame();
ClearGameLabels();
//If the player is playing against CPU
//and CPU is player 1, adjust the turn to CPU turn.
if (Properties.Settings.Default.PlayVsCPU
&& Properties.Settings.Default.CPUAsPlayer == 1)
game.CurrentPlayerTurn = TicTacToe.PlayerTurn.CPU;
}
//If the player is playing against the CPU
//and it is not their CurrentPlayerTurn, do nothing.
if (Properties.Settings.Default.PlayVsCPU && game.CurrentPlayerTurn == TicTacToe.PlayerTurn.CPU)
return;
//Get the name of the label and parse it to find out our indexes.
Label clickedGamePosition = (Label)sender;
//Do not allow placing a move in a taken position.
if (clickedGamePosition.Text != "")
return;
//Each label is named 'lblXX' where XX is the row and column
//that was clicked. So first pick off 'lbl', to leave 'xx'
string rowColumn = clickedGamePosition.Name.Remove(0, 3);
//Now get the row and column.
//ToString() must be called as rowColumn[x] returns type char.
int row = int.Parse(rowColumn[0].ToString());
int col = int.Parse(rowColumn[1].ToString());
//Take the current player's CurrentPlayerTurn.
game.TakePlayerTurn(game.CurrentPlayerTurn, row, col);
//Swap to the next player's CurrentPlayerTurn.
TicTacToe.XorO winningPlayer = game.TogglePlayerTurn(game.CurrentPlayerTurn);
//Update the player turn label
string playerStr = (game.CurrentPlayerTurn.ToString() == TicTacToe.PlayerTurn.CPU.ToString()) ? "CPU (THINKING...)" : game.CurrentPlayerTurn.ToString();
lblPlayerTurn.Text = $"Player turn: {playerStr}";
//Update winner
//Check for a winner which will overwrite the turn label.
UpdateWinner(winningPlayer);
} //GameBoardLbl_Click
/* Update the form label if there is a winner.
* Preconditions: not yet
* Inputs: XorO enum winningPlayer
* Outputs: void return
* Postconditions: not yet
*/
private void UpdateWinner(TicTacToe.XorO winningPlayer)
{
//Check for a winner which will overwrite the turn label.
if (game.GameOver) //There is a winner
{
string winningPlayerText = "**WINNER**: ";
//Not playing against CPU, easy case.
if (!Properties.Settings.Default.PlayVsCPU)
{
if (winningPlayer == TicTacToe.XorO.x) //Player 1 wins.
winningPlayerText += "Player 1";
else if (winningPlayer == TicTacToe.XorO.o)
winningPlayerText += "Player 2"; //Player 2 wins.
else
winningPlayerText = "**DRAW GAME!**";
}
else // (PLAY VS CPU)
{
//Player 1 CPU Wins
if (winningPlayer == TicTacToe.XorO.x && Properties.Settings.Default.CPUAsPlayer == 1)
winningPlayerText += "CPU";
else if (winningPlayer == TicTacToe.XorO.x) //Player 1 Wins
winningPlayerText += "Player 1";
else if (winningPlayer == TicTacToe.XorO.o && Properties.Settings.Default.CPUAsPlayer == 2) //player 2 cpu wins
winningPlayerText += "CPU";
else if (winningPlayer == TicTacToe.XorO.o) // player 2 wins
winningPlayerText += "Player 2";
else //Draw Game.
winningPlayerText = "**DRAW GAME!**";
} //end else
//Add Game Over text.
winningPlayerText += "\n **GAME OVER** - Click to Start";
//Update the player turn label with the winner.
lblPlayerTurn.Text = winningPlayerText;
} // if GameOver
} //UpdateWinner
/* Sets CPU as Player 1
* Visual Studio generated delegate.
* Preconditions: not yet
* Inputs: object sender, EventArgs e
* Outputs: void return
* Postconditions: not yet
*/
private void cPUAsPlayer1ToolStripMenuItem_Click(object sender, EventArgs e)
{
//If we are playing vs CPU and If the current box for
//P1 CPU is checked, Clear PlayVsCPU options.
if (Properties.Settings.Default.PlayVsCPU && cPUAsPlayer1ToolStripMenuItem.Checked == true)
{
SetPlayVsCPU(0);
}
else //We are not currently playing vs CPU. Start doing so with CPU as player 1.
{
SetPlayVsCPU(1);
}
}
/* Sets CPU as Player 2
* Visual Studio generated delegate.
* Preconditions: not yet
* Inputs: object sender, EventArgs e
* Outputs: void return
* Postconditions: not yet
*/
private void cPUAsPlayer2ToolStripMenuItem_Click(object sender, EventArgs e)
{
//If we are playing vs CPU and If the current box for
//P2 CPU is checked, Clear PlayVsCPU options.
if (Properties.Settings.Default.PlayVsCPU && cPUAsPlayer2ToolStripMenuItem.Checked == true)
{
SetPlayVsCPU(0);
}
else //We are not currently playing vs CPU. Start doing so with CPU as player 2.
{
SetPlayVsCPU(2);
}
}
/* Clears playing vs CPU if set.
* Visual Studio generated delegate.
* Preconditions: not yet
* Inputs: object sender, EventArgs e
* Outputs: void return
* Postconditions: not yet