Click here to Skip to main content
15,892,072 members
Articles / Mobile Apps

A C# implementation of Reversi (Othello) Game for PocketPC and Windows

Rate me:
Please Sign up or sign in to vote.
4.75/5 (13 votes)
4 Aug 20043 min read 91.7K   4.4K   36  
A C# implementation of Reversi (Othello) Game for PocketPC and Windows.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using gma.Reversi;
using System.Threading;

namespace gma.Windows.Reversi
{
	/// <summary>
	/// Zusammenfassung f�r frmMain.
	/// </summary>
	public class frmMain : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Panel panel;
		private System.Windows.Forms.ProgressBar progressBar;
		private System.Windows.Forms.ImageList imageList;
		private System.Windows.Forms.MainMenu mainMenu;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.MenuItem menuItemNewGame;
		private System.Windows.Forms.MenuItem menuItemQuit;
		private System.Windows.Forms.MenuItem menuItemUndo;
		private System.ComponentModel.IContainer components;

		public frmMain()
		{
			//
			// Erforderlich f�r die Windows Form-Designerunterst�tzung
			//
			InitializeComponent();

			//
			// TODO: F�gen Sie den Konstruktorcode nach dem Aufruf von InitializeComponent hinzu
			//
		}

		static void Main() 
		{
			Application.Run(new frmMain());
		}


		/// <summary>
		/// Die verwendeten Ressourcen bereinigen.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Vom Windows Form-Designer generierter Code
		/// <summary>
		/// Erforderliche Methode f�r die Designerunterst�tzung. 
		/// Der Inhalt der Methode darf nicht mit dem Code-Editor ge�ndert werden.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmMain));
			this.panel = new System.Windows.Forms.Panel();
			this.progressBar = new System.Windows.Forms.ProgressBar();
			this.imageList = new System.Windows.Forms.ImageList(this.components);
			this.mainMenu = new System.Windows.Forms.MainMenu();
			this.menuItem1 = new System.Windows.Forms.MenuItem();
			this.menuItemNewGame = new System.Windows.Forms.MenuItem();
			this.menuItemQuit = new System.Windows.Forms.MenuItem();
			this.menuItemUndo = new System.Windows.Forms.MenuItem();
			this.SuspendLayout();
			// 
			// panel
			// 
			this.panel.Location = new System.Drawing.Point(8, 8);
			this.panel.Name = "panel";
			this.panel.Size = new System.Drawing.Size(232, 232);
			this.panel.TabIndex = 0;
			// 
			// progressBar
			// 
			this.progressBar.Location = new System.Drawing.Point(8, 248);
			this.progressBar.Name = "progressBar";
			this.progressBar.Size = new System.Drawing.Size(232, 23);
			this.progressBar.TabIndex = 1;
			// 
			// imageList
			// 
			this.imageList.ImageSize = new System.Drawing.Size(28, 28);
			this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
			this.imageList.TransparentColor = System.Drawing.Color.Transparent;
			// 
			// mainMenu
			// 
			this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					 this.menuItem1});
			// 
			// menuItem1
			// 
			this.menuItem1.Index = 0;
			this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.menuItemNewGame,
																					  this.menuItemUndo,
																					  this.menuItemQuit});
			this.menuItem1.Text = "Game";
			// 
			// menuItemNewGame
			// 
			this.menuItemNewGame.Index = 0;
			this.menuItemNewGame.Text = "New Game";
			this.menuItemNewGame.Click += new System.EventHandler(this.menuItemNewGame_Click);
			// 
			// menuItemQuit
			// 
			this.menuItemQuit.Index = 2;
			this.menuItemQuit.Text = "Quit";
			this.menuItemQuit.Click += new System.EventHandler(this.menuItemQuit_Click);
			// 
			// menuItemUndo
			// 
			this.menuItemUndo.Index = 1;
			this.menuItemUndo.Text = "Undo";
			this.menuItemUndo.Click += new System.EventHandler(this.menuItemUndo_Click);
			// 
			// frmMain
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(250, 275);
			this.Controls.Add(this.progressBar);
			this.Controls.Add(this.panel);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Menu = this.mainMenu;
			this.Name = "frmMain";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "frmMain";
			this.Load += new System.EventHandler(this.frmMain_Load);
			this.ResumeLayout(false);

		}
		#endregion

		BoardComplex brd;
		GUIPlayer human;
		VirtualPlayer computer;

		private void frmMain_Load(object sender, System.EventArgs e)
		{
			panel.Location=new System.Drawing.Point((this.Width-panel.Width)/2, 10);

			progressBar.Location= new System.Drawing.Point(panel.Location.X , panel.Location.Y+panel.Height +3);
			progressBar.Size = new Size(panel.Width , 20 );

			brd = new BoardComplex();

			human= new GUIPlayer(brd);
			human.PlayerColor =  Board.PLAYER_RED;

			computer = new VirtualPlayerComplex(brd);
			computer.PlayerColor = Board.PLAYER_WHITE;
			//computer.OnLog += new OnLogEvent(LogWrite);
			computer.OnProgress +=new OnProgressEvent(computer_OnProgress);

			progressBar.Minimum=0;
			progressBar.Maximum=100;
			
			brd.OnGameOver+=new OnGameOverEvent(brd_OnGameOver);
			brd.OnNeedRedraw += new OnNeedRedrawEvent(Redraw);
			brd.OnNeedRedrawAll += new OnNeedRedrawEvent(RedrawAll);
			menuItemNewGame_Click(null, null);
		}

		private void brd_OnGameOver()
		{
			int diference=brd.CounterRed-brd.CounterWhite;
			if (human.PlayerColor==Board.PLAYER_WHITE) diference=-diference;

			string txt=String.Empty;
			if (diference==0)  
				txt="The Game is a draw.\n\rB {0}: W {1}";
			else
				if (diference>0)  
				txt="Congratulations !\n\rYou are a Winner.\n\rB {0}: W {1}";
			else
				txt="Sorry, you lose.\n\rB {0}: W {1}";
			MessageBox.Show(String.Format(txt,brd.CounterRed ,brd.CounterWhite ),"Game over");
		}


		private void computer_OnProgress(int aProgress)
		{
			progressBar.Value = aProgress;
		}


		private void LogWrite(string msg)
		{
			/*
			textBoxLog.AppendText(msg);
			textBoxLog.SelectionStart = textBoxLog.Text.Length;
			textBoxLog.ScrollToCaret();
			*/
		}

		public void RedrawCell(gma.Reversi.Point aPoint, int phase)
		{
			int i = aPoint.X;
			int j = aPoint.Y;

			PictureBox btn = allButtons[i, j];
			if (btn == null)
			{
				btn = new PictureBox();
				btn.Size = new System.Drawing.Size(28, 28);
				btn.Location = new System.Drawing.Point(i * 29, j * 29);
				btn.Tag = new gma.Reversi.Point(i, j);
				//btn.BorderStyle=BorderStyle.FixedSingle;
				btn.Click += new System.EventHandler(this.ButtonClick);
				panel.Controls.Add(btn);
				allButtons[i, j] = btn;
			}

			//btn.BorderStyle = BorderStyle.None;

			switch (brd.GetStateAt(i, j))
			{
				case Board.PLAYER_RED:
					btn.Image =  imageList.Images[5-phase];
					break;
				case Board.PLAYER_WHITE:
					btn.Image =  imageList.Images[1+phase];
					break;
				case Board.SQUARE_EMPTY:
					btn.Image =  imageList.Images[0];
					break;
			}
			btn.BackColor = Color.White;
			btn.Refresh();
		}


		private int animationSpeed = 4;
		IList OldAvailableMoves=new ArrayList();
		bool IsAnimating=false;
		public void Redraw()
		{
			IsAnimating=true;
			this.Text=String.Format("Reversi B {0}:{1} W"  ,brd.CounterRed ,brd.CounterWhite);
			for (int phase=3; phase>=0; phase--)
			{
				foreach (gma.Reversi.Point anAffectedPoint in brd.AffectedSquares)
					RedrawCell(anAffectedPoint, phase );
				Application.DoEvents();
				Thread.Sleep(animationSpeed*25);
			}

			foreach(gma.Reversi.Point aPoint in OldAvailableMoves)
				if ( !brd.AffectedSquares.Contains(aPoint)) RedrawCell(aPoint,0);
			OldAvailableMoves.Clear();

			IList availableMoves = brd.GetAvailableMoves(brd.CurrentPlayer);
			foreach(gma.Reversi.Point aPoint in availableMoves)
			{
				if (brd.CurrentPlayer!=computer.PlayerColor)
				{
					allButtons[aPoint.X,aPoint.Y].Image = null;
					allButtons[aPoint.X,aPoint.Y].Refresh();
					OldAvailableMoves.Add(aPoint);
				}
			}
			IsAnimating=false;
		}

		private void RedrawAll()
		{
			Application.DoEvents();
			for (int i = 0; i < Board.SIZEX; i++)
				for (int j = 0; j < Board.SIZEY; j++)
					RedrawCell(new gma.Reversi.Point(i,j),0);
		}


        
		PictureBox[,] allButtons = new PictureBox[8, 8];

		void ButtonClick(object sender, System.EventArgs e)
		{
			if (brd.CurrentPlayer!=human.PlayerColor || IsAnimating) return;
			gma.Reversi.Point aPoint = (gma.Reversi.Point)(((PictureBox)sender).Tag);
			human.MakeMove(aPoint);
		}

		private void menuItemQuit_Click(object sender, System.EventArgs e)
		{
			Application.Exit();
		}

		private void menuItemNewGame_Click(object sender, System.EventArgs e)
		{
			frmStartGame frm= new frmStartGame();
			frm.MyColor=human.PlayerColor;
			frm.SearchDepth=5;
			frm.AnimationSpeed = animationSpeed;
			if (frm.ShowDialog()==DialogResult.OK)
			{
				Application.DoEvents();
				human.PlayerColor =  frm.MyColor;
				human.EnabelUndo=frm.EnableUndo; 
				menuItemUndo.Enabled=human.EnabelUndo;
				computer.PlayerColor = -human.PlayerColor;
				computer.MAX_DEPTH=frm.SearchDepth;
				animationSpeed = frm.AnimationSpeed;
				brd.StartGame();
			}
		}

		private void menuItemUndo_Click(object sender, System.EventArgs e)
		{
			try 
			{
				brd=human.UndoLastMove();
				human.Board=brd;
				computer.Board=brd;
				brd.OnGameOver+=new OnGameOverEvent(brd_OnGameOver);
				brd.OnNeedRedraw += new OnNeedRedrawEvent(Redraw);
				brd.OnNeedRedrawAll += new OnNeedRedrawEvent(RedrawAll);
				RedrawAll();
				Redraw();
			}
			catch (Exception)
			{
				MessageBox.Show("Unable to undo last Move!");
			}

		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer
Germany Germany
Tweeter: @gmamaladze
Google+: gmamaladze
Blog: gmamaladze.wordpress.com

Comments and Discussions