Search This Blog

WPF Game 1


Here, just did one small game for my wife and my baby with their photos( That's the reason they happy).

WPF , VS2010,Microsoft Expression Blend 4, InstallAware Studio Admin 9, I used.
Also I doing Silverlight 4 edition at the same time.




For Algorithm the core codes like below:


////////////////////////////////////////////////////////////////////////
//
// Kai Zhou Copyright (C) 2010
//
// created date : 2010-7-15
// developer : Kai Zhou
//
//
////////////////////////////////////////////////////////////////////////

using System;
using System.Net;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
//using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using System.IO;
using System.Diagnostics;
namespace GuoGuoGo.Bll
{
public class Engine
{

public const int LevelCount = 7;

public static Size ItemSize = new Size(36,36);

static int SelectedCount = 0;
private static string starPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
enum ItemDer
{
LineX,
LineY,
LTRB,
LBRT
};


public static Point MaxBackGridSplits
{
get
{
return new Point(12, 8);
}
}

static Pojo.ImgItem CurSelectedItem = null;


static double ItemCount //= Config.SLConfig.BackGridSplits.X * Config.SLConfig.BackGridSplits.Y;
{
get;
set;
}

public delegate void ItemLinked(Pojo.ImgItem item);
public static event ItemLinked ItemLinkedHanlder;


public static int CurLevelIndex
{
get;
set;
}


public static Grid GameBackGrid
{
get;
set;
}



public static Pojo.GameLevel CurLevel = null;


public static Pojo.ImgItem[][] AllItems
{
get;
set;
}

public delegate void delegateRefreshGrid();
public static event delegateRefreshGrid RefreshGridHanlder;


///
public delegate void delegateItemCompleted(Pojo.GameLevel level);
public static event delegateItemCompleted GameCompletedHanlder;


public static void InitEngine()
{
ClearItemsCach();
}

public delegate void delegateSetLevel();
public static event delegateSetLevel SetLevelEventHanlder;


public static void SetLevel(int level)
{
int TotalScore = 0;
if (CurLevel != null) TotalScore = CurLevel.Score;

if (level == 0) level = 1;
else if (level > LevelCount)
{
TotalScore = 0;
}


CurLevel = new GuoGuoGo.Pojo.GameLevel();
CurLevel.Level = level;
CurLevel.BackGridSplits = MaxBackGridSplits;
CurLevel.Score = TotalScore;


//int imgIndex = Config.SLConfig.AllGameLevelImages.Length < itemimages =" new" i =" 0;" imagesource =" new" itemcount =" CurLevel.BackGridSplits.X" selectedcount =" 0;" showgridlines =" false;" i =" 0;" cd =" new" width =" new" i =" 0;" rd =" new" height =" new" width =" CurLevel.BackGridSplits.X" height =" CurLevel.BackGridSplits.Y"> CreatedItems = new List();
Random rand = new Random();

for (int i = 0; i < index =" rand.Next(CurLevel.ItemImages.Length" item =" new" itemimg =" CurLevel.ItemImages[index];" item2 =" new" itemimg =" item.ItemImg" i =" 0;" x =" (int)(i" y =" (int)(i" index =" rand.Next(CreatedItems.Count" item =" CreatedItems[index];" location =" new" background =" GameBackGrid;" curselecteditem =" null;"> lastItems = GetExistsItems();
if (lastItems.Count == 0)
{
FillGrid();
return;
}
//ClearItemsCach();
Random rand = new Random();



if (lastItems.Count <= 0) return; for (int x = 0; x < y =" 0;" index =" rand.Next(lastItems.Count" item =" lastItems[index];" item =" new" itemimg =" item.ItemImg" location =" new" background =" GameBackGrid;" score =" 0;" allitems =" new" i =" 0;"> GetExistsItems()
{
List list = new List();
for (int i = 0; i < x =" (int)(i" y =" (int)(i" curselecteditem =" null;">= ItemCount)
{

if (GameCompletedHanlder != null) GameCompletedHanlder(CurLevel);
}

}
else
{
if (CurSelectedItem != null)
{
CurSelectedItem.CnacelSelect();
}
item.Select();
CurSelectedItem = item;
return true;
}

return false;
}






public static bool IsCanLink(Pojo.ImgItem item1, Pojo.ImgItem item2)
{

if (item1.ItemImg != item2.ItemImg || item1 == item2) return false;

ItemDer itemder = GetItemDer(item1, item2);
switch (itemder)
{
case ItemDer.LineX:
{
return CheckLineX(item1, item2);
}
case ItemDer.LineY:
{
return CheckLineY(item1, item2);
}
case ItemDer.LTRB:
{
return CheckLTRB(item1, item2);
}
case ItemDer.LBRT:
{
return CheckLBRT(item1, item2);
}
}
return false;
}



private static bool CheckLineX(Pojo.ImgItem item1, Pojo.ImgItem item2)
{

if (CheckInPointsIsEmpty(item1.Location, item2.Location, ItemDer.LineX) || (item1.Location.Y == 0 && item2.Location.Y == 0) ||
(item1.Location.Y == CurLevel.BackGridSplits.Y - 1 && item2.Location.Y == CurLevel.BackGridSplits.Y - 1))
{
return true;
}


for (int i = (int)item1.Location.Y - 1; i >= 0 ; i--)
{
Point p1=new Point(item1.Location.X, i);
Point p2=new Point(item2.Location.X, i);

if (!CheckPointIsEmpty(p1) || !CheckPointIsEmpty(p2)) break;

if (CheckInPointsIsEmpty(p1, p2, ItemDer.LineX))
{
return true;
}

if (i == 0)
{
return true;
}
}


for (int i = (int)item1.Location.Y + 1; i <= CurLevel.BackGridSplits.Y - 1; i++) { Point p1 = new Point(item1.Location.X, i); Point p2 = new Point(item2.Location.X, i); if (!CheckPointIsEmpty(p1) || !CheckPointIsEmpty(p2)) break; if (CheckInPointsIsEmpty(p1, p2, ItemDer.LineX)) { return true; } if (i == CurLevel.BackGridSplits.Y - 1) { return true; } } return false; } private static bool CheckLineY(Pojo.ImgItem item1, Pojo.ImgItem item2) { if (CheckInPointsIsEmpty(item1.Location, item2.Location, ItemDer.LineY) || (item1.Location.X == 0 && item2.Location.X == 0) || (item1.Location.X == CurLevel.BackGridSplits.X - 1 && item2.Location.X == CurLevel.BackGridSplits.X - 1)) { return true; } for (int i = (int)item1.Location.X - 1; i >= 0; i--)
{
Point p1 = new Point(i, item1.Location.Y);
Point p2 = new Point(i, item2.Location.Y);

if (!CheckPointIsEmpty(p1) || !CheckPointIsEmpty(p2)) break;

if (CheckInPointsIsEmpty(p1, p2, ItemDer.LineY))
{
return true;
}

if (i == 0)
{
return true;
}
}


for (int i = (int)item1.Location.X + 1; i <= CurLevel.BackGridSplits.X - 1; i++) { Point p1 = new Point(i, item1.Location.Y); Point p2 = new Point(i, item2.Location.Y); if (!CheckPointIsEmpty(p1) || !CheckPointIsEmpty(p2)) break; if (CheckInPointsIsEmpty(p1, p2, ItemDer.LineY)) { return true; } if (i == CurLevel.BackGridSplits.X - 1) { return true; } } return false; } private static bool CheckLTRB(Pojo.ImgItem item1, Pojo.ImgItem item2) { if (item1.Location.X > item2.Location.X)
{
Pojo.ImgItem itemtmp = item1;
item1 = item2;
item2 = itemtmp;
}


for (int i = (int)item2.Location.X - 1; i >= 0; i--)
{
Point p1 = new Point(i, item2.Location.Y);
Point p2 = new Point(i, item1.Location.Y);

if (!CheckPointIsEmpty(p1))
{
break;
}

if (p2 != item1.Location && !CheckPointIsEmpty(p2))
{

if (i < i ="="" i =" (int)item1.Location.X" p1 =" new" p2 =" new"> item2.Location.X)
{
break;
}
continue;
}

if (CheckInPointsIsEmpty(p2, item2.Location, ItemDer.LineX) && CheckInPointsIsEmpty(p1, p2, ItemDer.LineY))
{
return true;
}

else if (i == CurLevel.BackGridSplits.X - 1)
{
return true;
}
}


for (int i = (int)item2.Location.Y - 1; i >= 0; i--)
{
Point p1 = new Point(item2.Location.X,i);
Point p2 = new Point(item1.Location.X,i);

if (!CheckPointIsEmpty(p1))
{
break;
}

if (p2 != item1.Location && !CheckPointIsEmpty(p2))
{

if (i < i ="="" i =" (int)item1.Location.Y" p1 =" new" p2 =" new"> item2.Location.Y)
{
break;
}
continue;
}

if (CheckInPointsIsEmpty(p2, item2.Location, ItemDer.LineY) && CheckInPointsIsEmpty(p1, p2, ItemDer.LineX))
{
return true;
}

else if (i == CurLevel.BackGridSplits.Y - 1)
{
return true;
}
}

return false;
}


private static bool CheckLBRT(Pojo.ImgItem item1, Pojo.ImgItem item2)
{

if (item1.Location.X > item2.Location.X)
{
Pojo.ImgItem itemtmp = item1;
item1 = item2;
item2 = itemtmp;
}


for (int i = (int)item2.Location.X - 1; i >= 0; i--)
{
Point p1 = new Point(i, item2.Location.Y);
Point p2 = new Point(i, item1.Location.Y);

if (!CheckPointIsEmpty(p1))
{
break;
}

if (p2 != item1.Location && !CheckPointIsEmpty(p2))
{

if (i < i ="="" i =" (int)item1.Location.X" p1 =" new" p2 =" new"> item2.Location.X)
{
break;
}
continue;
}

if (CheckInPointsIsEmpty(p2, item2.Location, ItemDer.LineX) && CheckInPointsIsEmpty(p1, p2, ItemDer.LineY))
{
return true;
}

else if (i == CurLevel.BackGridSplits.X - 1)
{
return true;
}
}


for (int i = (int)item1.Location.Y - 1; i >= 0; i--)
{
Point p1 = new Point(item1.Location.X, i);
Point p2 = new Point(item2.Location.X, i);

if (!CheckPointIsEmpty(p1))
{
break;
}

if (p2 != item2.Location && !CheckPointIsEmpty(p2))
{

if (i < i ="="" i =" (int)item2.Location.Y" p1 =" new" p2 =" new"> item1.Location.Y)
{
break;
}
continue;
}


if (CheckInPointsIsEmpty(p2, item1.Location, ItemDer.LineY) && CheckInPointsIsEmpty(p1, p2, ItemDer.LineX))
{
return true;
}

else if (i == CurLevel.BackGridSplits.Y - 1)
{
return true;
}
}

return false;
}


private static bool CheckInPointsIsEmpty(Point p1, Point p2,ItemDer iDer)
{

if (iDer == ItemDer.LineX)
{

if (Math.Abs(p1.X - p2.X) == 1 || (p1.X - p2.X) == 0)
{
return true;
}


int offsetx = (int)(p1.X - p2.X);

if (offsetx < i =" 1;" i =" 1;" ider ="="" y ="="" offsety =" (int)(p1.Y" i =" 1;" i =" 1;" x ="="" y ="=""> 0)
{
return ItemDer.LTRB;
}
else
return ItemDer.LBRT;
}

#endregion
}
}





How to build a voice controlled Web browser



Yes, a voice controlled Web browser.
After vista and Win 7 released, we all know about speech recognition API. From the movie -Iron man, he got a cool robot as big toy. I think it is voice controlled toy , low A.I robot. I want one!!!!
Here I will show you how to create your own web browser with C#, forget about IE, Firefox, Chrome, etc. a voice controled one.
Today, first step, I will show your how to build a typical one, a window form web browser, next one I will show you the WPF edition, and then I will put the voice control function in.

Now I post the core function here, I don't show you how to drag the drop the button and so on because that's too easy for you. OK, Here is the code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace JinGangInternet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Navigate(this.textBox1.Text);
}

private void BackToolStripMenuItem_Click(object sender, EventArgs e)
{
webBrowser1.GoBack();
}

private void ForwardToolStripMenuItem_Click(object sender, EventArgs e)
{
this.webBrowser1.GoForward();
}

private void StopToolStripMenuItem_Click(object sender, EventArgs e)
{
webBrowser1.Stop();
}

private void RefreshToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!webBrowser1.Url.Equals("about:blank"))
{
webBrowser1.Refresh();
}
}

private void MainPageToolStripMenuItem_Click(object sender, EventArgs e)
{
webBrowser1.GoHome();
}

private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
webBrowser1.ShowSaveAsDialog();
}

private void PrintToolStripMenuItem_Click(object sender, EventArgs e)
{
webBrowser1.ShowPrintDialog();
}

private void ProperityToolStripMenuItem_Click(object sender, EventArgs e)
{
webBrowser1.ShowPropertiesDialog();
}

private void webBrowser1_CanGoBackChanged(object sender, EventArgs e)
{
this.BackToolStripMenuItem.Enabled = webBrowser1.CanGoBack;
}

private void webBrowser1_CanGoForwardChanged(object sender, EventArgs e)
{
this.ForwardToolStripMenuItem.Enabled = webBrowser1.CanGoForward;
}

private void webBrowser1_DocumentTitleChanged(object sender, EventArgs e)
{
this.Text = webBrowser1.DocumentTitle;
}

private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
this.textBox1.Text = webBrowser1.Url.ToString();
}

private void Navigate(String address)
{
if (String.IsNullOrEmpty(address)) return;
if (address.Equals("about:blank")) return;
if (!address.StartsWith("http://")) address = "http://" + address;
try
{
webBrowser1.Navigate(new Uri(address));
}
catch (System.UriFormatException)
{
return;
}
}

private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.CanGoBackChanged += new EventHandler(webBrowser1_CanGoBackChanged);
webBrowser1.CanGoForwardChanged += new EventHandler(webBrowser1_CanGoForwardChanged);
webBrowser1.DocumentTitleChanged += new EventHandler(webBrowser1_DocumentTitleChanged);
this.webBrowser1.Navigated += new WebBrowserNavigatedEventHandler(this.webBrowser1_Navigated);
}
}
}

That's all for form1, next time I will show you cool WPF edition.

WPF project about convert XML to text file




I was working on a small WPF project. As some of people already know Pronto, this ERP suite
can not deal with Web service unless integrated with .NET , the P.I.E , but it cost money for license from Pronto.
So I made this WPF program for one of our clients. They will run this on their server 24/7 and once the XML file achieved from their Kiosks to their server, this program will change the XML file to txt file with right data format; then copy the txt file to another fold for process; Or transfer to our pronto server to process. At the end of process, the retailer POS will get the all data.

O.k easy one.

The IDE is VS2010, UI designed with Blend 3. No SQL server used here, user customize saved with ini file, was tried app.config, but it is easy to read, for write , it is not safe even sometimes works, runtime issue. LinQ used for XML date query. typical 3.5 project. MVVM .

The core part is muti-thread, so the famous backgroundWorker would be best choice for this
long time running program.
this.backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker_DoWork);
this.backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker_RunWorkerCompleted);
this.backgroundWorker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker_ProgressChanged); this.backgroundWorker.WorkerSupportsCancellation = true;
this.backgroundWorker.WorkerReportsProgress = true;


There are a lot of good example on the net about backgroundWorker thread, it is a great and very useful thing. What I did with my project is the Asynchronous one. But one thing these article didn't mentioned about is how to make the the cancel method works. Normally people start coding will still got no responding error after hit the cancel button. The tip is you need return your long time run process thread with a string to your dowork. That will fix the problem.
You won't find this with MSDN, trust me, when you do this part , you will know what I mean.

For long time process, your can use file watcher, but still got some thread not access issue, so what I am use is like this.
namespace ProcessFiles
{
class Program
{
private bool ProgramRunning = true;
private int FilesHandled = 1;

static void Main(string[] args)
{
Program prog = new Program();
prog.ReadDirectoryThread();
}

private void ReadDirectoryThread()
{
while (this.ProgramRunning)
{
DirectoryInfo DirInfo = new DirectoryInfo(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\incoming\\");

foreach (FileInfo FInfo in DirInfo.GetFiles("*.xml"))
{
Thread t = new Thread(new ParameterizedThreadStart(ProcessFile));
t.Start(FInfo.FullName);
while (t.ThreadState != System.Threading.ThreadState.Stopped)
{
//Thread.Sleep(5);
}
}

}
}

void ProcessFile(object FileToProcess)
{
string sFile = FileToProcess.ToString();
bool isProcessed = false;

// File processing
try
{
sFile = "*.xml";
// Process your file here. Convert the XML file to text file
//TransformXML();
// Loading from a file, you can also load from a stream
//XDocument loaded = XDocument.Load(sFile);

//// create a writer and open the file
//TextWriter tw = new StreamWriter("XmltoCSV.txt");

// Query the data and write out a subset of contacts
var contacts = from c in loaded.Descendants("CONTACT")
select new
{
FirstName = (string)c.Element("FIRSTNAME"),
LastName = (string)c.Element("LASTNAME"),
City = (string)c.Element("CITY"),
State = (string)c.Element("STATE"),
Country = (string)c.Element("COUNTRY")
};

foreach (var contact in contacts)
{
string s = contact.FirstName + "," +
contact.LastName + "," +
contact.City + "," +
contact.State + "," +
contact.Country;

// write a line of text to the file
tw.WriteLine(s);
}

// close the stream
tw.Close();

}
catch
{
return;
}

// After the file is processed, we move it
while (!isProcessed)
{
try
{
string ProcessedFilesDir = string.Format("{0}\\processed\\{1}_{2}.txt", Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss"), Guid.NewGuid().ToString());
File.Move(sFile, ProcessedFilesDir);
Console.WriteLine(FilesHandled + " - File " + sFile.ToString() + " processed\n");
FilesHandled++;
}
catch
{
isProcessed = false;
}
finally
{
isProcessed = true;
}
}
}
void TransferFile(object FileToTransfer)
{
// write the transfer part here like Secured FTP
}


}
}

As you can see this sample code is a console one, but it is easy change to any Windows form or WPF one, also for the LinQ XML query part you can use XSLT as well, could be another good solution.

For the customize part, easy one, ini file.

public void IniWriteValue(string Section, string Key, string Value, string filepath)
{
WritePrivateProfileString(Section, Key, Value, filepath);
}

public string IniReadValue(string Section, string Key, string filepath)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp,
255, filepath);
return temp.ToString();

}

O.k that's all. Next time I will put the the program on the Google code, that will make sense.
And finally I got some time to updated my blog. That's wonderful.