PHP Game Programming 2004 phần 4 pdf

38 364 0
PHP Game Programming 2004 phần 4 pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

98 Chapter 5 ■ Operators, Statements, and Functions See how the value of $someNum changed? Its value is the result from the operations inside the function. Passing variables by reference is a very handy way to return results for mul - tiple variables because a function can return only one value if you are using the return keyword. Recursion PHP functions also support recursion. Recursion is simply when a function calls itself. One of the easiest ways to explain recursion is just to show you; take this, for example: function power($base, $exponent) { if($exponent) { return $base * power($base, $exponent - 1); } return 1; } Notice how the return statement is calling the power function, but it is subtracting one from the variable $exponent every time it is called. Eventually $exponent will hit zero and the if statement will not execute. At this point is when the recursion ends. Take an in-depth look at how this works. echo(power(2,3)); 1. The function power is called with the base set to 2 and the exponent set to 3. 2. Next, the $exponent is tested; since it is non-zero it succeeds and proceeds to the next line. 3. The return statement calls the power function again, except this time the base is 2 and the exponent is also 2. 4. The $exponent variable is tested again. It is still a non-zero value. 5. Power is called again with the value 2 as the base and 1 as the exponent. 6. The exponent variable is tested again; it is still a non-zero value. 7. Power is called a final time with the value 2 as the base and 0 as the exponent. 8. This time the test fails and the function returns 1 to the third invocation of the function. 9. 1 is now multiplied by the base and the third invocation of the function returns 2 to the second invocation of the function. 99 The Magic of Including Files 10. 2 is now multiplied by the base value, giving us 4, and 4 is returned to the first invocation of the power function. 11. 4 is now multiplied by the base, giving us the final value of 8, and 8 is returned from the power function back to your program. Pretty confusing, huh? Recursion can be a nasty beast but you can do some pretty cool things with it. The Magic of Including Files Now that you have all this cool knowledge about how to make functions, you need a way to include libraries (so to speak) in your PHP pages. Basically what you can do is make a file full of common functions that you use all the time and put them in all of your games. For instance, if you take a look at the CD, I have included a PHP file (common.php) that has some base functions that will be used in all of the games in this book. PHP gives you two ways to include files in your application. You can use the require state- ment or the include statement. When the PHP interpreter encounters the require state- ment it puts the file in the code and it is now generally available to your page. The include statement evaluates and executes the code each time the include statement is encountered. This allows you to have dynamic includes in your files. For example: for($loopCounter = 0; $loopCounter < 5; $loopCounter++) { include(“file” . $loopCounter . “.php”); } If you did the above example with the require statement, then the only file that would be included would be file4.php. Instead of worrying about which one is better I would just always use the include statement. There is no performance hit and you can be a lot more flexible in your coding. Note PHP assumes the include files are in the directory specified by the include_path directive in the php.ini file. If your include files are not in this directory you need to specify the full path along with the filename to include it. 100 Chapter 5 ■ Operators, Statements, and Functions Conclusion You have covered a ton of information in this chapter. You now know all about operators and how to control the flow of your code with sound logic. You also know how to create blocks of reusable code using functions. You even know how to make a mini-library and include it in all of your PHP pages. Next up: arrays, and then your first PHP game! Arrays, Games, and Graphics Chapter 6 Arrays! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103 Chapter 7 Playing with Chess and Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . .133 Chapter 8 GD Graphics Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .157 Chapter 9 Creating Battle Tank and Using Dynamic Terrain . . . . . . . . . . . . . . . .193 PART III This page intentionally left blank chapter 6 Arrays! ■ Initializing Arrays ■ Using Strings for Indexes ■ Looping through Sequential Arrays ■ Looping through Non-Sequential Arrays ■ Multi-Dimensional Arrays ■ Sorting Arrays ■ Your First PHP Game I n Chapter 4, when you were making the form processing example, the check boxes were named nEquipmentID[] . Those two brackets mean that it is an array. An array consists of several elements, each of which has a value. You can access each element in the array by using an index. In PHP your index can be either an integer or a string, which allows a lot of flexibility in your code. Note As in C/C++, arrays in PHP are zero based, meaning that the first index in the array starts at 0. Take a look at Figure 6.1. This representation should make it clear how an array stores its data. 103 104 Chapter 6 ■ Arrays! $board[0] $board[1] $board[2] $board[3] "A" "B" "C" "D" Figure 6.1 How an array stores data. In this case the array is named $board , and it has four elements. The first element of the array, $board[0] , is equal to “A”. The second element of the array, $board[1] , is equal to “B,” and so on. So how do you create arrays? Initializing Arrays There are several ways that you can initialize arrays. You could simply list the variable with the value you would like to add to the array, like this: $board[] = “A”: $board[] = “B”: $board[] = “C”: $board[] = “D”: Because you did not specify an index, the elements are automatically added in sequential order. You could have also specified what index you would like the element to appear in, like this: $board[0] = “A”: $board[1] = “B”: $board[5] = “C”: $board[7] = “D”: This is more impractical, but valid all the same. Usually when assigning elements to an array you should do it in a sequential order. This way there is no confusion about where the element is. However, there are times when you will want to create a hash key and use that for your index. If you ever assign items in a non-sequential order and then later add an element to the array without specifying the index it should appear in, then the element will be automat - ically added to the next highest index. For example: $board[0] = “A”: $board[1] = “B”: Using Strings for Indexes 105 $board[60] = “C”: $board[] = “D”: // “D” would be added to index 61, not 2. The final way to declare an array is to use the array() function. You simply pass the values you want in the array as parameters to the function. $board = array(“A”, “B”, “C”, “D”); This will create an array exactly like the first example did. “A” is the first element in the array with an index of 0. “B” is the second element in the array with an index of 1, and so on. If you wish to change the index of an element using the array() function, you can do so like this: $board = array(1 => “a”, “b”, 7 => “c”, “d”); In the example above, “a” will be at index 1, “b” will be located at index 2, “c” will be located at index 7, and “d” will be located at index 8. You can put the => operator before any element of the array to change its index. Using Strings for Indexes As mentioned earlier in this chapter, you can use strings as indexes into your arrays. The global variable _SESSION in PHP uses strings as its indexes. The syntax for accessing an array that uses strings as an index looks like this: _SESSION[“gTurn”]; Creating an array that uses strings for an index is very simple. Recall the first example I used to initialize an array with elements in a specific index. $board[0] = “A”: $board[1] = “B”: $board[5] = “C”: $board[7] = “D”: Instead of using an integer as an index you would simply replace it with a string, as the following example demonstrates: $board[“element1”] = “A”: $board[“element2”] = “B”: $board[“element3”] = “C”: $board[“element4”] = “D”: 106 Chapter 6 ■ Arrays! You can also use the => operator along with the array() function to create an array with strings as indexes. $board = array(“element1” => “A”, “element2” => “B”, “element3” => “C”, “element4” => “D”); If you use strings as indexes into your array, you have to access the array with the speci- fied string indexes. In other words, if you typed in the following code: <?php $board = array(“element1” => “A”, “element2” => “B”, “element3” => “C”, “element4” => “D”); echo($board[“element1”]); echo($board[0]); ?> You would get an error when the PHP interpreter tried to print the last line, echo($board[0]”) , that looks like Figure 6.2. Looping through Sequential Arrays The easiest way to loop through sequential arrays is to use the for loop. I know you are probably thinking, “How do I know how many elements are in the array?” You can access Figure 6.2 Trying to access a string-indexed array with an integer. Looping through Sequential Arrays 107 the number of elements in the array by using the count() function. Your for loop should look like the following: <?php $board = array(“a”, “b”, “c”, “d”); for($index = 0; $index < count($board); $index++) { // Print each element on its own line echo(“Index = “ . $index . “, Element = “ . $board[$index] . “<BR>”); } ?> First you initialize your array with all the elements you need. Then, in the first statement of the for loop, you initialize your indexing variable ( $index ). The second statement of the for loop is your Boolean expression. This tells the loop when to stop; in this case the for loop will stop when it reaches one less than the total number of elements in the array $board . Why don’t you specify to stop when the loop reaches the total count of the ele- ments? Because you have to remember that PHP uses a starting index of zero for arrays. If you went to the total count of the elements you would get an error when you tried to print the value because that index does not exist in the array. The third and final statement of the for loop simply increments the indexing variable every time the loop restarts. The results should look like Figure 6.3. Figure 6.3 Results of looping through a sequential array. [...]... $_POST[‘dlDifficulty’]; EndGame(); $gGameState = GAME_ START; StartGame(); } if($gGameState == GAME_ START) { StartGame(); } // Check to see if the user is starting a new game if($_POST[‘btnNewGame’] != “”) { EndGame(); $gGameState = GAME_ START; StartGame(); } As you can see, a switch statement is used to determine the state of the game You also may have noticed that there is not a state for the game starting; this... if(CheckFull() == 1) { $gGameState = GAME_ OVER; Render(); return; } // Draw the board DrawBoard(); break; } case GAME_ WIN: { EndGame(); printf(“”); break; } case GAME_ OVER: { EndGame(); printf(“”); break; } } // Update our game state $_SESSION[‘gGameState’] = $gGameState; } Your First PHP Game if($_POST[‘dlDifficulty’]... need is four game states The first of the four states is to tell you when the game is starting, the second lets you know when the game is in play, the third tells you if someone has won the game, and the fourth and final state tells you if someone has lost the game // Includes include(“common .php ); // Game States define( GAME_ START”, 0); define( GAME_ PLAY”, 1); define( GAME_ WIN”, 2); define( GAME_ OVER”,... 123 1 24 Chapter 6 ■ Arrays! The StartGame() and EndGame() functions control the session variables The StartGame() function creates all the variables that will be stored in the session and changes the game state to play The EndGame() function simply unsets all the variables and destroys the active session function StartGame() { global $gGameState; global $gBoard; if($gGameState == GAME_ START) { $gGameState... level $gDifficulty = $_SESSION[‘gDifficulty’]; } function EndGame() { global $gGameState; global $gBoard; $gGameState = GAME_ OVER; unset($gBoard); Your First PHP Game unset($gGameState); unset($turn); session_destroy(); } The first lines of the StartGame() function tell it that the function will use global variables Then the function changes the game state and starts the session Starting the session creates... CheckWin(), check to see if the board is full or if someone has won the game Your First PHP Game function CheckFull() { global $gGameState; global $gBoard; $gGameState = GAME_ OVER; for($iLoop = 0; $iLoop < count($gBoard); $iLoop++) { if($gBoard[$iLoop] == “”) { $gGameState = GAME_ PLAY; return 0; } } return 1; } function CheckWin() { global $gGameState; global $gBoard; $player = 1; while($player    ... == $tile && $gBoard [4] == $tile && $gBoard[8] == ‘’) $computerMove = 8; if($gBoard[0] == $tile && $gBoard [4] == ‘’ && $gBoard[8] == $tile) $computerMove = 4; if($gBoard[0] == ‘’ && $gBoard [4] == $tile && $gBoard[8] == $tile) $computerMove = 0; if($gBoard[2] == $tile && $gBoard [4] == $tile && $gBoard[6] == ‘’) $computerMove = 6; Your First PHP Game if($gBoard[2] == $tile && $gBoard [4] == ‘’ && $gBoard[6] . the middle of your page. Your First PHP Game Now it’s time to program your first game in PHP! You will start off with a simple game of tic-tac-toe. This game will use all the aspects that you. know how to make a mini-library and include it in all of your PHP pages. Next up: arrays, and then your first PHP game! Arrays, Games, and Graphics Chapter 6 Arrays! . . . . . . . . . . you take a look at the CD, I have included a PHP file (common .php) that has some base functions that will be used in all of the games in this book. PHP gives you two ways to include files in

Ngày đăng: 12/08/2014, 21:21

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan