Pages

Subscribe:

Ads 468x60px

Monday, 12 September 2011

Time Ticker2 Game

Tools used : .NetFramework Beta 2, Editplus.

Introduction
Microsoft had made lot of Changes for Beta2,  some of the changes are old Namespace such as  System.WinFormsmodified  to System.Windows.Forms. In addition no. of new Namespaces like Microsoft.CSharp, Microsoft.JScript,Microsoft.Vsa etc... are added.  In Beta2, namespace Microsoft.Win32.Interop is integrated with mscorlib library, so no need to use this library while compiling, whereas it is compulsory in Beta1.
TimeTicker sample application can be compatible with Beta2 with the following modifications.
1) Change namespace  System.WinForms to System.Windows.Forms
2) Change BorderStyle property to FormBorderStyle
3) Change the Methods FromHWND to FromHwnd and  FromARGB to  FromArgb
Source code
/*
Author Mokhtar B
Date 4th July, 2001
Company Adsoft Solutions Pvt. Ltd 
Application Type Windows Forms 
*/
using System;using System.Windows.Forms; using System.Drawing;public class TimeTicker:Form
{
private Graphics g;private Font DispFont;private string CDate; private SolidBrush MyBrush;// Constructorpublic TimeTicker()
{
InitializeComponents();
}
public void InitializeComponents()
{
DispFont = 
new Font("Arial",35,FontStyle.Bold);
MyBrush = 
new SolidBrush(Color.Red);
CDate = DateTime.Now.ToString();
g = Graphics.FromHwnd(
this.Handle);//Instantiating Timer ClassTimer aTimer = new Timer(); 
aTimer.Interval = 1000; 
// 1000 millisecondsaTimer.Enabled = true;
aTimer.Tick += 
new EventHandler(OnTimer);//Setting Form Propertiesthis.Size = new Size(310, 150);this.Text = "Time Ticker";this.MaximizeBox = false;this.MinimizeBox = false;this.FormBorderStyle = FormBorderStyle.FixedSingle;//Setting Form Icon through Icon Classthis.Icon = new Icon("clock.ico"); this.StartPosition=FormStartPosition.CenterScreen;
}
protected override void OnPaint(PaintEventArgs e)
{
g.DrawString(CDate.Substring(9) , DispFont,MyBrush,10,30);
}
//Timer Eventprotected void OnTimer(object source, EventArgs e)
{ 
CDate = DateTime.Now.ToString();
g.Clear(Color.FromArgb(216,208,200));
g.DrawString(CDate.Substring(9) , DispFont,MyBrush,10,30);
}
public static void Main()
{
Application.Run(
new TimeTicker()); 
} 
}
Compilation
csc /t:winexe /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll TimeTicker2.cs
Output

Mastermind Game with Drag and Drop Functionality

There as nice article some time ago on this site for creating mastermind game by Mike Gold. I am rewriting complete game from scratch to implement Drag and Drop feature and presentable User interface. 


MasterMindGameLogic: I have Implemented Game logic in separate Class Board which handles all Game. 
frmMasterMind.cs: Is a form containing user interface for mastermind game 
I have used off-Screen drawing combined with opaque background by overriding OnPaintBackground method of form to Produce flicker free and smooth rendering of User interface.  
For Dragging I have used combination of mouse down mouse Move and mouse up events.  
For purpose of speeding up Drawing I have created all images in memory  like pegs, Result pegs , peg hole and  result hole so that I do not have to create this images during every screen refresh, other purpose of doing so was to allow in future to use Skin for such objects.  
I have also used AntiAlias effect so show smooth edges wherever required however I will recommend caution while using that because it will reduce drawing speed considerably.
I have also tested this application on Compact framework beta1 pocket pc (after removing some parts like gradient peg, Inset circle, AntiAlias effects etc) it works in same manner except some thing messes up in menu (may be its bug of beta1)  
Drawing Utility:  I have written some useful methods for drawing various object of games like pegs, Hole on board raised string etc in this class.

Asteroids in C#

Edited by C# Corner Editor
Summary
As my first experiment in a game design, rather than using a DirectX wrapper, I decided to explore the functionality of GDI+. GDI+ has lot of nice features to offer but performance wise it is slow. So GDI+ may not be a good idea to develop practical fast paced games. This game also includes sounds. 
Overview
The attached project contains three classes, one class for each object - SpaceShip, Asteroid, and Bullet.
These classes do have many common methods and properties so they could be inherited from the same base class.
The windows form object pulls all these classes together into the same playing field, handles collision detection and player interaction. Everything is treated on a tick by tick basis via the use of a timer object.
Installation
All source/compiled files and resources should be in the same directory.
Collision Detection
Simple use of a rectangle object that represents the space occupied by the object on the screen, using the "IntersectsWith" Method we can find if other rectangles overlap.
The next step is to use the pixel map of the image contained within the rectangle for more precise collision detection, this has been implemented using some 'unsafe' C++ which gives us direct access to the memory space for the images, where we can rapidly test pixel/byte by pixel/byte.
Physics
The physics model is pretty simplistic using thrust and inertia we calculate where the ship will be.
Sound
winmm.dll is imported using InteropServices and its PlaySound Method is used for in game sound.
Performance
Performance wise, you may not be happy with the game specially when you run the game in full screen mode.
The killer lines are in the form constructor:
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, 
true);
SetStyle(ControlStyles.DoubleBuffer, 
true);
The above code provide double buffering process which enhances the speed of drawing. The performance is worse if you comment the double buffering code. The Timer interval is 50 so refresh is about 20 fps.. maybe this could be less.
Conclusion
I hope you find this program useful and fun. I am planning to implement more features in this game. I would be very interested in hearing any comments on performance and alternative ways to handle display with GDI+. Please visit the forums at www.aurora-soft.co.uk

Eater Game Programming




Description 

This is a simple game written in C# in which the user moves a packman like player around the form and gobbles up red dots. The object is to get all the dots in as quick a time as you can. The design for the game is shown below:





Fig 2 - The UML for this game was reverse engineered using WithClass 2000
By examining the design, you can see that the eater game is not so difficult to understand because its simply a group of classes that are aggregates of the Form.

Each instance of class draws itself on the Form and the methods of the class are called from the form to exercise the class's behavior.  
The Sequence of Events is shown in the WithClass UML Diagram below after an arrow key to the right is pressed:


Fig 3 - Sequence of Events after a Right Key is pressed and the Eater hits a stone
The diagram above shows the flow of methods through the objects when a right arrow key is pressed and for those of you new to UML its known as a sequence diagram. The messages on the arrows map back to methods in the classes and each box with a vertical line represents an instance of the class in our Eater Game.
The code for the sequence above is shown below:
Listing 1 - KeyDown Event Handler
// KeyDown Event handled by the Formprivate void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{ 
// Invalidate the Eater before moving it string result = e.KeyData.ToString();
Invalidate(TheEater.GetFrame());
switch (result)
{
case "Left":// Move the Eater to the LeftTheEater.MoveLeft(ClientRectangle);
Invalidate(TheEater.GetFrame());
break;case "Right":// Move the Eater to the RightTheEater.MoveRight(ClientRectangle);
Invalidate(TheEater.GetFrame());
break;case "Up":// Move the Eater to the UpTheEater.MoveUp(ClientRectangle);
Invalidate(TheEater.GetFrame());
break;case "Down":// Move the Eater to the DownTheEater.MoveDown(ClientRectangle);
Invalidate(TheEater.GetFrame());
break;default:break;
} 
// Check to see if the Eater ate a stoneint hit = CheckIntersection();if (hit != -1)
{
// The Eater Ate a Stone, Increment the score, play a sound and remove the stoneTheScore.Increment();
PlaySoundInThread("hit.wav");
Invalidate(TheScore.GetFrame());
Invalidate(((Stone)Stones[hit]).GetFrame());
Stones.RemoveAt(hit);
// Check to see if the game is overif (Stones.Count == 0)
{
// Game is over , all the stones are eaten, show the time it took to eat themMessageBox.Show("You Win!\nYour time is " + TheTime.TheString + " seconds.");
Application.Exit();
}
}

In the Key Handler code above, each case of movement is handled for the Eater player.  If the Eater finds a stone, the score is incremented and a stone is removed.
Drawing of the stones, the eater, the score, and the timer is all handled by the each of the respective classes.  Below is the OnPaint method for the form to draw the board:
Listing 2 - Paining the Game Board
private
 void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
g.FillRectangle(Brushes.White, 0, 0, 
this.ClientRectangle.Width,
ClientRectangle.Height); 
// draw the scoreTheScore.Draw(g);// draw the timeTheTime.Draw(g, TheSeconds);// draw the stones for (int i = 0; i < Stones.Count; i++)
{
((Stone)Stones[i]).Draw(g);
} 
// also draw the eater TheEater.Draw(g);
}
Animation of the Eater is handled by using two bitmaps.  One bitmap has the eater with its mouth open,  the other with its mouth closed.  The Eater is drawn on the odd pixels with the mouth open and the even pixels with the mouth closed.  It also checks to see if it moved horizontally the last time or vertically.  This could probably be expanded to 8 images, two for each direction the eater moves in.
Listing 3 - Drawing the Eater
public void Draw(Graphics g)
{
Rectangle destR = 
new Rectangle(Position.X, Position.Y, EaterImage.Width, 
EaterImage.Height); 
Rectangle srcR = 
new Rectangle(0,0, EaterImage.Width, EaterImage.Height);// make it look like the mouth is movingif ( ((Position.X % 2 == 1) && ((Position.X - LastPositionX) != 0)) ||
((Position.Y % 2 == 1) && ((Position.Y - LastPositionY) != 0))
)
g.DrawImage(EaterImage, destR, srcR, GraphicsUnit.Pixel);
elseg.DrawImage(EaterImage2, destR, srcR, GraphicsUnit.Pixel);
LastPositionX = Position.X;
LastPositionY = Position.Y;
}

Invalidation
Back in the days when people were programming Macintoshes (remember the toolbox!), even before Windows 3.1 came into existence there was the concept of Invalidating regions of the window.  I must admit its not an intuitive concept, but seems to work well. The concept goes that when erasing and redrawing an area of the window,  you don't simply erase and redraw the area.  You "Invalidate" the part of the window you want redrawn.  This minimizes flicker in that area.  The actual drawing is done in the OnPaint Routine (Or Form1_Paint in this example).  Anotherwords you invalidate a rectangular region you want to redraw,  this forces the Form1_Paint to be called and go through the entire Form1_Paint routine.  Everything in Form1_Paint is executed, but only the area of the screen that you Invalidated is actually drawn.  In the Listing 1 Key Handler, the Eater area is first invalidated to erase the original position of the Eater and then the new area of where the eater is being drawn to after the move is invalidated.  The effect to the eye is that the eater is actually moving.  The eater can be made to "speed up" by increasing the increment at which the Position is changed when the key is being pressed.
Improvements
I was actually thinking of a few things that could be introduced to the game to give it more of a twist.  The game can be changed to have the timer time down and the score could be based on the number of stones eaten in that time.  A maze object could be introduced on the board to make it a little more challenging to get the stones.  Maybe a bullet object could be created to allow the eater to shoot at the stones.  Perhaps you'll see Eater II  or Super Eater in the near future ;-)

BattleShips Games

This application presents a grid of 100 squares to the user. The user has thirty five attempts to find to find the computers fleet. The computer randomly positions five ships of varying sizes around the board.
The board is made up of 100 buttons each uniquely numbered. They start sea-green indicating not selected. When selected the application checks if the area is occupied and turns red if unoccupied turns blue. The application also emits an explosion for a hit and a splash for a miss. It also recognizes a complete sinking by ringing the ships bell. On complete sinking of a ship it's corresponding ship indicator turns yellow.
After 35 attempts the application will show all missed squares by turning the squares yellow.


It uses the following......
wav files for all the sounds
Buttons for the squares
Random method to place the ships
Use manager to organise the squares
I have included the code and wav files in the following zip file (See attached file: BattleBoat.zip)
You will notice three classes - Battleship, GridManager and MainForm.
The Mainfrom is the entry point for the application. It initializes the application and controls play.
GridManager manages the grid. It adds the ships. Controls the current condition of the buttons.
Battleship - holds information about each ship. It tells the condition of the ship e.g. if it has sunk or wrecked etc, it holds the type, name and length of the ship
You might note I have used the random method twice before I assign the ship. This was the only way to ensure complete randomization. If I used it once then it seems to position the ships very close together.