《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

相关文章

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

c++中的set容器介绍及操作大全

《c++中的set容器介绍及操作大全》:本文主要介绍c++中的set容器介绍及操作大全,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录​​一、核心特性​​️ ​​二、基本操作​​​​1. 初始化与赋值​​​​2. 增删查操作​​​​3. 遍历方

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决

C++11委托构造函数和继承构造函数的实现

《C++11委托构造函数和继承构造函数的实现》C++引入了委托构造函数和继承构造函数这两个重要的特性,本文主要介绍了C++11委托构造函数和继承构造函数的实现,具有一定的参考价值,感兴趣的可以了解一下... 目录引言一、委托构造函数1.1 委托构造函数的定义与作用1.2 委托构造函数的语法1.3 委托构造函

C++11作用域枚举(Scoped Enums)的实现示例

《C++11作用域枚举(ScopedEnums)的实现示例》枚举类型是一种非常实用的工具,C++11标准引入了作用域枚举,也称为强类型枚举,本文主要介绍了C++11作用域枚举(ScopedEnums... 目录一、引言二、传统枚举类型的局限性2.1 命名空间污染2.2 整型提升问题2.3 类型转换问题三、C

C++链表的虚拟头节点实现细节及注意事项

《C++链表的虚拟头节点实现细节及注意事项》虚拟头节点是链表操作中极为实用的设计技巧,它通过在链表真实头部前添加一个特殊节点,有效简化边界条件处理,:本文主要介绍C++链表的虚拟头节点实现细节及注... 目录C++链表虚拟头节点(Dummy Head)一、虚拟头节点的本质与核心作用1. 定义2. 核心价值二

C++ 检测文件大小和文件传输的方法示例详解

《C++检测文件大小和文件传输的方法示例详解》文章介绍了在C/C++中获取文件大小的三种方法,推荐使用stat()函数,并详细说明了如何设计一次性发送压缩包的结构体及传输流程,包含CRC校验和自动解... 目录检测文件的大小✅ 方法一:使用 stat() 函数(推荐)✅ 用法示例:✅ 方法二:使用 fsee