1. Trang chủ
  2. » Công Nghệ Thông Tin

PHP Game Programming 2004 phần 4 pdf

38 366 0

Đ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

Thông tin cơ bản

Tiêu đề PHP Game Programming 2004 phần 4
Trường học Unknown University
Chuyên ngành PHP Programming
Thể loại Giáo trình
Năm xuất bản 2004
Thành phố Unknown City
Định dạng
Số trang 38
Dung lượng 545,16 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

■ Initializing Arrays ■ Using Strings for Indexes ■ Looping through Sequential Arrays ■ Looping through Non-Sequential Arrays ■ Multi-Dimensional Arrays ■ Sorting Arrays ■ Your Fi

Trang 1

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)

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

Trang 2

99

invocation of the power

from the power

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

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

N o t e

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

Trang 3

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!

Trang 6

chapter 6

A rrays!

■ Initializing Arrays

■ Using Strings for Indexes

■ Looping through Sequential Arrays

■ Looping through Non-Sequential Arrays

■ Multi-Dimensional Arrays

■ Sorting Arrays

■ Your First PHP Game

In 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

N o t e

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

Trang 7

$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?

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”:

Trang 8

Using Strings for Indexes

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(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:

Trang 9

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”,

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

Trang 10

Looping through Sequential Arrays

the number of elements in the array by using the count() function Your for loop should look like the following:

// 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 ments? Because you have to remember that PHP uses a starting index of zero for arrays

ele-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

Trang 11

Looping through the array with a for loop is perfect, as long as you know that the array is zero-based and ordered sequentially So how do you loop through an array that is not ordered sequentially?

Looping through Non-Sequential Arrays

This is a perfect time to use a while loop Of course, you will be using the while loop in conjunction with three other functions: reset(), list(), and each() The reset function sets the current index of the array back to the first element available It takes one argument, and that is the array that you would like to reset

The results of the example above appear exactly like Figure 6.3, even though the indexes

in this particular array are not in a sequential order Calling the reset() function in this example is quite unnecessary because, since the array has just been created, the current index is obviously the first available element But it is good practice to get into, because you might end up trying to loop through an array and it could be starting in the middle

of it, and that would be no good

Trang 12

Looping through Non-Sequential Arrays

PHP also offers several other functions to operate on arrays, such as current(), key(), next(), and prev() to name just a few For a complete list of functions that PHP supports, please refer to Appendix B Take a look at the following example and Figure 6.4 to see what the key() and current() functions do:

N o t e

Key and index mean exactly the same thing; the function in PHP is called key() instead of index()

Figure 6.4 An example of the key() and current() functions

Trang 13

Earlier I mentioned next() and prev() These two functions are another way to navigate through an array As you might imagine, next() goes to the next available index in the array, and returns the element prev() does the same thing but instead of going to the next available index, it goes to the previous index Take a look at the following loop:

Trang 14

Multi-Dimensional Arrays

exactly how you create multi-dimensional arrays in PHP You make an array that holds an array

<?php

$board = array(“Row1” => array(“a”, “b”), “Row2” => array(“c”, “d”, “e”));

echo($board[“Row1”][0]); // Prints “a”

echo($board[“Row2”][2]); // Prints “e”

?>

One great use for multi-dimensional arrays is that you can represent a game board using

a two-dimensional array Then each position in the game board, at say location e1, would hold a value that would tell you if there is a piece at that square or not Or you could use

a loop, like in the following example, to print the game board:

“&nbsp;”, “&nbsp;”, “&nbsp;”),

array(“&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”,

“&nbsp;”, “&nbsp;”, “&nbsp;”),

array(“&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”,

“&nbsp;”, “&nbsp;”, “&nbsp;”),

array(“&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”, “&nbsp;”,

“&nbsp;”, “&nbsp;”, “&nbsp;”),

Trang 15

Figure 6.5 Results of looping through a multi-dimensional array

Sorts arrays in alphabetical order

Sorts arrays in alphabetical order without changing indexes

Sorts arrays in reverse order

Sorts arrays in reverse order without changing indexes

Sorts arrays by key values

Sorts arrays by key values in reverse order

A customizable sort function that keeps string indices

A customizable sort function that sorts by key

*A complete list of PHP functions is available in Appendix B

Trang 16

Sorting Arrays

Now take a closer look at each of these sorting functions The sort() function sorts the ments in the array by numeric and then alphabetical order Numbers come first, then punctuation marks, and finally letters While the function is sorting, it reassigns the indexes to reflect the new order

ele-<?php

$items = array(“Sword”, “Medpac”, “Advanced Medpac”,

“Armor”, “Blaster”, “Shotgun”);

echo(“Index = “ $index “, “ $items[$index] “<BR>”);

}

echo(“Index = “ $index “, “ $items[$index] “<BR>”);

}

?>

The results of this example should look like Figure 6.6

Figure 6.6 The sort() function in action

Trang 17

Take a look at what happens when you have an array with specified indexes when you use the sort function

<?php

$items = array(“Item1” => “Sword”, “Item2” => “Medpac”, “Item3” => “Advanced Medpac”,

“Item4” => “Armor”, “Item5” => “Blaster”, “Item6” => “Shotgun”);

// Print the unsorted items

while(list($index, $value) = each($items))

Trang 18

Sorting Arrays

To avoid losing your specified string indices you need to use the asort() function This will sort the array and its elements without taking away your string indices If you wanted to sort this array in reverse you would use the rsort() function However, the rsort() function will also lose specified string indices, so to sort an array in reverse with string indices you need

to use the arsort() function You can also sort by your string indices by using ksort()

echo(“Index = “ $index “, “ $value “<BR>”);

The results of this example look like Figure 6.8

Figure 6.8 The ksort() function in action

Trang 19

N o t e

You can sort in reverse order by key by using the krsort() function

The last of the sorting functions for arrays has to be the coolest With usort() you can organize your arrays however you want The usort() function takes two arguments: the first is the array you would like to sort, and the second is a name of a function that con-tains your own sorting logic

$items = array(“Item6” => “Sword”, “Item5” => “Medpac”, “Item3” => “Advanced Medpac”,

“Item4” => “Armor”, “Item2” => “Blaster”, “Item1” => “Shotgun”);

// Print the unsorted items

while(list($index, $value) = each($items))

Trang 20

Your First PHP Game

Figure 6.9 The usort() function in action

C a u t i o n

Make sure you pass the function name to usort() as a string; otherwise you will get a warning play in the middle of your page

dis-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 have learned in all the previous chapters It contains session variables, arrays, functions, and PHP working together with HTML

The first step you need to take to set up a new game is to create a directory for it inside your Web server For IIS the directory would be C:\Inetpub\wwwroot, and if you are using

an Apache Web server the directory would be /usr/web If you are on Windows the Apache directory would look something like C:\Apache depending on where you installed Apache You can name the directory whatever you like I am going to name it tictactoe

Trang 21

Now that you have a directory set up you can create a new PHP file I recommend lowing a regular naming scheme The default page in a directory should be named index.php or default.php You can use whichever you like Since the game will only be in one file I will just name it index.php

fol-The next step you need to take is to define all of your constants and globals, and include the common functions file that you use in all of your games The first set of constants that you 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

frame-<!doctype html public “-//W3C//DTD HTML 4.0 //EN”>

<html>

Trang 22

Your First PHP Game

The render function needs to determine what state the game is in by using the global game state variable that was declared earlier If the state of the game is starting, then the render function needs to start a new game and change the state to playing If the state of the game

Trang 23

is playing then the render function needs to take the user input, process it, calculate the move for the computer, and update the board If one of the players has won the game, the render function needs to tell the user that he either has won or lost the game

As you can see, the render function needs to do a ton of work To accomplish all these tasks the render function will need some helper functions You will need a function to start a new game, a function to draw the board, a function to check for a win, a function

to check to see if the board is full, and, finally, a function to end the game and free your session Let’s start off with the render function itself and then continue on to the child functions that render() will call

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

TỪ KHÓA LIÊN QUAN