《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++如何通过Qt反射机制实现数据类序列化

《C++如何通过Qt反射机制实现数据类序列化》在C++工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作,所以本文就来聊聊C++如何通过Qt反射机制实现数据类序列化吧... 目录设计预期设计思路代码实现使用方法在 C++ 工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作。由于数据类

Linux下如何使用C++获取硬件信息

《Linux下如何使用C++获取硬件信息》这篇文章主要为大家详细介绍了如何使用C++实现获取CPU,主板,磁盘,BIOS信息等硬件信息,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录方法获取CPU信息:读取"/proc/cpuinfo"文件获取磁盘信息:读取"/proc/diskstats"文

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指

go 指针接收者和值接收者的区别小结

《go指针接收者和值接收者的区别小结》在Go语言中,值接收者和指针接收者是方法定义中的两种接收者类型,本文主要介绍了go指针接收者和值接收者的区别小结,文中通过示例代码介绍的非常详细,需要的朋友们下... 目录go 指针接收者和值接收者的区别易错点辨析go 指针接收者和值接收者的区别指针接收者和值接收者的

C++中初始化二维数组的几种常见方法

《C++中初始化二维数组的几种常见方法》本文详细介绍了在C++中初始化二维数组的不同方式,包括静态初始化、循环、全部为零、部分初始化、std::array和std::vector,以及std::vec... 目录1. 静态初始化2. 使用循环初始化3. 全部初始化为零4. 部分初始化5. 使用 std::a

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的

C++ vector的常见用法超详细讲解

《C++vector的常见用法超详细讲解》:本文主要介绍C++vector的常见用法,包括C++中vector容器的定义、初始化方法、访问元素、常用函数及其时间复杂度,通过代码介绍的非常详细,... 目录1、vector的定义2、vector常用初始化方法1、使编程用花括号直接赋值2、使用圆括号赋值3、ve

如何高效移除C++关联容器中的元素

《如何高效移除C++关联容器中的元素》关联容器和顺序容器有着很大不同,关联容器中的元素是按照关键字来保存和访问的,而顺序容器中的元素是按它们在容器中的位置来顺序保存和访问的,本文介绍了如何高效移除C+... 目录一、简介二、移除给定位置的元素三、移除与特定键值等价的元素四、移除满足特android定条件的元

Python获取C++中返回的char*字段的两种思路

《Python获取C++中返回的char*字段的两种思路》有时候需要获取C++函数中返回来的不定长的char*字符串,本文小编为大家找到了两种解决问题的思路,感兴趣的小伙伴可以跟随小编一起学习一下... 有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:

Java Optional避免空指针异常的实现

《JavaOptional避免空指针异常的实现》空指针异常一直是困扰开发者的常见问题之一,本文主要介绍了JavaOptional避免空指针异常的实现,帮助开发者编写更健壮、可读性更高的代码,减少因... 目录一、Optional 概述二、Optional 的创建三、Optional 的常用方法四、Optio