《C++游戏编程入门》第7章 指针:Tic-Tac-Toe 2.0

2024-03-13 08:28

本文主要是介绍《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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/804221

相关文章

解决java.lang.NullPointerException问题(空指针异常)

《解决java.lang.NullPointerException问题(空指针异常)》本文详细介绍了Java中的NullPointerException异常及其常见原因,包括对象引用为null、数组元... 目录Java.lang.NullPointerException(空指针异常)NullPointer

C++一个数组赋值给另一个数组方式

《C++一个数组赋值给另一个数组方式》文章介绍了三种在C++中将一个数组赋值给另一个数组的方法:使用循环逐个元素赋值、使用标准库函数std::copy或std::memcpy以及使用标准库容器,每种方... 目录C++一个数组赋值给另一个数组循环遍历赋值使用标准库中的函数 std::copy 或 std::

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

c++中std::placeholders的使用方法

《c++中std::placeholders的使用方法》std::placeholders是C++标准库中的一个工具,用于在函数对象绑定时创建占位符,本文就来详细的介绍一下,具有一定的参考价值,感兴... 目录1. 基本概念2. 使用场景3. 示例示例 1:部分参数绑定示例 2:参数重排序4. 注意事项5.

使用C++将处理后的信号保存为PNG和TIFF格式

《使用C++将处理后的信号保存为PNG和TIFF格式》在信号处理领域,我们常常需要将处理结果以图像的形式保存下来,方便后续分析和展示,C++提供了多种库来处理图像数据,本文将介绍如何使用stb_ima... 目录1. PNG格式保存使用stb_imagephp_write库1.1 安装和包含库1.2 代码解

C++实现封装的顺序表的操作与实践

《C++实现封装的顺序表的操作与实践》在程序设计中,顺序表是一种常见的线性数据结构,通常用于存储具有固定顺序的元素,与链表不同,顺序表中的元素是连续存储的,因此访问速度较快,但插入和删除操作的效率可能... 目录一、顺序表的基本概念二、顺序表类的设计1. 顺序表类的成员变量2. 构造函数和析构函数三、顺序表

使用C++实现单链表的操作与实践

《使用C++实现单链表的操作与实践》在程序设计中,链表是一种常见的数据结构,特别是在动态数据管理、频繁插入和删除元素的场景中,链表相比于数组,具有更高的灵活性和高效性,尤其是在需要频繁修改数据结构的应... 目录一、单链表的基本概念二、单链表类的设计1. 节点的定义2. 链表的类定义三、单链表的操作实现四、