Computer Science Teacher
Computer Science Teacher - Thoughts and Information from Alfred Thompson

May, 2011

  • Computer Science Teacher - Thoughts and Information from Alfred Thompson

    XNA and Visual Basic–Your First Lesson

    • 3 Comments

    image

    I have been playing with Visual Basic and XNA for a few days now. Support has been out for VB and XNA for a little while now but the release of the Windows Phone Developer Tools 7.1 Beta and a new document on Visual Basic Support in XNA Game Studio (Mango) has really kicked me into trying it out. As much as I like C# Visual Basic has long been my language of choice for programming for fun.  So after I wrote my first VB game for Windows Phone (Windows Phone 7 Games in Visual Basic) I decided to jump a step back (sideways?) to Windows gaming and an old standby – Pong. Pong is sort of a “Hello World” for game development. So where do you start? Well the first thing you need to know is that there are four and a half methods that you absolutely have to write code for to create an XNA game.

    • Initialize – Set the initial state. Basically get everything ready in a known stable configuration.
    • LoadContent – Bring the images, sound files and any other “content” into the running program.
    • Update – Make work happen. Do stuff. This is the main game loop generally.
    • Draw – Once everything is set draw the pictures and make things appear on the screen.

    The half? Well you are probably going to need to declare some variables at the class level so you can get at them from the various methods. For our pong game we’ll need several variables – for the paddles, the ball, the images we will draw and some variables for keep track of things like random numbers and what is happening with the way the user interacts with the game.  We’ll want to create this game to work with or without Xbox game controllers so we want to track the keyboard as well as controllers.

    Private WithEvents graphics As GraphicsDeviceManager
    Private WithEvents spriteBatch As SpriteBatch
     
    Dim t_paddle1 As Texture2D
    Dim t_paddle2 As Texture2D
    Dim t_ball As Texture2D
     
    Dim paddle1 As Paddle
    Dim paddle2 As Paddle
    Dim ball As Ball
     
    Dim rand As New Random()
    Dim currentState As KeyboardState
    Dim currentPad As GamePadState

    You’ll note that we have two variables of type Paddle and one of type Ball. This is to help us control those objects better and we’ll look at the code for them a little further on down the post. For now let us look at Initialize.

    Protected Overrides Sub Initialize()
     
        ResetGame()
     
        MyBase.Initialize()
    End Sub

    I’ve added a call to ResetGame to the Initialize method that Visual Studio created for us when we told it we wanted a Windows XNA game project. By having the reset game code in a separate method (subroutine) we can reuse it other places if and when appropriate. The purpose is to set all the variables to a known state like so:

    Private Sub ResetGame()
        paddle1 = New Paddle(10, 200)
        paddle2 = New Paddle(770, 200)
        ball = New Ball(385, 285)
    End Sub

    We’re just creating new instances of paddles and a ball and placing them at specific locations. The Constructor for the classes helps us out here.

    Now let us look at loading the content. In this case we need texture(or image) files for the paddles and the ball.  We’ll have added the image files (you can borrow these two images that I borrowed from Sam Stokes Smile Save them as Ball.png, paddle1.png and paddle2.png)

    ballpaddle1paddle2

    Protected Overrides Sub LoadContent()
        ' Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = New SpriteBatch(GraphicsDevice)
     
        t_paddle1 = Content.Load(Of Texture2D)("paddle1")
        t_paddle2 = Content.Load(Of Texture2D)("paddle2")
        t_ball = Content.Load(Of Texture2D)("ball")
     
    End Sub

    Now let’s do some work in Update.

    Protected Overrides Sub Update(ByVal gameTime As GameTime)
        ' Allows the game to exit
        If GamePad.GetState(PlayerIndex.One).Buttons.Back = ButtonState.Pressed Then
            Me.Exit()
        End If
     
        UpdateBall()
        UpdatePaddles()
        CheckCollisions()
     
     
        MyBase.Update(gameTime)
    End Sub

    Once again I have used method calls to keep things simple, organized and easier to maintain. Now for what those methods look like. First things first – move the ball. What we are doing here is changing the X and Y locations of the ball on the screen. We want to make sure it bounces off the bottom. We will check for collisions with the paddles and going off the screen later.

    Private Sub UpdateBall()
        'update positions
        ball.pos.X += ball.h_speed
        ball.pos.Y += ball.v_speed
     
        'check for boundaries
        'bottom
        If ball.pos.Y > (Window.ClientBounds.Height - 10 - t_ball.Height) Then
            ball.v_speed *= -1
        End If
     
        'top
        If ball.pos.Y < 10 Then
            ball.v_speed *= -1
        End If
    End Sub

    In update paddles I am checking both the game controllers (looking for two of them) and the keyboard. I am using the W (for up) and X (for down) keys to controll the paddle on the left and the up and down arrow keys to controll the paddle on the right.

    Private Sub UpdatePaddles()
     
            'get keyboard keys
            currentState = Keyboard.GetState()
            Dim currentKeys As Keys() = currentState.GetPressedKeys()
            'check for up and down arrow keys
            For Each key As Keys In currentKeys
                If key = Keys.Up Then
                    paddle2.pos.Y -= paddle2.speed
                End If
                If key = Keys.Down Then
                    paddle2.pos.Y += paddle2.speed
                End If
                If key = Keys.W Then
                    paddle1.pos.Y -= paddle1.speed
                End If
                If key = Keys.X Then
                    paddle1.pos.Y -= paddle1.speed
                End If
                If key = Keys.Escape Then
                    Me.[Exit]()
                End If
            Next
     
     
            'get controller information
            currentPad = GamePad.GetState(PlayerIndex.One)
     
            'check for up and down arrow keys
            If currentPad.Triggers.Left > 0.0 Then
                paddle1.pos.Y -= paddle1.speed
            End If
     
            If currentPad.Triggers.Right > 0.0 Then
                paddle1.pos.Y += paddle1.speed
            End If
     
            currentPad = GamePad.GetState(PlayerIndex.Two)
     
            'check for up and down arrow keys
            If currentPad.Triggers.Left > 0.0 Then
                paddle2.pos.Y -= paddle2.speed
            End If
     
            If currentPad.Triggers.Right > 0.0 Then
                paddle2.pos.Y += paddle2.speed
            End If
     
     
     
            'check boundaries
            If paddle1.pos.Y <= 10 Then
                paddle1.pos.Y = 10
            End If
            If paddle2.pos.Y <= 10 Then
                paddle2.pos.Y = 10
            End If
     
            If paddle1.pos.Y + t_paddle1.Height >= Window.ClientBounds.Height - 10 Then
                paddle1.pos.Y = Window.ClientBounds.Height - t_paddle1.Height - 10
            End If
            If paddle2.pos.Y + t_paddle2.Height >= Window.ClientBounds.Height - 10 Then
                paddle2.pos.Y = Window.ClientBounds.Height - t_paddle2.Height - 10
            End If
        End Sub

    The last thing we do in Update is to check for collisions. Now that the paddles and the ball are in new locations are there any two in the same or overlapping locations?

    Private Sub CheckCollisions()
           'check paddle1 if ball moving left, else check paddle2
           If ball.h_speed < 0 Then
               'check if ball has surpassed paddle
               If ball.pos.X < paddle1.pos.X + 20 Then
                   'check if ball has hit paddle or went through
                   If (ball.pos.Y + t_ball.Height < paddle1.pos.Y) OrElse (ball.pos.Y > paddle1.pos.Y + t_paddle1.Height) Then
                       'LOST!
                       ResetGame()
                   Else
                       'ball hit - calculate new speeds
                       'speed of ball changes randomly - 3 to 6
                       If ball.h_speed < 0 Then
                           ball.h_speed = rand.[Next](3, 7)
                       Else
                           ball.h_speed = rand.[Next](-6, -2)
                       End If
     
                       If ball.v_speed < 0 Then
                           ball.v_speed = rand.[Next](3, 7)
                       Else
                           ball.v_speed = rand.[Next](-6, -2)
                       End If
                   End If
               End If
           Else
               'check if ball has surpassed paddle
               If ball.pos.X + t_ball.Width > paddle2.pos.X Then
                   'check if ball has hit paddle or went through
                   If (ball.pos.Y + t_ball.Height < paddle2.pos.Y) OrElse (ball.pos.Y > paddle2.pos.Y + t_paddle2.Height) Then
                       'LOST!
                       ResetGame()
                   Else
                       'ball hit - calculate new speeds
                       'speed of ball changes randomly - 3 to 6
                       If ball.h_speed < 0 Then
                           ball.h_speed = rand.[Next](3, 7)
                       Else
                           ball.h_speed = rand.[Next](-6, -2)
                       End If
     
                       If ball.v_speed < 0 Then
                           ball.v_speed = rand.[Next](3, 7)
                       Else
                           ball.v_speed = rand.[Next](-6, -2)
                       End If
                   End If
               End If
           End If
       End Sub

    If you read through there carefully you will notice that we are calling ResetGame if the ball escapes the right or left boundary of the screen. Code reuse at its finest!

    Now let’s draw things!

    Protected Overrides Sub Draw(ByVal gameTime As GameTime)
        GraphicsDevice.Clear(Color.CornflowerBlue)
     
        spriteBatch.Begin()
        spriteBatch.Draw(t_paddle1, New Rectangle(paddle1.pos.X, paddle1.pos.Y, t_paddle1.Width, t_paddle1.Height), Color.White)
        spriteBatch.Draw(t_paddle2, New Rectangle(paddle2.pos.X, paddle2.pos.Y, t_paddle2.Width, t_paddle2.Height), Color.White)
        spriteBatch.Draw(t_ball, New Rectangle(ball.pos.X, ball.pos.Y, t_ball.Width, t_ball.Height), Color.White)
        spriteBatch.[End]()
     
        MyBase.Draw(gameTime)
    End Sub

    The spriteBatch tool is helpful here.

    That is the game code. We do need our classes for the ball and paddles though. Here is the ball class. We locate the ball at a specified position passed via the constructor and we select a random speed and direction. This is a fun area to play with the make the game harder or easier BTW.

    Public Class Ball
        'position of ball
        Public pos As Point
        Public h_speed As Integer, v_speed As Integer
     
        'constructor - position
        Public Sub New(x As Integer, y As Integer)
            pos = New Point(x, y)
     
            Dim rand As New Random()
            h_speed = rand.[Next](3, 7)
            If rand.[Next](0, 2) = 0 Then
                h_speed *= -1
            End If
     
            rand = New Random()
            v_speed = rand.[Next](3, 7)
            If rand.[Next](0, 2) = 0 Then
                v_speed *= -1
            End If
        End Sub
     
    End Class

    Now for the paddles. We et a location in the constructor and specify a speed. Now I am not suggesting that you change the constructor to all the program to set a speed. An unscrupulous programmer night use that to set the speed of the two paddles differently giving one player an edge. Not that I would ever do such a thing of course. But it is a thought.

    Public Class Paddle
        'position of paddle
        Public pos As Point
        Public speed As Integer
     
        'constructor - position
        Public Sub New(x As Integer, y As Integer)
            pos = New Point(x, y)
            speed = 6
        End Sub
     
    End Class

    This is about the most simple Pong game you can create of course. I’d love to see what others do with it. Perhaps create something completely different or perhaps just add scoring and sound or who knows what. Let me know if you do something with it. Thanks.



  • Computer Science Teacher - Thoughts and Information from Alfred Thompson

    Windows Phone 7 Games in Visual Basic

    • 3 Comments

    I’ve been working all week in C#. Now C# is a wonderful language if you are going to use semi-colons and curly braces. It fixes almost all of the issues I have with C++ and Java. But frankly I have missed the beauty of programming in Visual Basic. So when I saw Sam Stokes’ post (You can now use Visual Basic on Windows Phone 7 to do XNA development-) I knew it was time to take a VB break. So I got the document on Visual Basic Support in XNA Game Studio (Mango) and installed the Windows Phone Developer Tools 7.1 Beta and I went to town. Well actually what I did was to convert my C# Whack Something Game into Visual Basic. Hey I had to start somewhere. I’m going to rewrite it from scratch and do it right soon. Hopefully over the Memorial Day weekend if the “honey do” list is not too long. But for now here is a step by step illustrated with some code (not great code but it works) instruction on creating your first Windows Phone 7 Game in Visual Basic. BTW Pong in VB and XNA for Windows is here.

    Fire Drill Project

    We will be creating a game that causes “flames” to randomly appear on your screen. By touching the flames you will put them out. But beware! More flames will appear.

    Open Visual Studio and select New Project from the File menu. You should get a window that looks something like this:

    clip_image002

    Select Windows Phone Game (4.0) and give you project a name such as FireDrill and press the OK button.

    On the Solution Explorer right click on the Content option and either select Add -> Existing Item or press Shift-Alt-a to open the file window. Browse to where the image files are and select x.png and flame.png.

    clip_image004

    clip_image006

    You can save the flame and X image from here and use them BTW.xflame Just save them with the right file names and extension.

    Now that we have the images we need it is time to start writing some code. We need several variables:

    • · Textures to identify the images
    • · Rectangles to hold the images and help with detection of touches.
    • · Flags to determine what images are being displayed
    • · Some counters to help control how often “fires” pop up.
    • · A random number variable to make things more random

    Our code might look something like this:

     

    Dim aFire As Texture2D, bFire As Texture2D, xButton As Texture2D
    Dim aRec As Rectangle, bRec As Rectangle, xRec As Rectangle
    Dim aShow As [Boolean], bShow As [Boolean]
    Dim r As Random
    Dim cycleCount As Integer, howOften As Integer

    This lines go in the top of the class right below the lines:

     

    Private WithEvents graphics As GraphicsDeviceManager
    Private WithEvents spriteBatch As SpriteBatch

    We’ll see how these are used in a minute. But we also have to initialize there variables. We’ll set the Booleans for aShow and bShow to false so that they are not displayed right away when the program loads. We’ll use howOften to determine how many frames to show before deciding to show or not show one of the fires. The default FPS (frames per second) for a Windows Phone is about 33 frames per second so if we wait every 30th frame that will be just about a second. We’ll change that randomly as the program runs to make things less predictable.

    We’ll also set the initial locations of our two flames, the X (for eXit) button and initialize our counters and random number variable. Out code will be in the Initialize method and look something like this:

     

    aRec = New Rectangle(100, 100, 47, 50)
    bRec = New Rectangle(700, 300, 47, 50)
    aShow = False
    bShow = False
    xRec = New Rectangle(0, 400, 64, 64)
    r = New Random()
    cycleCount = 0
    howOften = 30

    Our images are going into what we call 2D textures and we’ll bring them in from the files in the LoadContent method. Notice that we use the same file for both flames that wiil appear.

     

    aFire = Me.Content.Load(Of Texture2D)("flame")
    bFire = Me.Content.Load(Of Texture2D)("flame")
    xButton = Me.Content.Load(Of Texture2D)("x")

    We draw these textures in the Draw method – you saw that coming didn’t you? Each frame we will redraw the objects on the screen of our phone using the spriteBatch object. We will first check our Boolean flags (remember aShow and bShow) and if they are set to true they will be drawn. The X button will always be drawn of course.

     

    graphics.GraphicsDevice.Clear(Color.AliceBlue)
    spriteBatch.Begin()
    If aShow Then
        spriteBatch.Draw(aFire, aRec, Color.AliceBlue)
    End If
     
    If bShow Then
        spriteBatch.Draw(bFire, bRec, Color.AliceBlue)
    End If
    spriteBatch.Draw(xButton, xRec, Color.AliceBlue)
     
    spriteBatch.[End]()

    Note that we are using the same color for the background of the screen and of the objects we are drawing on it (AliceBlue in this case) to make things look nice. For “interesting” try different colors.

    Now for the real work. What we want to happen is for “flames” to appear in random places on the screen. When we touch them with our finger that will “put them out.” This means that we have to:

    • · Exit the game if the player touches the X button
    • · Make a flame disappear (by setting the show flag to false)
    • · Determine if it is time to show one or more flames
    • · Set the location of one or both flames and display them by setting the show flag to true

    We check for touching the button or flames by checking touch points against the rectangles that define the locations of the objects. The status of the TouchPanel tells us where it was touched.

    Our code may look something like this:

     

    For Each t As TouchLocation In touches
        Dim touchRec As New Rectangle(CInt(t.Position.X), CInt(t.Position.Y), 1, 1)
     
        If touchRec.Intersects(xRec) Then
            Me.[Exit]()
        End If
        If touchRec.Intersects(aRec) AndAlso aShow Then
            aShow = False
        End If
        If touchRec.Intersects(bRec) AndAlso bShow Then
            bShow = False
        End If
    Next

    We’ll count the cycles and if enough have passed (according to HowOften) we will select one or both of the flames to appear using a set of if statements. If it is “time” we will use the random number variable to select a location for the flame(s) to appear, set the show flag to true, reset our cycle counter and pick a new random number of cycles before checking again. Our code might look like the following:

    Dim shouldShow As Integer = r.[Next](1, 100)
    cycleCount += 1
    If cycleCount > howOften Then
        If shouldShow < 60 Then
            aShow = True
            aRec.X = r.[Next](100, 700)
            aRec.Y = r.[Next](10, 400)
        End If
        If shouldShow > 50 Then
            bShow = True
            bRec.X = r.[Next](100, 700)
            bRec.Y = r.[Next](10, 400)
        End If
        howOften = r.[Next](33, 100)
        cycleCount = 0
    End If

    If you don’t have a Windows Phone yet make sure the deployment is set for the emulator.

    clip_image007

    If everything works you should see something like this:

    clip_image009

    The emulator uses mouse clicks to emulate touches unless you have a touch screen on your computer.

    What next?

    Well some things are obvious:

    • · More flames
    • · Score keeping
    • · Losing or winning
    • · Code clean up – shouldn’t there be classes here?

    You get the idea. What can you do from this basic outline?

    clip_image010

    Visit the App Hub at http://create.msdn.com/en-US for more Windows Phone development resources.

    © 2010 Microsoft Corporation. All rights reserved. This document and its contents are provided AS IS without warranty of any kind, and should not be interpreted as an offer or commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information presented. The information in this document represents the current view of Microsoft on the content.

    MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED, OR STATUTORY, AS TO THE INFORMATION IN THIS DOCUMENT.



  • Computer Science Teacher - Thoughts and Information from Alfred Thompson

    US Teams in the Worldwide Imagine Cup Finals 2011

    • 0 Comments

    The Worldwide finalists for all categories of the Imagine Cup are out and you can read all of the amazing projects at the Imagine Cup Blog. There are 124 teams from 73 countries and regions making their way to New York City this July.  With projects ranging from helping provide better drinking water worldwide to addressing disease and disaster relief, these students are changing the world.  I’m a little biased of course and I am seriously routing for the US teams who I have listed below. Teams in Software Design, Windows Phone development, game design (two teams in different sub categories) and a really cool project in the Embedded Development category. We’re looking good! 

    Team

    School

    Category

    Project

    Note-Taker

    Arizona State University

    Software Design

    A portable device that helps visually-impaired students by utilizing a touch-based tablet connected to a camera that shows the whiteboard on one half of the screen and allows notes to be taken on the other half.

     

    Syntax Errors

    Santiago Canyon College

    Embedded Development

    This self-contained mobile workstation based on an embedded RTOS platform and managed code application allows emergency workers to track assets such as medical suppliers, water, food, and personnel in real time during emergency relief efforts.

     

    Lifelens

    UCLA, University of California, Davis, Harvard, University of Central Florida

    Windows Phone 7

    Lifelens is an innovative point-of-care tool to diagnose malaria using an augmented mobile smartphone application. The project addresses the unacceptably high child mortality rates caused by the lack of detection and availability of treatment of malarial diseases

    Dragon

    Rice University

    Game Design (Windows/Xbox)

    Azmo the Dragon is a game that helps children learn about their asthma as they play as a dragon who destroys civilizations.

    ICsquared

     

    Ithaca College

    Game Design (Web)

    The project aims at inspiring players to take real world actions. The main part of the game focuses on recycling rubbish, gathering experience and taking quests.

    No matter where in the world you are from though you can probably leave words of encouragement for finalists from your part of the world on the Microsoft Imagine Cup Facebook wall!

    • This year, students registered from 183 countries.
    • We have finalists from countries ranging from New Zealand to Nigeria and Ukraine to the United Kingdom.
    • One of the interesting regions well represented among those international teams is the Middle East – with teams from Iraq, Pakistan, Egypt, Cyprus, Tunisia and more.
    • The Worldwide Finals will be in New York City, July 8-13, the first time ever in the United States.

    And if you are staying for day three of the CSTA CS & IT Conference you can be a big part of our final day celebration with a lot of surprises beyond just the chance to meet some world changing students.



Page 2 of 9 (27 items) 12345»