C# and WPF tutorial files

This commit is contained in:
Unknown
2017-05-29 21:01:07 +01:00
parent dfdd754362
commit 1cb838df3a
107 changed files with 5760 additions and 0 deletions

View File

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

View File

@ -0,0 +1,92 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" 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>{0FB8FF87-B543-44CE-BE5C-9E6EE23AC755}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>BasicCalculator</RootNamespace>
<AssemblyName>BasicCalculator</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</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.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Operation.cs" />
<Compile Include="OperationType.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BasicCalculator", "BasicCalculator.csproj", "{0FB8FF87-B543-44CE-BE5C-9E6EE23AC755}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0FB8FF87-B543-44CE-BE5C-9E6EE23AC755}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0FB8FF87-B543-44CE-BE5C-9E6EE23AC755}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0FB8FF87-B543-44CE-BE5C-9E6EE23AC755}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0FB8FF87-B543-44CE-BE5C-9E6EE23AC755}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,356 @@
namespace BasicCalculator
{
partial class Form1
{
/// <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.UserInputText = new System.Windows.Forms.TextBox();
this.CalculationResultText = new System.Windows.Forms.Label();
this.ButtonsPanel = new System.Windows.Forms.TableLayoutPanel();
this.EqualsButton = new System.Windows.Forms.Button();
this.DotButton = new System.Windows.Forms.Button();
this.ZeroButton = new System.Windows.Forms.Button();
this.PlusButton = new System.Windows.Forms.Button();
this.ThreeButton = new System.Windows.Forms.Button();
this.TwoButton = new System.Windows.Forms.Button();
this.OneButton = new System.Windows.Forms.Button();
this.MinusButton = new System.Windows.Forms.Button();
this.SixButton = new System.Windows.Forms.Button();
this.FiveButton = new System.Windows.Forms.Button();
this.FourButton = new System.Windows.Forms.Button();
this.TimesButton = new System.Windows.Forms.Button();
this.NineButton = new System.Windows.Forms.Button();
this.EightButton = new System.Windows.Forms.Button();
this.SevenButton = new System.Windows.Forms.Button();
this.DivideButton = new System.Windows.Forms.Button();
this.DelButton = new System.Windows.Forms.Button();
this.CEButton = new System.Windows.Forms.Button();
this.ButtonsPanel.SuspendLayout();
this.SuspendLayout();
//
// UserInputText
//
this.UserInputText.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.UserInputText.Location = new System.Drawing.Point(11, 12);
this.UserInputText.Name = "UserInputText";
this.UserInputText.Size = new System.Drawing.Size(578, 29);
this.UserInputText.TabIndex = 0;
//
// CalculationResultText
//
this.CalculationResultText.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.CalculationResultText.Location = new System.Drawing.Point(11, 54);
this.CalculationResultText.Name = "CalculationResultText";
this.CalculationResultText.Size = new System.Drawing.Size(578, 77);
this.CalculationResultText.TabIndex = 1;
this.CalculationResultText.Text = "Please enter an equation and press enter or =";
//
// ButtonsPanel
//
this.ButtonsPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ButtonsPanel.ColumnCount = 4;
this.ButtonsPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.ButtonsPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.ButtonsPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.ButtonsPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
this.ButtonsPanel.Controls.Add(this.EqualsButton, 3, 4);
this.ButtonsPanel.Controls.Add(this.DotButton, 2, 4);
this.ButtonsPanel.Controls.Add(this.ZeroButton, 1, 4);
this.ButtonsPanel.Controls.Add(this.PlusButton, 3, 3);
this.ButtonsPanel.Controls.Add(this.ThreeButton, 2, 3);
this.ButtonsPanel.Controls.Add(this.TwoButton, 1, 3);
this.ButtonsPanel.Controls.Add(this.OneButton, 0, 3);
this.ButtonsPanel.Controls.Add(this.MinusButton, 3, 2);
this.ButtonsPanel.Controls.Add(this.SixButton, 2, 2);
this.ButtonsPanel.Controls.Add(this.FiveButton, 1, 2);
this.ButtonsPanel.Controls.Add(this.FourButton, 0, 2);
this.ButtonsPanel.Controls.Add(this.TimesButton, 3, 1);
this.ButtonsPanel.Controls.Add(this.NineButton, 2, 1);
this.ButtonsPanel.Controls.Add(this.EightButton, 1, 1);
this.ButtonsPanel.Controls.Add(this.SevenButton, 0, 1);
this.ButtonsPanel.Controls.Add(this.DivideButton, 3, 0);
this.ButtonsPanel.Controls.Add(this.DelButton, 2, 0);
this.ButtonsPanel.Controls.Add(this.CEButton, 0, 0);
this.ButtonsPanel.Location = new System.Drawing.Point(16, 134);
this.ButtonsPanel.Name = "ButtonsPanel";
this.ButtonsPanel.RowCount = 5;
this.ButtonsPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F));
this.ButtonsPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F));
this.ButtonsPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F));
this.ButtonsPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F));
this.ButtonsPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F));
this.ButtonsPanel.Size = new System.Drawing.Size(573, 486);
this.ButtonsPanel.TabIndex = 2;
//
// EqualsButton
//
this.EqualsButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.EqualsButton.Location = new System.Drawing.Point(432, 391);
this.EqualsButton.Name = "EqualsButton";
this.EqualsButton.Size = new System.Drawing.Size(138, 92);
this.EqualsButton.TabIndex = 19;
this.EqualsButton.Text = "=";
this.EqualsButton.UseVisualStyleBackColor = true;
this.EqualsButton.Click += new System.EventHandler(this.EqualsButton_Click);
//
// DotButton
//
this.DotButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.DotButton.Location = new System.Drawing.Point(289, 391);
this.DotButton.Name = "DotButton";
this.DotButton.Size = new System.Drawing.Size(137, 92);
this.DotButton.TabIndex = 18;
this.DotButton.Text = ".";
this.DotButton.UseVisualStyleBackColor = true;
this.DotButton.Click += new System.EventHandler(this.DotButton_Click);
//
// ZeroButton
//
this.ZeroButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.ZeroButton.Location = new System.Drawing.Point(146, 391);
this.ZeroButton.Name = "ZeroButton";
this.ZeroButton.Size = new System.Drawing.Size(137, 92);
this.ZeroButton.TabIndex = 17;
this.ZeroButton.Text = "0";
this.ZeroButton.UseVisualStyleBackColor = true;
this.ZeroButton.Click += new System.EventHandler(this.ZeroButton_Click);
//
// PlusButton
//
this.PlusButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.PlusButton.Location = new System.Drawing.Point(432, 294);
this.PlusButton.Name = "PlusButton";
this.PlusButton.Size = new System.Drawing.Size(138, 91);
this.PlusButton.TabIndex = 15;
this.PlusButton.Text = "+";
this.PlusButton.UseVisualStyleBackColor = true;
this.PlusButton.Click += new System.EventHandler(this.PlusButton_Click);
//
// ThreeButton
//
this.ThreeButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.ThreeButton.Location = new System.Drawing.Point(289, 294);
this.ThreeButton.Name = "ThreeButton";
this.ThreeButton.Size = new System.Drawing.Size(137, 91);
this.ThreeButton.TabIndex = 14;
this.ThreeButton.Text = "3";
this.ThreeButton.UseVisualStyleBackColor = true;
this.ThreeButton.Click += new System.EventHandler(this.ThreeButton_Click);
//
// TwoButton
//
this.TwoButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.TwoButton.Location = new System.Drawing.Point(146, 294);
this.TwoButton.Name = "TwoButton";
this.TwoButton.Size = new System.Drawing.Size(137, 91);
this.TwoButton.TabIndex = 13;
this.TwoButton.Text = "2";
this.TwoButton.UseVisualStyleBackColor = true;
this.TwoButton.Click += new System.EventHandler(this.TwoButton_Click);
//
// OneButton
//
this.OneButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.OneButton.Location = new System.Drawing.Point(3, 294);
this.OneButton.Name = "OneButton";
this.OneButton.Size = new System.Drawing.Size(137, 91);
this.OneButton.TabIndex = 12;
this.OneButton.Text = "1";
this.OneButton.UseVisualStyleBackColor = true;
this.OneButton.Click += new System.EventHandler(this.OneButton_Click);
//
// MinusButton
//
this.MinusButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.MinusButton.Location = new System.Drawing.Point(432, 197);
this.MinusButton.Name = "MinusButton";
this.MinusButton.Size = new System.Drawing.Size(138, 91);
this.MinusButton.TabIndex = 11;
this.MinusButton.Text = "-";
this.MinusButton.UseVisualStyleBackColor = true;
this.MinusButton.Click += new System.EventHandler(this.MinusButton_Click);
//
// SixButton
//
this.SixButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.SixButton.Location = new System.Drawing.Point(289, 197);
this.SixButton.Name = "SixButton";
this.SixButton.Size = new System.Drawing.Size(137, 91);
this.SixButton.TabIndex = 10;
this.SixButton.Text = "6";
this.SixButton.UseVisualStyleBackColor = true;
this.SixButton.Click += new System.EventHandler(this.SixButton_Click);
//
// FiveButton
//
this.FiveButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.FiveButton.Location = new System.Drawing.Point(146, 197);
this.FiveButton.Name = "FiveButton";
this.FiveButton.Size = new System.Drawing.Size(137, 91);
this.FiveButton.TabIndex = 9;
this.FiveButton.Text = "5";
this.FiveButton.UseVisualStyleBackColor = true;
this.FiveButton.Click += new System.EventHandler(this.FiveButton_Click);
//
// FourButton
//
this.FourButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.FourButton.Location = new System.Drawing.Point(3, 197);
this.FourButton.Name = "FourButton";
this.FourButton.Size = new System.Drawing.Size(137, 91);
this.FourButton.TabIndex = 8;
this.FourButton.Text = "4";
this.FourButton.UseVisualStyleBackColor = true;
this.FourButton.Click += new System.EventHandler(this.FourButton_Click);
//
// TimesButton
//
this.TimesButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.TimesButton.Location = new System.Drawing.Point(432, 100);
this.TimesButton.Name = "TimesButton";
this.TimesButton.Size = new System.Drawing.Size(138, 91);
this.TimesButton.TabIndex = 7;
this.TimesButton.Text = "X";
this.TimesButton.UseVisualStyleBackColor = true;
this.TimesButton.Click += new System.EventHandler(this.TimesButton_Click);
//
// NineButton
//
this.NineButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.NineButton.Location = new System.Drawing.Point(289, 100);
this.NineButton.Name = "NineButton";
this.NineButton.Size = new System.Drawing.Size(137, 91);
this.NineButton.TabIndex = 6;
this.NineButton.Text = "9";
this.NineButton.UseVisualStyleBackColor = true;
this.NineButton.Click += new System.EventHandler(this.NineButton_Click);
//
// EightButton
//
this.EightButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.EightButton.Location = new System.Drawing.Point(146, 100);
this.EightButton.Name = "EightButton";
this.EightButton.Size = new System.Drawing.Size(137, 91);
this.EightButton.TabIndex = 5;
this.EightButton.Text = "8";
this.EightButton.UseVisualStyleBackColor = true;
this.EightButton.Click += new System.EventHandler(this.EightButton_Click);
//
// SevenButton
//
this.SevenButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.SevenButton.Location = new System.Drawing.Point(3, 100);
this.SevenButton.Name = "SevenButton";
this.SevenButton.Size = new System.Drawing.Size(137, 91);
this.SevenButton.TabIndex = 4;
this.SevenButton.Text = "7";
this.SevenButton.UseVisualStyleBackColor = true;
this.SevenButton.Click += new System.EventHandler(this.SevenButton_Click);
//
// DivideButton
//
this.DivideButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.DivideButton.Location = new System.Drawing.Point(432, 3);
this.DivideButton.Name = "DivideButton";
this.DivideButton.Size = new System.Drawing.Size(138, 91);
this.DivideButton.TabIndex = 3;
this.DivideButton.Text = "%";
this.DivideButton.UseVisualStyleBackColor = true;
this.DivideButton.Click += new System.EventHandler(this.DivideButton_Click);
//
// DelButton
//
this.DelButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.DelButton.Location = new System.Drawing.Point(289, 3);
this.DelButton.Name = "DelButton";
this.DelButton.Size = new System.Drawing.Size(137, 91);
this.DelButton.TabIndex = 2;
this.DelButton.Text = "Del";
this.DelButton.UseVisualStyleBackColor = true;
this.DelButton.Click += new System.EventHandler(this.DelButton_Click);
//
// CEButton
//
this.CEButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CEButton.Dock = System.Windows.Forms.DockStyle.Fill;
this.CEButton.Location = new System.Drawing.Point(3, 3);
this.CEButton.Name = "CEButton";
this.CEButton.Size = new System.Drawing.Size(137, 91);
this.CEButton.TabIndex = 0;
this.CEButton.Text = "CE";
this.CEButton.UseVisualStyleBackColor = true;
this.CEButton.Click += new System.EventHandler(this.CEButton_Click);
//
// Form1
//
this.AcceptButton = this.EqualsButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(11F, 24F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.CEButton;
this.ClientSize = new System.Drawing.Size(600, 632);
this.Controls.Add(this.ButtonsPanel);
this.Controls.Add(this.CalculationResultText);
this.Controls.Add(this.UserInputText);
this.MinimumSize = new System.Drawing.Size(460, 502);
this.Name = "Form1";
this.Text = "Basic Calculator";
this.ButtonsPanel.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox UserInputText;
private System.Windows.Forms.Label CalculationResultText;
private System.Windows.Forms.TableLayoutPanel ButtonsPanel;
private System.Windows.Forms.Button CEButton;
private System.Windows.Forms.Button EqualsButton;
private System.Windows.Forms.Button DotButton;
private System.Windows.Forms.Button ZeroButton;
private System.Windows.Forms.Button PlusButton;
private System.Windows.Forms.Button ThreeButton;
private System.Windows.Forms.Button TwoButton;
private System.Windows.Forms.Button OneButton;
private System.Windows.Forms.Button MinusButton;
private System.Windows.Forms.Button SixButton;
private System.Windows.Forms.Button FiveButton;
private System.Windows.Forms.Button FourButton;
private System.Windows.Forms.Button TimesButton;
private System.Windows.Forms.Button NineButton;
private System.Windows.Forms.Button EightButton;
private System.Windows.Forms.Button SevenButton;
private System.Windows.Forms.Button DivideButton;
private System.Windows.Forms.Button DelButton;
}
}

View File

@ -0,0 +1,542 @@
using System;
using System.Linq;
using System.Windows.Forms;
namespace BasicCalculator
{
/// <summary>
/// A basic calculator
/// </summary>
public partial class Form1 : Form
{
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
public Form1()
{
InitializeComponent();
}
#endregion
#region Clearing Methods
/// <summary>
/// Clears the user input text
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void CEButton_Click(object sender, EventArgs e)
{
// Clears the text from the user input text box
this.UserInputText.Text = string.Empty;
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Deletes the first character in front of the cursor
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void DelButton_Click(object sender, EventArgs e)
{
// Delete the value after the selected position
DeleteTextValue();
// Focus the user input text
FocusInputText();
}
#endregion
#region Operator Methods
/// <summary>
/// Adds the Divide character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void DivideButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("/");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Adds the Times character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void TimesButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("*");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Adds the Minus character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void MinusButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("-");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Adds the Plus character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void PlusButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("+");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Calculates the given equation in the user input text
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void EqualsButton_Click(object sender, EventArgs e)
{
// Calculate the equation
CalculateEquation();
// Focus the user input text
FocusInputText();
}
#endregion
#region Number Methods
/// <summary>
/// Adds the . character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void DotButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue(".");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Adds the 0 character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void ZeroButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("0");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Adds the 1 character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void OneButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("1");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Adds the 2 character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void TwoButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("2");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Adds the 3 character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void ThreeButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("3");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Adds the 4 character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void FourButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("4");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Adds the 5 character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void FiveButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("5");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Adds the 6 character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void SixButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("6");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Adds the 7 character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void SevenButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("7");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Adds the 8 character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void EightButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("8");
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Adds the 9 character to the text at the currently selection position
/// </summary>
/// <param name="sender">The event sender</param>
/// <param name="e">The event arguments</param>
private void NineButton_Click(object sender, EventArgs e)
{
// Insert the value in the user input text box at the currently selected position
InsertTextValue("9");
// Focus the user input text
FocusInputText();
}
#endregion
/// <summary>
/// Calculates the given equation and outputs the answer to the user label
/// </summary>
private void CalculateEquation()
{
// 1. Enums
// 2. New classes
// 3. For loops
// 4. try/catch
// 5. Recursive functions
// 6. Switch statements
this.CalculationResultText.Text = ParseOperation();
// Focus the user input text
FocusInputText();
}
/// <summary>
/// Parses the users equation and calculates the result
/// </summary>
/// <returns></returns>
private string ParseOperation()
{
try
{
// Get the users equation input
var input = this.UserInputText.Text;
// Remove all spaces
input = input.Replace(" ", "");
// Create a new top-level operation
var operation = new Operation();
var leftSide = true;
// Loop through each character of the input
// starting from the left working to the right
for (int i = 0; i < input.Length; i++)
{
// TODO: Handle order priority
// 4.2 + 5.7 * 3
// It should calculate 5 * 3 first, then 4 + the result (so 4 + 15)
// Check if the current character is a number
if ("0123456789.".Any(c => input[i] == c))
{
if (leftSide)
operation.LeftSide = AddNumberPart(operation.LeftSide, input[i]);
else
operation.RightSide = AddNumberPart(operation.RightSide, input[i]);
}
// If it is an operator ( + - * / ) set the operator type
else if ("+-*/".Any(c => input[i] == c))
{
// If we are on the right side already, we now need to calculate our current operation
// and set the result to the left side of the next operation
if (!leftSide)
{
// Get the operator type
var operatorType = GetOperationType(input[i]);
// Check if we actually have a right side number
if (operation.RightSide.Length == 0)
{
// Check the operator is not a minus (as they could be creating a negative number)
if (operatorType != OperationType.Minus)
throw new InvalidOperationException($"Operator (+ * / or more than one -) specified without an right side number");
// If we got here, the operator type is a minus, and there is no left number currently, so add the minus to the number
operation.RightSide += input[i];
}
else
{
// Calculate previous equation and set to the left side
operation.LeftSide = CalculateOperation(operation);
// Set new operator
operation.OperationType = operatorType;
// Clear the previous right number
operation.RightSide = string.Empty;
}
}
else
{
// Get the operator type
var operatorType = GetOperationType(input[i]);
// Check if we actually have a left side number
if (operation.LeftSide.Length == 0)
{
// Check the operator is not a minus (as they could be creating a negative number)
if (operatorType != OperationType.Minus)
throw new InvalidOperationException($"Operator (+ * / or more than one -) specified without an left side number");
// If we got here, the operator type is a minus, and there is no left number currently, so add the minus to the number
operation.LeftSide += input[i];
}
else
{
// If we get here, we have a left number and now an operator, so we want to move to the right side
// Set the operation type
operation.OperationType = operatorType;
// Move to the right side
leftSide = false;
}
}
}
}
// If we are done parsing, and there were no exceptions
// calculate the current operation
return CalculateOperation(operation);
}
catch (Exception ex)
{
return $"Invalid equation. {ex.Message}";
}
}
/// <summary>
/// Calculates an <see cref="Operation"/> and returns the result
/// </summary>
/// <param name="operation">The operation to calculate</param>
private string CalculateOperation(Operation operation)
{
// Store the number values of the string representations
decimal left = 0;
decimal right = 0;
// Check if we have a valid left side number
if (string.IsNullOrEmpty(operation.LeftSide) || !decimal.TryParse(operation.LeftSide, out left))
throw new InvalidOperationException($"Left side of the operation was not a number. {operation.LeftSide}");
// Check if we have a valid right side number
if (string.IsNullOrEmpty(operation.RightSide) || !decimal.TryParse(operation.RightSide, out right))
throw new InvalidOperationException($"Right side of the operation was not a number. {operation.RightSide}");
try
{
switch (operation.OperationType)
{
case OperationType.Add:
return (left + right).ToString();
case OperationType.Minus:
return (left - right).ToString();
case OperationType.Divide:
return (left / right).ToString();
case OperationType.Multiply:
return (left * right).ToString();
default:
throw new InvalidOperationException($"Unknown operator type when calculating operation. { operation.OperationType }");
}
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to calculate operation {operation.LeftSide} {operation.OperationType} {operation.RightSide}. {ex.Message}");
}
}
/// <summary>
/// Accepts a character and returns the known <see cref="OperationType"/>
/// </summary>
/// <param name="character">The character to parse</param>
/// <returns></returns>
private OperationType GetOperationType(char character)
{
switch (character)
{
case '+':
return OperationType.Add;
case '-':
return OperationType.Minus;
case '/':
return OperationType.Divide;
case '*':
return OperationType.Multiply;
default:
throw new InvalidOperationException($"Unknown operator type { character }");
}
}
/// <summary>
/// Attempts to add a new character to the current number, checking for valid characters as it goes
/// </summary>
/// <param name="currentNumber">The current number string</param>
/// <param name="newCharacter">The new character to append to the string</param>
/// <returns></returns>
private string AddNumberPart(string currentNumber, char newCharacter)
{
// Check if there is already a . in the number
if (newCharacter == '.' && currentNumber.Contains('.'))
throw new InvalidOperationException($"Number {currentNumber} already contains a . and another cannot be added");
return currentNumber + newCharacter;
}
#region Private Helpers
/// <summary>
/// Focuses the user input text
/// </summary>
private void FocusInputText()
{
this.UserInputText.Focus();
}
/// <summary>
/// Inserts the given text into the user input text box
/// </summary>
/// <param name="value">The value to insert</param>
private void InsertTextValue(string value)
{
// Remember selection start
var selectionStart = this.UserInputText.SelectionStart;
// Set new text
this.UserInputText.Text = this.UserInputText.Text.Insert(this.UserInputText.SelectionStart, value);
// Restore the selection start
this.UserInputText.SelectionStart = selectionStart + value.Length;
// Set selection length to zero
this.UserInputText.SelectionLength = 0;
}
/// <summary>
/// Deletes the character to the right of the selection start of the user input text box
/// </summary>
private void DeleteTextValue()
{
// If we don't have a value to delete, return
if (this.UserInputText.Text.Length < this.UserInputText.SelectionStart + 1)
return;
// Remember selection start
var selectionStart = this.UserInputText.SelectionStart;
// Delete the character to the right of the selection
this.UserInputText.Text = this.UserInputText.Text.Remove(this.UserInputText.SelectionStart, 1);
// Restore the selection start
this.UserInputText.SelectionStart = selectionStart;
// Set selection length to zero
this.UserInputText.SelectionLength = 0;
}
#endregion
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BasicCalculator
{
/// <summary>
/// Holds information about a single calculator operation
/// </summary>
public class Operation
{
#region Public Properties
/// <summary>
/// The left side of the operation
/// </summary>
public string LeftSide { get; set; }
/// <summary>
/// The right side of the operation
/// </summary>
public string RightSide { get; set; }
/// <summary>
/// The type of operation to perform
/// </summary>
public OperationType OperationType { get; set; }
/// <summary>
/// The inner operation to be performed initially before this operation
/// </summary>
public Operation InnerOperation { get; set; }
#endregion
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
public Operation()
{
// Create empty strings instead of having nulls
this.LeftSide = string.Empty;
this.RightSide = string.Empty;
}
#endregion
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BasicCalculator
{
/// <summary>
/// A type of operation the calculator can perform
/// </summary>
public enum OperationType
{
/// <summary>
/// Adds two values together
/// </summary>
Add,
/// <summary>
/// Takes one value from another
/// </summary>
Minus,
/// <summary>
/// Divides one number by another
/// </summary>
Divide,
/// <summary>
/// Multiplies two numbers together
/// </summary>
Multiply
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BasicCalculator
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

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("BasicCalculator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BasicCalculator")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("0fb8ff87-b543-44ce-be5c-9e6ee23ac755")]
// 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,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace BasicCalculator.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BasicCalculator.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace BasicCalculator.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

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

View File

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" 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>{77E04313-9F24-4906-94D7-E678564385D6}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>BitwiseOperators</RootNamespace>
<AssemblyName>BitwiseOperators</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</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" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BitwiseOperators", "BitwiseOperators.csproj", "{77E04313-9F24-4906-94D7-E678564385D6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{77E04313-9F24-4906-94D7-E678564385D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{77E04313-9F24-4906-94D7-E678564385D6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{77E04313-9F24-4906-94D7-E678564385D6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{77E04313-9F24-4906-94D7-E678564385D6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BitwiseOperators
{
public enum SomeValues
{
Red = 1,
Blue = 2,
Green = 4,
Black = 8,
White = 16,
Orange = 32,
Yellow = 64,
Pink = 128,
}
class Program
{
static void Main(string[] args)
{
//
// Binary
//
//
// Bitwise operators
//
// And & (Both)
// Or | (Either)
// Xor ^ (Exclusive or, different)
// Not ~ (Invert)
//
byte a = 122;
byte b = 7;
byte result = (byte)(a & b);
//Console.WriteLine($"{ Convert.ToString(a, 2).PadLeft(8, '0')} &");
//Console.WriteLine($"{ Convert.ToString(b, 2).PadLeft(8, '0')}");
//Console.WriteLine($"--------");
//Console.WriteLine($"{ Convert.ToString(result, 2).PadLeft(8, '0')}");
//Console.WriteLine();
//
// Bitwise Shifting
//
// Left <<
// Right >>
//
//byte c = 25;
//var cResult = (byte)(c << 4);
//Console.WriteLine($"{ Convert.ToString(c, 2).PadLeft(8, '0')} << 1");
//Console.WriteLine($"--------");
//Console.WriteLine($"{ Convert.ToString(cResult, 2).PadLeft(8, '0')}");
// Usage
//
// Toggling boolean
// Enum flags
// Masking
//
// Invert booleans
var d = true;
d ^= true;
// Enum flags
var someVals = (byte)(SomeValues.Blue);
Console.WriteLine($"{ Convert.ToString((byte)someVals, 2).PadLeft(8, '0')}");
if ((someVals & (byte)SomeValues.Blue) == (byte)SomeValues.Blue)
Console.WriteLine("Blue was included");
if ((someVals & (byte)SomeValues.White) == (byte)SomeValues.White)
Console.WriteLine("White was included");
// Masking
//
// -----1- Input
// 0000010 < Important bit (the mask)
// 0000010
var input = (byte)(SomeValues.White | SomeValues.Blue);
var mask = (byte)SomeValues.Blue;
var r = input & mask;
Console.ReadLine();
}
}
}

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("BitwiseOperators")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BitwiseOperators")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("77e04313-9f24-4906-94d7-e678564385d6")]
// 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,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>

View File

@ -0,0 +1,61 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" 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>{E7E6E236-2FD2-4D03-AED0-B15841A080B5}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ConsoleApplication1</RootNamespace>
<AssemblyName>ConsoleApplication1</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</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="NumberGuesser.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApplication1", "ConsoleApplication1.csproj", "{E7E6E236-2FD2-4D03-AED0-B15841A080B5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E7E6E236-2FD2-4D03-AED0-B15841A080B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E7E6E236-2FD2-4D03-AED0-B15841A080B5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E7E6E236-2FD2-4D03-AED0-B15841A080B5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E7E6E236-2FD2-4D03-AED0-B15841A080B5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,148 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
/// <summary>
/// Asks the user to guess a number between a certain range and then guesses that number in the fewest possible guesses
/// </summary>
public class NumberGuesser
{
#region Public Properties
/// <summary>
/// The largest number we ask the user to guess, between 0 and this number
/// </summary>
public int MaximumNumber { get; set; }
/// <summary>
/// The current number of guesses the computer has had
/// </summary>
public int CurrentNumberOfGuesses { get; private set; }
/// <summary>
/// The current known minimum number the user is thinking of
/// </summary>
public int CurrentGuessMinimum { get; private set; }
/// <summary>
/// The current known maximum number the user is thinking of
/// </summary>
public int CurrentGuessMaximum { get; private set; }
#endregion
#region .ctor
/// <summary>
/// Default constructor
/// </summary>
public NumberGuesser()
{
// Set default maximum number
this.MaximumNumber = 100;
}
#endregion
#region Public Methods
/// <summary>
/// Asks the user to think of a number between 0 and the maximum number
/// </summary>
public void InformUser()
{
// Ask user to think of a number between 0 and MaximumNumber
Console.WriteLine($"I want you to think of a number between 0 and { this.MaximumNumber }. Ok?");
Console.ReadLine();
}
/// <summary>
/// Asks the user a series of questions to discover the number they are thinking of
/// </summary>
public void DiscoverNumber()
{
// Clear variables to their initial values before a discovery
this.CurrentNumberOfGuesses = 0;
this.CurrentGuessMinimum = 0;
this.CurrentGuessMaximum = this.MaximumNumber / 2;
// While the guess isn't the same as the known maximum value
while (this.CurrentGuessMinimum != this.CurrentGuessMaximum)
{
// Increase guess amount (by 1)
this.CurrentNumberOfGuesses++;
// Ask the user if their number is between the guess range
Console.WriteLine($"Is your number between { this.CurrentGuessMinimum } and { this.CurrentGuessMaximum}?");
string response = Console.ReadLine();
// If the user confirmed their number is within the current range...
if (response?.ToLower().FirstOrDefault() == 'y')
{
// We know the number is between guessFrom and guessTo
// So set the new maximum number
this.MaximumNumber = this.CurrentGuessMaximum;
// Change the next guess range to be half of the new maximum range
this.CurrentGuessMaximum = this.CurrentGuessMaximum - (this.CurrentGuessMaximum - this.CurrentGuessMinimum) / 2;
}
// The number is greater than guessMax and less than or equal to max
else
{
// The new minimum is one above the old maximum
this.CurrentGuessMinimum = this.CurrentGuessMaximum + 1;
// Guess the bottom half of the new range
int remainingDifference = this.MaximumNumber - this.CurrentGuessMaximum;
// Set the guess max to half way between the guessMin and max
// NOTE: Math.Ceiling will round up the remaining difference to 2, if the difference is 3
this.CurrentGuessMaximum += (int)Math.Ceiling(remainingDifference / 2f);
}
// If we only have 2 numbers left, guess one of them
if (this.CurrentGuessMinimum + 1 == this.MaximumNumber)
{
// Increase guess amount (by 1)
this.CurrentNumberOfGuesses++;
// Ask the user if their number is the lower number
Console.WriteLine($"Is your number { this.CurrentGuessMinimum }?");
response = Console.ReadLine();
// If the user confirmed their number is the lower number...
if (response?.ToLower().FirstOrDefault() == 'y')
{
break;
}
else
{
// That means the number must be the higher of the two
this.CurrentGuessMinimum = this.MaximumNumber;
break;
}
}
}
}
/// <summary>
/// Annouces the number the user was thinking of and the number of guesses it took
/// </summary>
public void AnnounceResults()
{
// Tell the user their number
Console.WriteLine($"** Your number is { this.CurrentGuessMinimum } **");
// Let the user know how many guesses it took
Console.WriteLine($"Guessed in { this.CurrentNumberOfGuesses } guesses");
Console.ReadLine();
}
#endregion
}
}

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Create a new instance of our number guesser class
var numberGuesser = new NumberGuesser();
// Change the default maximum number to 200
numberGuesser.MaximumNumber = 200;
// Ask the user to think of a number
numberGuesser.InformUser();
// Discover the number the user is thinking of
numberGuesser.DiscoverNumber();
// Announce the results
numberGuesser.AnnounceResults();
}
}
}

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("ConsoleApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleApplication1")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("e7e6e236-2fd2-4d03-aed0-b15841a080b5")]
// 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")]

6
C# Beginners/README.md Normal file
View File

@ -0,0 +1,6 @@
# C# Beginners Tutorials
The files from the C# Beginners tutorials on the AngelSix YouTube channel
http://www.angelsix.com/youtube

View File

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

View File

@ -0,0 +1,9 @@
<Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}

View File

@ -0,0 +1,47 @@
<Window x:Class="WpfApplication1.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:WpfApplication1"
mc:Ignorable="d"
ResizeMode="NoResize"
Title="MainWindow" Height="500" Width="500">
<Window.Resources>
<Style TargetType="Button">
<Setter Property="Background" Value="White" />
<Setter Property="BorderThickness" Value="0.5" />
<Setter Property="FontSize" Value="70" />
</Style>
</Window.Resources>
<Grid Name="Container">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Click="Button_Click" x:Name="Button0_0" Grid.Column="0" Grid.Row="0" Content="X" />
<Button Click="Button_Click" x:Name="Button1_0" Grid.Column="1" Grid.Row="0" Content="O" />
<Button Click="Button_Click" x:Name="Button2_0" Grid.Column="2" Grid.Row="0" />
<Button Click="Button_Click" x:Name="Button0_1" Grid.Column="0" Grid.Row="1" />
<Button Click="Button_Click" x:Name="Button1_1" Grid.Column="1" Grid.Row="1" />
<Button Click="Button_Click" x:Name="Button2_1" Grid.Column="2" Grid.Row="1" />
<Button Click="Button_Click" x:Name="Button0_2" Grid.Column="0" Grid.Row="2" />
<Button Click="Button_Click" x:Name="Button1_2" Grid.Column="1" Grid.Row="2" />
<Button Click="Button_Click" x:Name="Button2_2" Grid.Column="2" Grid.Row="2" />
</Grid>
</Window>

View File

@ -0,0 +1,150 @@
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WpfApplication1
{
public enum MarkType
{
Free,
Nought,
Cross
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private MarkType[] mResults;
private bool mPlayer1Turn;
private bool mWinner;
public MainWindow()
{
InitializeComponent();
NewGame();
}
private void NewGame()
{
mResults = new MarkType[9];
for (var i = 0; i < mResults.Length; i++)
mResults[i] = MarkType.Free;
mPlayer1Turn = true;
Container.Children.Cast<Button>().ToList().ForEach(f =>
{
f.Content = string.Empty;
f.Background = Brushes.White;
f.Foreground = Brushes.Blue;
});
mWinner = false;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (mWinner)
{
NewGame();
return;
}
var button = (Button)sender;
var row = Grid.GetRow(button);
var column = Grid.GetColumn(button);
var index = column + (row * 3);
if (mResults[index] != MarkType.Free)
return;
mResults[index] = mPlayer1Turn ? MarkType.Cross : MarkType.Nought;
button.Content = mPlayer1Turn ? "X" : "O";
if (!mPlayer1Turn)
button.Foreground = Brushes.Red;
mPlayer1Turn ^= true;
CheckForWinner();
}
private void CheckForWinner()
{
if (mResults[0] != MarkType.Free && (mResults[0] & mResults[1] & mResults[2]) == mResults[0])
{
mWinner = true;
// Turn the winning blocks green
Button0_0.Background = Button1_0.Background = Button2_0.Background = Brushes.Green;
}
if (mResults[3] != MarkType.Free && (mResults[3] & mResults[4] & mResults[5]) == mResults[3])
{
mWinner = true;
// Turn the winning blocks green
Button0_1.Background = Button1_1.Background = Button2_1.Background = Brushes.Green;
}
if (mResults[6] != MarkType.Free && (mResults[6] & mResults[7] & mResults[8]) == mResults[6])
{
mWinner = true;
// Turn the winning blocks green
Button0_2.Background = Button1_2.Background = Button2_2.Background = Brushes.Green;
}
if (mResults[0] != MarkType.Free && (mResults[0] & mResults[3] & mResults[6]) == mResults[0])
{
mWinner = true;
// Turn the winning blocks green
Button0_0.Background = Button0_1.Background = Button0_2.Background = Brushes.Green;
}
if (mResults[1] != MarkType.Free && (mResults[1] & mResults[4] & mResults[7]) == mResults[1])
{
mWinner = true;
// Turn the winning blocks green
Button1_0.Background = Button1_1.Background = Button1_2.Background = Brushes.Green;
}
if (mResults[2] != MarkType.Free && (mResults[2] & mResults[5] & mResults[8]) == mResults[2])
{
mWinner = true;
// Turn the winning blocks green
Button2_0.Background = Button2_1.Background = Button2_2.Background = Brushes.Green;
}
if (mResults[0] != MarkType.Free && (mResults[0] & mResults[4] & mResults[8]) == mResults[0])
{
mWinner = true;
// Turn the winning blocks green
Button0_0.Background = Button1_1.Background = Button2_2.Background = Brushes.Green;
}
if (mResults[2] != MarkType.Free && (mResults[2] & mResults[4] & mResults[6]) == mResults[2])
{
mWinner = true;
// Turn the winning blocks green
Button2_0.Background = Button1_1.Background = Button0_2.Background = Brushes.Green;
}
if (!mResults.Any(f => f == MarkType.Free))
{
Container.Children.Cast<Button>().ToList().ForEach(f => f.Background = Brushes.Orange);
mWinner = true;
}
}
}
}

View File

@ -0,0 +1,55 @@
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("WpfApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WpfApplication1")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WpfApplication1.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfApplication1.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WpfApplication1.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@ -0,0 +1,106 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" 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>{9C304740-49D9-4ABB-ADE8-95CD37B6D0DA}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WpfApplication1</RootNamespace>
<AssemblyName>WpfApplication1</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</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.Data" />
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<AppDesigner Include="Properties\" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WpfApplication1", "WpfApplication1.csproj", "{9C304740-49D9-4ABB-ADE8-95CD37B6D0DA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9C304740-49D9-4ABB-ADE8-95CD37B6D0DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9C304740-49D9-4ABB-ADE8-95CD37B6D0DA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9C304740-49D9-4ABB-ADE8-95CD37B6D0DA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9C304740-49D9-4ABB-ADE8-95CD37B6D0DA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
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.5.2" />
</startup>
</configuration>

View File

@ -0,0 +1,9 @@
<Application x:Class="TicTacToe.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TicTacToe"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace TicTacToe
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}

View File

@ -0,0 +1,46 @@
<Window x:Class="TicTacToe.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:TicTacToe"
mc:Ignorable="d"
ResizeMode="NoResize"
Title="Tic Tac Toe" Height="500" Width="500">
<Window.Resources>
<Style TargetType="Button">
<Setter Property="Background" Value="White" />
<Setter Property="BorderThickness" Value="0.5" />
<Setter Property="FontSize" Value="70" />
</Style>
</Window.Resources>
<Grid x:Name="Container">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Click="Button_Click" x:Name="Button0_0" Grid.Column="0" Grid.Row="0" Content="X" />
<Button Click="Button_Click" x:Name="Button1_0" Grid.Column="1" Grid.Row="0" Content="O" />
<Button Click="Button_Click" x:Name="Button2_0" Grid.Column="2" Grid.Row="0" />
<Button Click="Button_Click" x:Name="Button0_1" Grid.Column="0" Grid.Row="1" />
<Button Click="Button_Click" x:Name="Button1_1" Grid.Column="1" Grid.Row="1" />
<Button Click="Button_Click" x:Name="Button2_1" Grid.Column="2" Grid.Row="1" />
<Button Click="Button_Click" x:Name="Button0_2" Grid.Column="0" Grid.Row="2" />
<Button Click="Button_Click" x:Name="Button1_2" Grid.Column="1" Grid.Row="2" />
<Button Click="Button_Click" x:Name="Button2_2" Grid.Column="2" Grid.Row="2" />
</Grid>
</Window>

View File

@ -0,0 +1,247 @@
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace TicTacToe
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region Private Members
/// <summary>
/// Holds the current results of cells in the active game
/// </summary>
private MarkType[] mResults;
/// <summary>
/// True if it is player 1's turn (X) or player 2's turn (O)
/// </summary>
private bool mPlayer1Turn;
/// <summary>
/// True if the game has ended
/// </summary>
private bool mGameEnded;
#endregion
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
public MainWindow()
{
InitializeComponent();
NewGame();
}
#endregion
/// <summary>
/// Starts a new game and clears all values back to the start
/// </summary>
private void NewGame()
{
// Create a new blank array of free cells
mResults = new MarkType[9];
for (var i = 0; i < mResults.Length; i++)
mResults[i] = MarkType.Free;
// Make sure Player 1 starts the game
mPlayer1Turn = true;
// Interate every button on the grid...
Container.Children.Cast<Button>().ToList().ForEach(button =>
{
// Change background, foreground and content to default values
button.Content = string.Empty;
button.Background = Brushes.White;
button.Foreground = Brushes.Blue;
});
// Make sure the game hasn't finished
mGameEnded = false;
}
/// <summary>
/// Handles a button click event
/// </summary>
/// <param name="sender">The button that was clicked</param>
/// <param name="e">The events of the click</param>
private void Button_Click(object sender, RoutedEventArgs e)
{
// Start a new game on the click after it finished
if (mGameEnded)
{
NewGame();
return;
}
// Cast the sender to a button
var button = (Button)sender;
// Find the buttons position in the array
var column = Grid.GetColumn(button);
var row = Grid.GetRow(button);
var index = column + (row * 3);
// Don't do anything if the cell already has a value in it
if (mResults[index] != MarkType.Free)
return;
// Set the cell value based on which players turn it is
mResults[index] = mPlayer1Turn ? MarkType.Cross : MarkType.Nought;
// Set button text to the result
button.Content = mPlayer1Turn ? "X" : "O";
// Change noughts to green
if (!mPlayer1Turn)
button.Foreground = Brushes.Red;
// Toggle the players turns
mPlayer1Turn ^= true;
// Check for a winner
CheckForWinner();
}
/// <summary>
/// Checks if there is a winner of a 3 line straight
/// </summary>
private void CheckForWinner()
{
#region Horizontal Wins
// Check for horizontal wins
//
// - Row 0
//
if (mResults[0] != MarkType.Free && (mResults[0] & mResults[1] & mResults[2]) == mResults[0])
{
// Game ends
mGameEnded = true;
// Highlight winning cells in green
Button0_0.Background = Button1_0.Background = Button2_0.Background = Brushes.Green;
}
//
// - Row 1
//
if (mResults[3] != MarkType.Free && (mResults[3] & mResults[4] & mResults[5]) == mResults[3])
{
// Game ends
mGameEnded = true;
// Highlight winning cells in green
Button0_1.Background = Button1_1.Background = Button2_1.Background = Brushes.Green;
}
//
// - Row 2
//
if (mResults[6] != MarkType.Free && (mResults[6] & mResults[7] & mResults[8]) == mResults[6])
{
// Game ends
mGameEnded = true;
// Highlight winning cells in green
Button0_2.Background = Button1_2.Background = Button2_2.Background = Brushes.Green;
}
#endregion
#region Vertical Wins
// Check for vertical wins
//
// - Column 0
//
if (mResults[0] != MarkType.Free && (mResults[0] & mResults[3] & mResults[6]) == mResults[0])
{
// Game ends
mGameEnded = true;
// Highlight winning cells in green
Button0_0.Background = Button0_1.Background = Button0_2.Background = Brushes.Green;
}
//
// - Column 1
//
if (mResults[1] != MarkType.Free && (mResults[1] & mResults[4] & mResults[7]) == mResults[1])
{
// Game ends
mGameEnded = true;
// Highlight winning cells in green
Button1_0.Background = Button1_1.Background = Button1_2.Background = Brushes.Green;
}
//
// - Column 2
//
if (mResults[2] != MarkType.Free && (mResults[2] & mResults[5] & mResults[8]) == mResults[2])
{
// Game ends
mGameEnded = true;
// Highlight winning cells in green
Button2_0.Background = Button2_1.Background = Button2_2.Background = Brushes.Green;
}
#endregion
#region Diagonal Wins
// Check for diagonal wins
//
// - Top Left Bottom Right
//
if (mResults[0] != MarkType.Free && (mResults[0] & mResults[4] & mResults[8]) == mResults[0])
{
// Game ends
mGameEnded = true;
// Highlight winning cells in green
Button0_0.Background = Button1_1.Background = Button2_2.Background = Brushes.Green;
}
//
// - Top Right Bottom Left
//
if (mResults[2] != MarkType.Free && (mResults[2] & mResults[4] & mResults[6]) == mResults[2])
{
// Game ends
mGameEnded = true;
// Highlight winning cells in green
Button2_0.Background = Button1_1.Background = Button0_2.Background = Brushes.Green;
}
#endregion
#region No Winners
// Check for no winner and full board
if (!mResults.Any(f => f == MarkType.Free))
{
// Game ended
mGameEnded = true;
// Turn all cells orange
Container.Children.Cast<Button>().ToList().ForEach(button =>
{
button.Background = Brushes.Orange;
});
}
#endregion
}
}
}

View File

@ -0,0 +1,21 @@
namespace TicTacToe
{
/// <summary>
/// The type of value a cell in the game is currently at
/// </summary>
public enum MarkType
{
/// <summary>
/// The cell hasn't been clicked yet
/// </summary>
Free,
/// <summary>
/// The cell is a O
/// </summary>
Nought,
/// <summary>
/// The cell is an X
/// </summary>
Cross
}
}

View File

@ -0,0 +1,55 @@
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("TicTacToe")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TicTacToe")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TicTacToe.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TicTacToe.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TicTacToe.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@ -0,0 +1,107 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" 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>{1ABAD3C0-F90C-4E5D-9E4E-2E8847F4C4A6}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TicTacToe</RootNamespace>
<AssemblyName>TicTacToe</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</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.Data" />
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<Compile Include="MarkType.cs" />
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<AppDesigner Include="Properties\" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TicTacToe", "TicTacToe.csproj", "{1ABAD3C0-F90C-4E5D-9E4E-2E8847F4C4A6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1ABAD3C0-F90C-4E5D-9E4E-2E8847F4C4A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1ABAD3C0-F90C-4E5D-9E4E-2E8847F4C4A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1ABAD3C0-F90C-4E5D-9E4E-2E8847F4C4A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1ABAD3C0-F90C-4E5D-9E4E-2E8847F4C4A6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal