最近在学些C#和winform的相关知识,所以写一些博客来记录一下自己的学习过程。作为一个又土又木的土木人,在以后写博客的过程中难免会出现一些错误,请各位大师多多指教,下面是我跟着大神的教程写的一个三子棋游戏(外国人好像叫Tic Tak Toe),我更改了一些地方,让游戏变得更甜蜜,非常适合跟女朋友一起玩。欢迎各位大神多提意见,多多交流。废话不多说,下面直接上代码:
using Systestem;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Tic_Tak_Toe
{
public partial class Form1 : Form
{
bool turn = false;//true=X turn;false=o turn;
int turn_count = 0;
public Form1()
{
InitializeComponent();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Author:ZeroCool","Description");
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void button_click(object sender, EventArgs e)
{
Button b = sender as Button;
if(turn)
{
b.Text = "我爱你";
b.Enabled = false;
turn = false;
chekForWinnner();
}
else if(!turn)
{
b.Text = "你爱我";
b.Enabled = false;
turn = true;
chekForWinnner();
}
turn_count++;
if(turn_count==9)
{
MessageBox.Show("平了","提示");
}
}
private void chekForWinnner()
{
bool there_is_a_winner = false;
//Horizontal check
if ((A1.Text == A2.Text) && (A2.Text == A3.Text) && (!A1.Enabled )) there_is_a_winner = true;
else if ((B1.Text == B2.Text) && (B2.Text == B3.Text) && (!B1.Enabled)) there_is_a_winner = true;
else if ((C1.Text == C2.Text) && (C2.Text == C3.Text) && (!C1.Enabled)) there_is_a_winner = true;
//Verital check
if ((C1.Text == B1.Text) && (B1.Text == A1.Text) && (!C1.Enabled)) there_is_a_winner = true;
else if ((C2.Text == B2.Text) && (B2.Text == A3.Text) && (!C2.Enabled)) there_is_a_winner = true;
else if ((C3.Text == B3.Text) && (B3.Text == A3.Text) && (!C3.Enabled)) there_is_a_winner = true;
//Diagnal
if (A1.Text == B2.Text && B2.Text == C3.Text && !A1.Enabled) there_is_a_winner = true;
else if (C1.Text == B2.Text && B2.Text == A3.Text && !C1.Enabled) there_is_a_winner = true;
if(there_is_a_winner)
{
string winner= "";
if(turn)
{
winner = "我爱你";
}
if(!turn)
{
winner = "你爱我";
}
try
{
foreach (Control c in Controls)
{
Button b = (Button)c;
b.Enabled = false;
}
}
catch { }
MessageBox.Show(winner+" Wins!","Yay!");
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void fileToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
turn = true;
turn_count = 0;
try
{
foreach(Control c in Controls)
{
Button b = (Button)c;
b.Enabled = true;
b.Text = "";
}
}
catch { }
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void A1_MouseEnter(object sender, EventArgs e)
{
}
private void mouse_Enter(object sender, EventArgs e)
{
//Button b = sender as Button;
//if (turn==true) { b.Text = "我爱你"; }
//if (turn == false) { b.Text = "你爱我"; }
}
private void mouse_Leave(object sender, EventArgs e)
{
//Button b = sender as Button;
//b.Text = "";
}
}
}
再来放几张游戏截图:
这是游戏开始界面