Wednesday, February 17, 2010

Building a simple text editor using WinForms

I’ve been playing around with WinForms recently, and decided to try and put together a simple text editor. It’s pretty straightforward to do so here’s how!

Setting Up

First of all, open up and create a new WinForms project in Visual Studio. When it’s all ready to go, you’ll see a designer view and some controls in the toolbox to the left. Drag over two Buttons, a TextField, a Label and a RichTextField. These can all be found in the “All Windows Forms” section of the Toolbox.

form design

It’s always a good idea to give each of the components a name so right-click and choose “Properties”. The Properties window should show on the right and you can change the name of the control at the top and the text that appears on the control at the bottom of this window. Now that the Form has been designed, it’s time to start programming.

Creating a new text file

If you right-click on the “Save to File” and click on “View Code”, you’ll be taken to the Form1.cs class that sits behind the form. The highlighted method will be a click event for that button. Before we put the code on the click event, add the following to the using statement which allows us to read and write files:

using System.IO;




In the click event for the Save to File button, paste the following code:



String input = richTextBox.Text;
String newName = newFileName.Text;

try
{
StreamWriter sw = new StreamWriter("Path to the file"+newName+".txt", true, Encoding.ASCII);
sw.WriteLine(input);
sw.Close();
}

catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}


This code begins by specifying string variables used to take input from the TextBox and RichTextBox. Then inside the try block, it opens the StreamWriter and writes the path to wherever you would like to save the file and encodes it. After the text from the RichTextBox is written to the file, the StreamWriter is closed.  Finally, a catch block is used to detect any errors while writing to the file.



If you Build and Run now, you’ll be able to type and save a text file! Next thing is to read information from a file we just created.





Reading from a text file



First thing we need to do here is to open up the click event for the “Read From File” button (again right-click and choose “View Code”). Copy the following code into the method:




String line;
try
{
StreamReader sr = new StreamReader("Path to the text filet");
line = sr.ReadLine();
while (line != null)
{
richTextBox.Text = line;
line = sr.ReadLine();
}
sr.Close();
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}



This code starts by creating a string variable used to hold whatever text is taken from the file. Next we create a try block (again so we make sure any errors are dealt with properly) where a StreamReader object is created. The while loop is fairly straightforward; it reads the text from the file and puts it into the RichTextBox before reading in the next line. The StreamReader is then closed and finally the catch block takes care of any errors we might have.



If you run the program now you should be able to create a new text file and read back from it. A good way to extend this project further is to have a drop down list containing all of the created text files so the user can open one from there.



One thing to note is when you’re specifying the path to your text file, you’ll have to use double backslashes (\\) which acts as a reserved character in C#.



As always you can leave a message if you have any problems or issues.

Sunday, January 31, 2010

Wiimote and XNA Part 2 – Moving the Ship

The Wii Remote itself can only track two axes of rotation without using the Infra-red sensor bar. The CPU inside the little white box calculates these rotations and sends the data to the Wii (or in our case XNA) through Bluetooth so it can be used to calculate the movements of the objects on the screen. It’s because of this that we’re building our project on top of the Chase Camera sample I gave the link to in part 1. The Chase Camera sample is built in such a way that it uses a Vector2 object to hold rotations in the X and Y axes and so is perfect to use with the Wii Remote.


In the Ship class of the game, we’ve already put in the code to create and connect to a Wii Remote, now we’re going to use that Remote to move the ship around our world.
Inside the Update method, there is a list of declarations that allow the player to move the ship using the keyboard, just under here is where we’re going to put our Wii Remote code.
As we’re working with rotations, to move the ship left or right, the Wii Remote has to be “rolled”, and the if statements we’ll use check if this rolling has happened more than a certain degree. For simplicity sake, we’ll re-use the code in the game that moves the ship using the keyboard. It is possible to use the rotation of the Wii Remote itself but for this introduction tutorial I’d like to keep it as simple as possible.
Copy in the following code underneath the keyboard controls:

//Used to make the model go to the plus end of the X axis (->)
if (Wiimote.WiimoteState.AccelState.X > 0.09f)
{
rotationAmount.X = - 1.0f;
}
//Used to make the model go to the minus end of the X axis (<-)
if (Wiimote.WiimoteState.AccelState.X < -0.09f)
{
rotationAmount.X = 1.0f;
}
//Used to make the model go along the minus end of the Y axis (down)
if (Wiimote.WiimoteState.AccelState.Y < -0.09f)
{
rotationAmount.Y = 1.0f;
}
//Used to make the model go along the plus end of the Y axis (up)
if (Wiimote.WiimoteState.AccelState.Y > 0.09f)
{
rotationAmount.Y = - 1.0f;
}






Accessing the buttons of the Wii Remote is as easy as using an Xbox 360 controller in XNA. To show how this is done, find the piece of code that uses the space bar to make the ship fly forward. Here you can see how the KeyboardState object keeps track of changes to the keyboard buttons. The WiimoteLib’s button functions work in the exact same way. We can use this if statement to move the ship using the B button of the Wii Remote (which is the trigger on the back). The following code shows you how to do this:










if (keyboardState.IsKeyDown(Keys.Space)||
Wiimote.WiimoteState.ButtonState.B == true)
thrustAmount = 1.0f;









Now if you build and run the game, you’ll be able to fly around the world using the Wii Remote. Remember though, to move left and right the Remote has to be rolled to the left or right. Try and play around with the variables to see how different sensitivities can affect how the Remote works.








Feel free to leave a comment if you have any problems, I’ll try and help as best I can.

Friday, January 29, 2010

Wiimote and XNA Part 1 – Setting everything up

Today I’m going to write a fairly simple tutorial that shows you how to get a Wii Remote working with Microsoft XNA Game Studio. Before we dive into the code though, we have to run through some things that need to be set up.

Before we begin:

To get a Wiimote working with XNA, the computer you’re working from must be Bluetooth enabled. Most new laptops and PCs have this built in but if yours doesn’t, a cheap Bluetooth adapter (like this one) works just as well. Next is the Wiimote library we’re going to use. This one was developed by Brian Peek and is pretty sophisticated. The game we’ll be using to build on are available on this XNA Creators Club page.

Pairing the Wiimote and PC

The easiest way to pair a Wiimote and your PC is to download and install the BlueSoliel Bluetooth stack. A trial version of this software is available at bluesoliel.com. The BlueCove Bluetooth stack is also known to work and can be found here. If your using BlueSoliel, this site offers a fairly detailed tutorial on how to pair the controller to the PC. For BlueCove, a more general tutorial can be found here.

The Game itself

For the purposes of this tutorial I’m using the Going Beyond: XNA Game Studio in 3D, Tutorial 2. I’ve chosen this to base this tutorial on as it’s a fairly easy guide to follow if you’ve never done 3D or you can download the complete sample. When you’ve opened up the sample game, it’s time to add a reference to the WiimoteLib. This adds a dll file that contains all the functions of the library.

To add a reference to the WiimoteLib:

  1. Click on “Solution Explorer”
  2. Right-click on your solution
  3. Click “Add Reference”
  4. In the Add Reference window, click on the “Browse” tab and navigate to where you’ve downloaded and extracted the WiimoteLib folder.
  5. Click OK and the WiimoteLib should be visible under the “References” folder of the Solution Explorer.

Adding the dll file to the solution

With the library referenced in our project, it’s time to import the classes we need into our game. Under the pre-made using statements add the following line of code: using WiimoteLib; Now its time to initialize our Wii Remote!

Initializing the Wii Remote

In the main constructor of the Ship class pop in the following three lines of code:

public static Boolean useWiimote1 = true; public static WiimoteLib.Wiimote Wiimote = new WiimoteLib.Wiimote(); public static WiimoteLib.WiimoteState wiimoteState = new WiimoteLib.WiimoteState();

The above lines of code a fairly straight forward, a boolean is used to detect whether we want to use the Remote or not (if your game needs alternate game control methods etc), a new Wiimote object is created and a WiimoteState object is used to track changes. In the initialize method, an if statement is used to pass the Wiimote object to an initializeWiimote method we’ll write in a minute. Copy the following code into the Ship method(just under the Initialization region):

if (useWiimote1 == true){ InitWiimote(Wiimote); }

Next we’ll write the initializeWiimote method. This is the method that will actually communicate with the Wii Remote first when they’re trying to connect. The code for this method is shown below:

private void InitWiimote(WiimoteLib.Wiimote wm){




    wm.Connect();
wm.SetReportType(InputReport.ButtonsAccel, true);
wm.SetLEDs(true, false, false, false);
}



Using the Wiimote object we created earlier, this calls the connect method of the WiimoteLib. Then, the InputReport type is set to ButtonsAccel, meaning we’re taking accelerometer and button data. There are a couple of InputReport types (such as one that tracks Infra-red data or extensions such as a Nunchuck attachment) but the button and accelerometer data is all we need for the purpose of this tutorial. If you run the game with a Wii Remote connected, the screen will open with a spaceship model in the middle. Your Wii Remote should have the LED light on the far left lit up to show that it’s connected. With no Remote connected, you’ll see an error like the one below:Running the game with no Wii Remote attached



This is a good error to get as it means the game is trying to connect to a Wii Remote! Now it’s time to move on to part 2 and actually use the Wii Remote to have our ship fly around.

Thursday, January 28, 2010

Intro

Here we are at my shiny new blog. I’ve decided to start one so I can write about any projects I’m working on, cool bits of technology I’ve tried (or read about online) and little snippets of code I think would be useful.

For my first proper post tomorrow I’ve decided to do a little tutorial based on my graduate project. It’ll show you how to get a Nintendo Wii Remote working in Microsoft’s XNA Game Studio. The work is based on the Managed Library for the Nintendo Wii Remote by Brian Peek (you can read his blog posts here).

For other uses for the Wii Remote, Johnny Chung Lee has made some pretty cool things (like a head tracker and an interactive whiteboard). You can read all about his projects here.