本文主要是介绍《C++游戏编程入门》第7章 指针:Tic-Tac-Toe 2.0,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
《C++游戏编程入门》第7章 指针:Tic-Tac-Toe 2.0
- 7.1 指针基础
- 07.pointing.cpp
- 7.2 指针和常量
- 7.3 传递指针
- 07.swap_pointer_ver.cpp
- 07.inventory_displayer_pointer_ver.cpp
- 7.4 返回指针
- 07.inventory_pointer.cpp
- 7.5 指针与数组的关系
- 07.array_passer.cpp
- 7.6 Tic-Tac-Toe 2.0
- 07.tic-tac-toe2.cpp
7.1 指针基础
包含内存地址的变量。
07.pointing.cpp
#include <iostream>
#include <string>
using namespace std;int main()
{int *pAPointer; // 声明指针int *pScore = nullptr; // 声明并初始化指针,空指针int score = 1000;pScore = &score; // 地址赋值给指针cout << "Assigning &score to pScore\n";cout << "&score is: " << &score << "\n"; // address of score variablecout << "pScore is: " << pScore << "\n"; // address stored in pointercout << "score is: " << score << "\n";cout << "*pScore is: " << *pScore << "\n\n"; // 指针解引用cout << "Adding 500 to score\n";score += 500;cout << "score is: " << score << "\n";cout << "*pScore is: " << *pScore << "\n\n";cout << "Adding 500 to *pScore\n";*pScore += 500;cout << "score is: " << score << "\n";cout << "*pScore is: " << *pScore << "\n\n";cout << "Assigning &newScore to pScore\n";int newScore = 5000;pScore = &newScore; // 指针重新赋值cout << "&newScore is: " << &newScore << "\n";cout << "pScore is: " << pScore << "\n";cout << "newScore is: " << newScore << "\n";cout << "*pScore is: " << *pScore << "\n\n";cout << "Assigning &str to pStr\n";string str = "score";string *pStr = &str; // 对象指针cout << "str is: " << str << "\n";cout << "*pStr is: " << *pStr << "\n";cout << "(*pStr).size() is: " << (*pStr).size() << "\n";cout << "pStr->size() is: " << pStr->size() << "\n";return 0;
}
7.2 指针和常量
const用来限制指针。
- 常量指针
int score = 100;
int* const pScore = &score;//常量指针,必须声明时初始化,指向地址固定
*pScore = 500;//可修改指向的值
- 指向常量的指针(指针常量)
const int* pNumber;//int const * pNumber;
int one = 1;
pNumber = &one;//可指向常量或非常量,指向的值是常量(无法通过指针修改)
int two = 2;
pNumber = &tow;//指向地址可改变
//*pNumber = 3;//error,指向的值不可改变
- 指向常量的常量指针(常量引用)
int N = 5;
//const int const * pBound = &N;
//声明时初始化,指向地址固定,指向的值固定
//可指向常量或非常量,指向的值是常量(无法通过指针修改)
const int* const pBound = &N;
7.3 传递指针
传址调用。
07.swap_pointer_ver.cpp
#include <iostream>
using namespace std;void badSwap(int x, int y);
void goodSwap(int *const pX, int *const pY); // 常量指针,指向地址固定,指向的值可修改int main()
{int myScore = 150;int yourScore = 1000;cout << "Original values\n";cout << "myScore: " << myScore << "\n";cout << "yourScore: " << yourScore << "\n\n";cout << "Calling badSwap()\n";badSwap(myScore, yourScore);cout << "myScore: " << myScore << "\n";cout << "yourScore: " << yourScore << "\n\n";cout << "Calling goodSwap()\n";goodSwap(&myScore, &yourScore);cout << "myScore: " << myScore << "\n";cout << "yourScore: " << yourScore << "\n";return 0;
}void badSwap(int x, int y)
{int temp = x;x = y;y = temp;
}void goodSwap(int *const pX, int *const pY)
{// store value pointed to by pX in tempint temp = *pX;// store value pointed to by pY in address pointed to by pX*pX = *pY;// store value originally pointed to by pX in address pointed to by pY*pY = temp;
}
07.inventory_displayer_pointer_ver.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;// 指向常量的常量指针
// 指向地址和指向的值都不能修改
void display(const vector<string> *const pInventory);int main()
{vector<string> inventory;inventory.push_back("sword");inventory.push_back("armor");inventory.push_back("shield");display(&inventory);return 0;
}// receive the address of inventory into the pointer pInventory
// pInventory can be a constant pointer because the address it stores doesn't change
// inventory can be accepted as a constant object because the function won't change it
void display(const vector<string> *const pInventory)
{cout << "Your items:\n";for (vector<string>::const_iterator iter = (*pInventory).begin(); iter != (*pInventory).end(); ++iter)cout << *iter << endl;
}
7.4 返回指针
07.inventory_pointer.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;// returns a pointer to a string element
string *ptrToElement(vector<string> *const pVec, int i);int main()
{vector<string> inventory;inventory.push_back("sword");inventory.push_back("armor");inventory.push_back("shield");// displays string object that the returned pointer points tocout << "Sending the object pointed to by returned pointer to cout:\n";cout << *(ptrToElement(&inventory, 0)) << "\n\n";// assigns one pointer to another -- inexpensive assignmentcout << "Assigning the returned pointer to another pointer.\n";string *pStr = ptrToElement(&inventory, 1);cout << "Sending the object pointed to by new pointer to cout:\n";cout << *pStr << "\n\n";// copies a string object -- expensive assignmentcout << "Assigning object pointed to by pointer to a string object.\n";string str = *(ptrToElement(&inventory, 2));cout << "Sending the new string object to cout:\n";cout << str << "\n\n";// altering the string object through a returned pointercout << "Altering an object through a returned pointer.\n";*pStr = "Healing Potion";cout << "Sending the altered object to cout:\n";cout << inventory[1] << endl;return 0;
}string *ptrToElement(vector<string> *const pVec, int i)
{// returns address of the string in position i of vector that pVec points toreturn &((*pVec)[i]);
}// 返回指针,超出作用域范围对象(局部变量指针),函数结束后不存在,野指针
string *badPointer()
{string local = "This string will cease to exist once the function ends.";string *pLocal = &local;return pLocal;
}
7.5 指针与数组的关系
数组名是指向数组第一个元素的常量指针。
07.array_passer.cpp
#include <iostream>
using namespace std;void increase(int *const array, const int NUM_ELEMENTS);
void display(const int *const array, const int NUM_ELEMENTS);int main()
{cout << "Creating an array of high scores.\n\n";const int NUM_SCORES = 3;int highScores[NUM_SCORES] = {5000, 3500, 2700};cout << "Displaying scores using array name as a constant pointer.\n";cout << *highScores << endl;cout << *(highScores + 1) << endl;cout << *(highScores + 2) << "\n\n";cout << "Increasing scores by passing array as a constant pointer.\n\n";increase(highScores, NUM_SCORES);cout << "Displaying scores by passing array as a constant pointer to a constant.\n";display(highScores, NUM_SCORES);return 0;
}void increase(int *const array, const int NUM_ELEMENTS)
{for (int i = 0; i < NUM_ELEMENTS; ++i)array[i] += 500;
}void display(const int *const array, const int NUM_ELEMENTS)
{for (int i = 0; i < NUM_ELEMENTS; ++i)cout << array[i] << endl;
}
7.6 Tic-Tac-Toe 2.0
07.tic-tac-toe2.cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;// global constants
const char X = 'X';
const char O = 'O';
const char EMPTY = ' ';
const char TIE = 'T';
const char NO_ONE = 'N';// function prototypes
void instructions();
char askYesNo(string question);
int askNumber(string question, int high, int low = 0);
char humanPiece();
char opponent(char piece);
void displayBoard(const vector<char> *const pBoard);
char winner(const vector<char> *const pBoard);
bool isLegal(const vector<char> *const pBoard, int move);
int humanMove(const vector<char> *const pBoard, char human);
int computerMove(vector<char> board, char computer);
void announceWinner(char winner, char computer, char human);// main function
int main()
{const int NUM_SQUARES = 9;vector<char> board(NUM_SQUARES, EMPTY);instructions();char human = humanPiece();char computer = opponent(human);displayBoard(&board);char turn = X;int move;do{if (turn == human){move = humanMove(&board, human);board[move] = human;}else{move = computerMove(board, computer);board[move] = computer;}displayBoard(&board);turn = opponent(turn);} while (winner(&board) == NO_ONE);announceWinner(winner(&board), computer, human);return 0;
}void instructions()
{cout << "Welcome to the ultimate man-machine showdown: Tic-Tac-Toe.\n";cout << "--where human brain is pit against silicon processor\n\n";cout << "Make your move known by entering a number, 0 - 8. The number\n";cout << "corresponds to the desired board position, as illustrated:\n\n";cout << " 0 | 1 | 2\n";cout << " ---------\n";cout << " 3 | 4 | 5\n";cout << " ---------\n";cout << " 6 | 7 | 8\n\n";cout << "Prepare yourself, human. The battle is about to begin.\n\n";
}char askYesNo(string question)
{char response;do{cout << question << " (y/n): ";cin >> response;} while (response != 'y' && response != 'n');return response;
}int askNumber(string question, int high, int low)
{int number;do{cout << question << " (" << low << " - " << high << "): ";cin >> number;} while (number > high || number < low);return number;
}char humanPiece()
{char go_first = askYesNo("Do you require the first move?");if (go_first == 'y'){cout << "\nThen take the first move. You will need it.\n";return X;}else{cout << "\nYour bravery will be your undoing... I will go first.\n";return O;}
}char opponent(char piece)
{if (piece == X)return O;elsereturn X;
}void displayBoard(const vector<char> *const pBoard)
{cout << "\n\t" << (*pBoard)[0] << " | " << (*pBoard)[1] << " | " << (*pBoard)[2];cout << "\n\t"<< "---------";cout << "\n\t" << (*pBoard)[3] << " | " << (*pBoard)[4] << " | " << (*pBoard)[5];cout << "\n\t"<< "---------";cout << "\n\t" << (*pBoard)[6] << " | " << (*pBoard)[7] << " | " << (*pBoard)[8];cout << "\n\n";
}char winner(const vector<char> *const pBoard)
{// all possible winning rowsconst int WINNING_ROWS[8][3] = {{0, 1, 2},{3, 4, 5},{6, 7, 8},{0, 3, 6},{1, 4, 7},{2, 5, 8},{0, 4, 8},{2, 4, 6}};const int TOTAL_ROWS = 8;// if any winning row has three values that are the same (and not EMPTY),// then we have a winnerfor (int row = 0; row < TOTAL_ROWS; ++row){if (((*pBoard)[WINNING_ROWS[row][0]] != EMPTY) &&((*pBoard)[WINNING_ROWS[row][0]] == (*pBoard)[WINNING_ROWS[row][1]]) &&((*pBoard)[WINNING_ROWS[row][1]] == (*pBoard)[WINNING_ROWS[row][2]])){return (*pBoard)[WINNING_ROWS[row][0]];}}// since nobody has won, check for a tie (no empty squares left)if (count(pBoard->begin(), pBoard->end(), EMPTY) == 0)return TIE;// since nobody has won and it isn't a tie, the game ain't overreturn NO_ONE;
}inline bool isLegal(int move, const vector<char> *pBoard)
{return ((*pBoard)[move] == EMPTY);
}int humanMove(const vector<char> *const pBoard, char human)
{int move = askNumber("Where will you move?", (pBoard->size() - 1));while (!isLegal(move, pBoard)){cout << "\nThat square is already occupied, foolish human.\n";move = askNumber("Where will you move?", (pBoard->size() - 1));}cout << "Fine...\n";return move;
}int computerMove(vector<char> board, char computer)
{int out = -1;const unsigned NUM = board.size();char human = opponent(computer);const int BEST_MOVES[NUM] = {4, 0, 2, 6, 8, 1, 3, 5, 7};// 遍历查找计算机能一步获胜的方格位置for (unsigned move = 0; move < NUM; move++){if (isLegal(move, &board)) // 当前位置为空{// 尝试移动board[move] = computer;// 测试计算机能否获胜if (winner(&board) == computer){out = move;goto exportation;}// 撤销移动board[move] = EMPTY;}}// 遍历查找人类能一步获胜的方格位置for (unsigned move = 0; move < NUM; move++){if (isLegal(move, &board)) // 当前位置为空{// 尝试移动board[move] = human;// 测试人类能否获胜if (winner(&board) == human){out = move;goto exportation;}// 撤销移动board[move] = EMPTY;}}// 中心》四边》四角for (unsigned move = 0; move < NUM; move++)if (isLegal(BEST_MOVES[move], &board)){out = BEST_MOVES[move];break;}exportation:cout << "I shall take square number " << out << endl;return out;
}void announceWinner(char winner, char computer, char human)
{if (winner == computer){cout << winner << "'s won!\n";cout << "As I predicted, human, I am triumphant once more -- proof\n";cout << "that computers are superior to humans in all regards.\n";}else if (winner == human){cout << winner << "'s won!\n";cout << "No, no! It cannot be! Somehow you tricked me, human.\n";cout << "But never again! I, the computer, so swear it!\n";}else{cout << "It's a tie.\n";cout << "You were most lucky, human, and somehow managed to tie me.\n";cout << "Celebrate... for this is the best you will ever achieve.\n";}
}
这篇关于《C++游戏编程入门》第7章 指针:Tic-Tac-Toe 2.0的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!