The Snake Eyes Game


Snake eyes is a simple dice game, where you roll a pair of dice trying not to get two 1's (a combination known as, you guessed it, snake eyes!) If you throw any combination other than two 1's, then your total is increased by the value currently shown on the two dice and you roll again. You keep rolling, increasing your score, until two 1's come up, when you 'lose', and your score is set back to 0.

Knowing how the game works gives you an idea of what you need to do. It's always worth thinking about this before you dive in and start coding, as it's always easier to create pages when you've a good idea of what you need. In our page, there needs to be a way to represent the dice, and a way to simulate the roll. There also needs to be some way to keep score. As you build the game, you'll see how we use the controls and code to accomplish this.

Creating the User Interface

The interface for this game is going to be quite simple. To represent our two dice, we'll be using ASP.NET Label controls, as it's easy to display numbers using these controls. In the next chapter we'll look at the Image control and show how to substitute the labels for pictures of the dice. We'll also need to add a button, to simulate the throwing of the dice. All in all, it's pretty simple.

Try It Out—Creating the User Interface

  1. Start the ASP.NET Web Matrix. If the Add New File dialog isn't showing, you need to display it using one of the following methods:

    • From the toolbar, by selecting the New File button (the one that looks like a sheet of notepaper)

    • From the menu, by selecting File then New

    • By selecting a directory in the Workspace, right-mouse clicking and selecting Add New Item…

  2. From this dialog, make sure (General) is selected from the Templates list, and select ASP.NET Page from the list on the right.

    click to expand

  3. Pick a suitable directory into which you're going to store the file. I've picked C:\BegWebMatrix, but you can choose any directory on your system.

  4. Make sure the Language is Visual Basic .NET, change the file name to Dice.aspx, and press the OK button.

  5. Click on the page and type the page title, which is Snake Eyes!:

    click to expand

  6. Since this is the title, we want it to stand out more, so, using the cursor, select the text. When the text is highlighted, select Heading 1 from the style list on the formatting toolbar:

    click to expand

    This formats the selected text, just like using the formatting in a word processor:

    click to expand

  7. Now, place the cursor at the end of this line of text and press Return, then type
    the following:

    Keep going, but don't get two 1's... 
  8. Press Return again, then drag two Label controls onto the form from the Web Controls section of the Toolbox:

    click to expand

  9. These are the labels that will represent the dice, so we want to format them to make them look a bit more like dice, and less like text. As in most other Microsoft products, you can select multiple items by holding down the Ctrl key and clicking on the items you wish to select. The second label is already selected, so holding down Ctrl, select the first label as well (just click it once with the left mouse button) – this will allow us to apply the same properties to both labels simultaneously.

  10. Now go to the Properties window, and change the following (note that to access specific font properties, you need to expand the Font properties group within the Properties window by clicking on the + icon):

    Property

    Value to use

    BorderStyle

    Solid

    Font: Name

    Verdana

    Font: Size

    X-Large

    Height

    44px

    Text

    0

    The labels should now look like this:

  11. Now, back in the design view, click to the right of these labels, press Return to place the cursor on the next line below these labels. Add another Label control, changing the Text property to:

    Ooops, you did it again :(

    and the Visible property to False:

  12. Back in the design view, place the cursor after this label, press Return again, and add a Button to the page, changing the Text property to:

    Hit me baby one more time...

  13. Finally, we need one more label, underneath the button. Press Return again and drag on another label, setting the following properties:

    Property

    Value to use

    Font:Name

    Verdana

    Font: Size

    X-Large

    ForeColor

    Red

    Text

    0

That's it for the design of this page, so let's have a look at exactly what Web Matrix has done for us.

How It Works

In the previous chapter, we saw how the page designer has several tabs. The one we've been working with is the Design view, allowing us to use easy drag-and-drop features to add controls to a form. It also allows us to use toolbars to format text, in exactly the same way we'd use a word processor. All of these features are just an easy way of creating HTML, the language of the web page – after all, that's what our web browser is going to display. One of the great features of Web Matrix is that it's a visual design tool, so we get to see what the page looks like as we design it. We also have a Properties window that enables us to change properties on our controls, without having to learn what this really means in HTML.

Let's just have a quick look and see exactly what has been created, and then you'll really see how much easier the designer is to work with than hand-coding HTML. If you click the HTML view tab, what you see is the following code:

 <html> <head> </head> <body>  <form runat="server">  <h1>Snake Eyes!   </h1>  <p>  Keep going, but don't get two 1's...   </p>  <p>  <asp:Label  runat="server" BorderStyle="Solid"  Height="44px" Font-Names="Verdana"  Font-Size="X-Large">0</asp:Label>  <asp:Label  runat="server" BorderStyle="Solid"  Height="44px" Font-Names="Verdana"  Font-Size="X-Large">0</asp:Label>  </p>  <p>  <asp:Label  runat="server">  Ooops, you did it again :(</asp:Label>  </p>  <p>  <asp:Button  runat="server"  Text="Hit me baby one more time..."></asp:Button>  </p>  <p>  <asp:Label  runat="server" Font-Names="Verdana"  Font-Size="X-Large" ForeColor="Red">0</asp:Label>  </p>  <!-- Insert content here -->  </form> </body> </html> 

It won't look quite like this as I've made it a bit neater to make it easier to read on the page, but the content is the same. The important point is that the WYSIWYG (What You See Is What You Get) designer lets you see what the page will look like as you design it, while underneath it's creating all of this HTML for you. It's certainly much simpler to work in design view than to write all of this code by hand!

Adding the Code

As it stands this page doesn't do anything; it's simply a visual interface with no interactive elements. Let's add some code to get this game going.

Try It Out—Adding the Code

  1. Switch back to design view, and select the Button control.

  2. Now double-click your mouse button, to switch to code view for this Button control.

  3. Add the following highlighted lines of code (this code will run every time the button
    is clicked):

    Sub Button1_Click(sender As Object, e As EventArgs)  Label3.Visible = False  Label1.Text = Int(Rnd() * 6) + 1  Label2.Text = Int(Rnd() * 6) + 1  If Label1.Text = "1" And Label2.Text = "1" Then  Label4.Text = 0  Label3.Visible = True  Else  Label4.Text = CInt(Label4.Text) + _  CInt(Label1.Text) + CInt(Label2.Text)  End If End Sub
  4. Now save the file and press F5 to run the page – you'll be shown the following dialog:

    click to expand

    This gives you the choice of running the page using the ASP.NET Web Matrix Web Server, or via an already configured Virtual Root. Just leave it set to the first option, and press the Start button. The Web Matrix Web Server is started and the page runs:

  5. Press the button a few times and see how the dice 'roll', and the score is increased:

    Keep going until you get two 1's on the dice (this may take some time – I got up to over 700 before this happened to me!):

    Notice how the score has been reset, and our hidden label has now appeared.

How It Works

Let's look at how this code works. We'll be looking at code in more detail in Chapters 4, 5, and 6, so we won't go into a great deal of detail on the structure. However, it's really important to examine how we can set the properties in code – this way you can see how what you do to the code affects the properties you set in the Property window.

First off, let's see the code in its entirety:

Sub Button1_Click(sender As Object, e As EventArgs)   Label3.Visible = False   Label1.Text = Int(Rnd() * 6) + 1   Label2.Text = Int(Rnd() * 6) + 1   If Label1.Text = "1" And Label2.Text = "1" Then     Label4.Text = 0     Label3.Visible = True   Else     Label4.Text = CInt(Label4.Text) + _                   CInt(Label1.Text) + CInt(Label2.Text)   End If End Sub

Notice that all of the code is within the Sub ... End Sub lines. This means that we have created a subroutine, sometimes known as a procedure. We'll look at these in detail in Chapter 4. Since this procedure was created by double-clicking the button, the code will only run when the button is clicked. Clicking the button when the page is running is called an event, and the procedure that runs when an event happens is called the event procedure. This means that we can have several buttons on page, each with its own bit of code (event procedure), and the procedures keep these bits of code separate. We're going to modify this game a little later and you'll see how this works.

OK, let's look at the code in detail, taking it line by line. The first thing we do is set the Visible property of Label3 to False, which means the label won't be shown on the page:

Label3.Visible = False

This is exactly the same as setting the Visible property in the Properties window – remember how we did that earlier when put the label on the page and changed its properties? "But hang on", I hear you say, "you already did then when you set the properties in design view – why do it again?" The difference is that when setting a value for a property at design time, that's the value the property will have unless it's changed in code. "Yeah, but why change it in code to the same value it's already got?" you argue. Well, later in the code we might be changing this property to True, thus making the label visible. This will happen when you lose a game. Once a game is lost you can start another one by simply pressing the button, and when starting a new game we don't want the label to be shown. So that's why we make it invisible – if we've lost a game and are starting a new one.

Next we need to roll the dice. We have two dice, represented by Label1 and Label2, so we need to set the Text property on these labels to the values of the dice:

Label1.Text = Int(Rnd() * 6) + 1 Label2.Text = Int(Rnd() * 6) + 1

This looks a bit complex, but it's actually quite simple. Each line of code produces a random number between 1 and 6, and places the resulting values in the labels we are using to simulate the dice. The dice roll actually does the following:

  • Rnd() produces a random number greater than or equal to 0, but less than 1.

  • We multiply that by 6, so it is now greater than equal to 0, but less than 6.

  • We use Int to convert it to an integer. This means that numbers with decimals, such as 4.32 become rounded to a whole number (in this particular example, we end up with 4).

  • We add 1 to our result to bring it within the range 1 to 6.

Once we've got the two values for the dice we need to see if two 1's have been rolled, because that's what determines a lost game. The values of our dice are stored in the Text property of our two labels, so we examine this property to see if they are both equal to "1".

If Label1.Text = "1" And Label2.Text = "1" Then

If they are both 1, then the game is over. We reset the score to 0, and show the 'you lose' message in the third label control by setting its Visible property to True.

    Label4.Text = 0     Label3.Visible = True

If it's not a losing throw, then we need to add the scores on the dice to the current score. To do this, we use a Visual Basic .NET function called CInt, which converts a string value into a number (converting a text representation of a number to a number the computer can work with as a number). Don't worry too much about this – Chapter 5 will explain all about this sort of thing. For the moment, all you need to know is that we are adding the dice values to the score:

Else     Label4.Text = CInt(Label4.Text) + _                   CInt(Label1.Text) + CInt(Label2.Text) End If

Label4 contains the current score, and Label1 and Label2 the values on the dice.

That's all there is to the code. It may look a little complex, and some of it may be confusing (especially if you haven't done any programming before), but be patient. Just revel in the fact that you've written your first ASP.NET web page. Go on. Sit back and feel smug. Feels good doesn't it? OK, you've still got lots to learn, but there's plenty of time.

Remembering Information

Before we get into more about pages, let's do some more to this game, as there is at least one thing wrong with it. The problem is that when you lose a game, the score is immediately reset to 0, so you can't see what score you did get before the losing roll. What we need is a way to remember the score, and possibly a high score too. Let's give it a go.

Try It Out—Saving the Scores

  1. Make sure you are in the design view for the web page (just hit the Design tab if not).

  2. Select the score label, and from the Edit menu select Copy. You can also just press Ctrl-C, or use Copy from the menu that appears if you click the right mouse button on this label. We want our scores to all look the same, so rather than adding new labels and setting the font and color, we'll just copy the existing score label.

  3. Add some text under the score label, saying:

    Last Score:

  4. Now, from the Edit menu select Paste (or press Ctrl-V). This pastes a copy of the score label, and gives it a new name (Label5) and saves us having to do the formatting.

  5. Now add more text underneath that:

    High Score:

  6. Now paste another copy of the score label. This will be called Label6. Your page should now look like this:

    click to expand

    We now need to add some more code to deal with these scores. Save the page before continuing (frequent saving is always a good idea with any product, but especially with a technology preview such as the Matrix!)

  7. Switch to Code view by clicking on the Code tab, and modify the code adding in the following highlighted lines:

      Label3.Visible = False   Label1.Text = Int(Rnd() * 6) + 1   Label2.Text = Int(Rnd() * 6) + 1   If Label1.Text = "1" And Label2.Text = "1" Then  Label5.Text = Label4.Text  If CInt(Label5.Text) > CInt(Label6.Text) Then  Label6.Text = label5.Text  End If     Label4.Text = 0     Label3.Visible = True   Else     Label4.Text = CInt(Label4.Text) + _             CInt(Label1.Text) + CInt(Label2.Text)   End If 
  8. Save the file and press F5 again to rerun the program. This time you'll notice that we have two new labels. Keep playing for a while and watch how they work:

    click to expand

How It Works

Let's see how this works. Remember that we have two new labels – Label5 is for recording the last score, and Label6 is for the high score.

The first thing we do if a game is over is to keep a copy of the current score. This is stored in Label4, so we copy that to Label5:

Label5.Text = Label4.Text

Now we want to see if this score is bigger than the current high score (which is 0, when the game starts). So, we use the CInt function again, to convert our scores into numbers, allowing us to compare them programmatically. Here we see if the current score (Label5) is greater than the high score (Label6). If it is, then we simply replace the high score with the current score.

If CInt(Label5.Text) > CInt(Label6.Text) Then   Label6.Text = label5.Text End If 

You can see that, not only is creating a web page simple, but modifying it is too. It's easy to add controls to a page, and to change existing code. But what about adding new code? Remember how we said earlier that the code for the button is kept separate from any other code? Let's give this a go, just to see how it's done – we'll add another button that resets our high scores.

Try It Out—Reset the High Score
  1. Make sure you are in the Design view for the page (just hit the Design tab if not).

  2. Add another button underneath the high score, and change its Text property to:

    Reset High Scores

  3. Double-click the button to view its code, and add the following:

    Sub Button2_Click(sender As Object, e As EventArgs)  Label6.Text = 0 End Sub
  4. Save the page and run it again. Play the game until you get a high score, and then reset it by clicking the new button. Notice that only the high score is reset, and nothing else happens.

How It Works

Actually, how it works is something you really don't need to worry about too much at this stage. We'll be covering this in more detail in later chapters. For now, all you have to remember is that, if you have a button, and an event procedure for that button, then the code for each button is separate, and only run when that button is pushed. You'll see this technique used often in ASP.NET web pages, and there will be plenty of examples of this as we work through the book.




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net