《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

相关文章

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

【C++ Primer Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<

C++包装器

包装器 在 C++ 中,“包装器”通常指的是一种设计模式或编程技巧,用于封装其他代码或对象,使其更易于使用、管理或扩展。包装器的概念在编程中非常普遍,可以用于函数、类、库等多个方面。下面是几个常见的 “包装器” 类型: 1. 函数包装器 函数包装器用于封装一个或多个函数,使其接口更统一或更便于调用。例如,std::function 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

Linux 网络编程 --- 应用层

一、自定义协议和序列化反序列化 代码: 序列化反序列化实现网络版本计算器 二、HTTP协议 1、谈两个简单的预备知识 https://www.baidu.com/ --- 域名 --- 域名解析 --- IP地址 http的端口号为80端口,https的端口号为443 url为统一资源定位符。CSDNhttps://mp.csdn.net/mp_blog/creation/editor

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名

数论入门整理(updating)

一、gcd lcm 基础中的基础,一般用来处理计算第一步什么的,分数化简之类。 LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a; } <pre name="code" class="cpp">LL lcm(LL a, LL b){LL c = gcd(a, b);return a / c * b;} 例题:

6.1.数据结构-c/c++堆详解下篇(堆排序,TopK问题)

上篇:6.1.数据结构-c/c++模拟实现堆上篇(向下,上调整算法,建堆,增删数据)-CSDN博客 本章重点 1.使用堆来完成堆排序 2.使用堆解决TopK问题 目录 一.堆排序 1.1 思路 1.2 代码 1.3 简单测试 二.TopK问题 2.1 思路(求最小): 2.2 C语言代码(手写堆) 2.3 C++代码(使用优先级队列 priority_queue)