C++ 很有趣:编写一个井字游戏 (Tic Tac Toe)

开发 后端
这篇文章,以及整个系列都是针对那些想学习C++或者对这个语言性能好奇的开发者。

这个有趣的C++系列打算展示一下使用C++写代码可以和其他主流语言一样高效而有趣。在第二部分,我将向你展示使用C++从无到有的创建一个井字游戏。这篇文章,以及整个系列都是针对那些想学习C++或者对这个语言性能好奇的开发者。

许多年轻人想学习编程来写游戏。C++是用的最多的用来写游戏的语言,尽管在写出下个愤怒的小鸟之前,需要学会很多的编程经验。一个井子游戏是开始学习的 一个好选择,事实上,在许多年前我开始学习C++后,他是我写的地一个游戏。我希望这篇文章可以帮助到那些还不熟悉C++的初学者和有经验的开发者。

我使用的是Visual Studio 2012来写这篇文章的源代码。

游戏介绍

如果你没有玩过井字游戏或者并不熟悉这个游戏,下面是来自维基百科的描述.

  井字游戏 (或者"圈圈和叉叉",Xs and Os) 是一个两人的纸笔游戏,两个人轮流在3X3的网格内画圈和叉. 当一名玩家放置的标志在水平,垂直或者对角线上成一条线即获得胜利.

这个游戏也可以人机对战,先手不固定.

创建这个程序的时候有2个关键的东西:程序的逻辑和程序的UI界面. 有许多在windows中创建用户UI的方法, 包括 Win32 API, MFC, ATL, GDI+, DirectX, etc. 在这篇文章中,我将展示使用多种技术来实现同一个程序逻辑. 我们将新建2个应用, 一个使用 Win32 API 另一个使用 C++/CX.

 

游戏逻辑

如果一个玩家在网格上放下一个标记时,遵循几个简单的规则,那他就可以玩一个完美的游戏(意味着赢或者平局)。在Wikipedia上写有这些规则,在里面你也可以找到先手玩家的最优策略。

在xkcd drawing上 有先手和后手玩家的最优策略。尽管有几个错误(在几种情况下没有走必胜的步骤,至少在一个情况下丢失了一个X标记),我将使用这个版本作为游戏策略(修复 了那些我能找到的错误)。记住电脑总是玩一个完美的游戏。如果你实现了这样一个游戏,你可能也想让用户赢,这种情况下你需要一个不同的方法。当对本文的目 的,这个策略应该足够了。

提出的第一个问题是在C++程序中用什么数据结构来表示图像的模型。这可以有不同的选择,比如树、图、数组或者位字段(如果真有人对内存消耗很在意)。网 格有9个单元,我选择的最简单的使用对每个单元使用一个包含9个整数的数组:0表示空的单元,1表示单元被标记为X,2表示单元被标记为O。让我们看下图 以及它将被如何编码。

这幅图可以这么理解:

  • 在单元(0,0)放X。网格可以编码为:1,0,0,0,0,0,0,0,0
  • 如果对手在单元(0,1)放置O,那么在单元(1,1)放置X。现在网格编码为:1,2,0,0,1,0,0,0,0
  • 如果对手在单元(0,2)放置O,那么在单元(2,2)放置X。现在网格编码为:1,2,2,0,1,0,0,0,1
  • 如果对手在单元(2,2)放置O,那么在单元(2,0)放置X。现在网格编码为:1,2,0,0,1,0,1,0,2。这时,无论对手怎么做,X都将赢得比赛。
  • 如果对手在单元(0,2)放置O,那么在单元(1,0)放置X。现在网格编码为:1,2,2,1,1,0,1,0,2。这表示的是一个赢得比赛的一步。

记住这个我们就可以开始在程序中对其编码了。我们将使用一个std::array来表示一个9格板。这是个固定大小的容器,在编译时就已知的大小,在连续的内存区域存储元素。为了避免一遍又一遍的使用相同数组类型,我将定义一个别名来简化。

  1. #include <array> 
  2.  
  3. typedef std::array<char, 9> tictactoe_status; 

上面描述的最优策略用这样的数组队列(另一个数组)来表示。

  1. tictactoe_status const strategy_x[] =  
  2.    {1,0,0,0,0,0,0,0,0}, 
  3.    {1,2,0,0,1,0,0,0,0}, 
  4.    {1,2,2,0,1,0,0,0,1}, 
  5.    {1,2,0,2,1,0,0,0,1}, 
  6.    // ... 
  7. }; 
  8.  
  9. tictactoe_status const strategy_o[] =  
  10.    {2,0,0,0,1,0,0,0,0}, 
  11.    {2,2,1,0,1,0,0,0,0}, 
  12.    {2,2,1,2,1,0,1,0,0}, 
  13.    {2,2,1,0,1,2,1,0,0}, 
  14.    // ... 
  15. }; 

#p#

strategy_x是先手玩家的最优策略,strategy_o是后手玩家的最优策略。如果你看了文中的源代码,你将注意到这两个数组的真实定义和我前面展示的不同。

  1. tictactoe_status const strategy_x[] =  
  2. #include "strategy_x.h" 
  3. }; 
  4.  
  5. tictactoe_status const strategy_o[] =  
  6. #include "strategy_o.h" 
  7. }; 

这是个小技巧,我的理由是,它允许我们把真实的很长的数组内容放在分开的文件中(这些文件的扩展性不重要,它可以不仅仅是C++头文件,也可以是其他任何 文件),保证源码文件和定义简单干净。strategy_x.h和strategy_o.h文件在编译的预处理阶段就被插入到源码文件中,如同正常的头文 件一样。下面是strategy_x.h文件的片断。

  1. // http://imgs.xkcd.com/comics/tic_tac_toe_large.png 
  2. // similar version on http://upload.wikimedia.org/wikipedia/commons/d/de/Tictactoe-X.svg 
  3. // 1 = X2 = O0 = unoccupied 
  4.  
  5. 1,0,0,0,0,0,0,0,0, 
  6.  
  7. 1,2,0,0,1,0,0,0,0, 
  8. 1,2,2,0,1,0,0,0,1, 
  9. 1,2,0,2,1,0,0,0,1, 
  10. 1,2,0,0,1,2,0,0,1, 

你应该注意到,如果你使用支持C++11的编译器,你可以使用一个std::vector而不是C类型的数组。Visual Studio 2012不支持这么做,但在Visual Studio 2013中支持。

  1. std::vector<tictactoe_status> strategy_o =  
  2.    {2, 0, 0, 0, 1, 0, 0, 0, 0}, 
  3.    {2, 2, 1, 0, 1, 0, 0, 0, 0}, 
  4.    {2, 2, 1, 2, 1, 0, 1, 0, 0}, 
  5.    {2, 2, 1, 0, 1, 2, 1, 0, 0}, 
  6.    {2, 2, 1, 1, 1, 0, 2, 0, 0}, 
  7. }; 

为了定义这些数字表示的对应玩家,我定义了一个叫做tictactoe_player的枚举类型变量。

  1. enum class tictactoe_player : char 
  2.    none = 0
  3.    computer = 1
  4.    user = 2
  5. }; 

游戏的逻辑部分将会在被称之为tictactoe_game 的类中实现。最基本的,这个 class 应该有下面的状态:

  • 一个布尔值用来表示游戏是否开始了,命名为 started 。
  • 游戏的当前状态(网格上的标记), 命名为 status 。
  • 根据当前的状态得到的之后可以进行的下法的集合,命名为strateg
  1. class tictactoe_game 
  2.    bool started; 
  3.    tictactoe_status status; 
  4.    std::set<tictactoe_status> strategy; 
  5.     
  6.    // ... 
  7. }; 

 

在游戏的过程中,我们需要知道游戏是否开始了、结束了,如果结束了,需要判定是否有哪个玩家赢了或者最终两个人打平。为此,tictactoe_game类提供了三个方法:

  • is_started()来表示游戏是否开始了
  • is_victory()来检查是否有哪位玩家在游戏中获胜
  • is_finished()来检查游戏是否结束。当其中某位玩家在游戏中获胜或者当网格被填满玩家不能再下任何的棋子的时候,游戏结束。
  1. bool is_started() const {return started;} 
  2. bool is_victory(tictactoe_player const player) const {return is_winning(status, player);} 
  3. bool is_finished() const  

 对于方法is_victory()和is_finished(),实际上是依赖于两个私有的方法,is_full(), 用来表示网格是否被填满并且不能再放下任何的棋子,以及方法is_winning, 用来表示在该网格上是否有某玩家胜出。它们的实现将会很容易被读懂。is_full 通过计算网格中空的(在表示网格的数组中值为0)格子的数量,如果没有这样的格子那么将返回true。is_winning将会检查这些连线,网格的行、列、以及对角线,依此来查看是否有哪位玩家已经获胜。

  1. bool is_winning(tictactoe_status const & status, tictactoe_player const player) const 
  2.    auto mark = static_cast<char>(player); 
  3.    return  
  4.       (status[0] == mark && status[1] == mark && status[2] == mark) || 
  5.       (status[3] == mark && status[4] == mark && status[5] == mark) || 
  6.       (status[6] == mark && status[7] == mark && status[8] == mark) || 
  7.       (status[0] == mark && status[4] == mark && status[8] == mark) || 
  8.       (status[2] == mark && status[4] == mark && status[6] == mark) || 
  9.       (status[0] == mark && status[3] == mark && status[6] == mark) || 
  10.       (status[1] == mark && status[4] == mark && status[7] == mark) || 
  11.       (status[2] == mark && status[5] == mark && status[8] == mark); 
  12.  
  13. bool is_full(tictactoe_status const & status) const  
  14.    return 0 == std::count_if(std::begin(status), std::end(status), [](int const mark){return mark == 0;}); 

当一个玩家获胜的时候,我们想给他所连成的线(行、列、或者对角线)上画一条醒目的线段。因此首先我们得知道那条线使得玩家获胜。我们使用了方法get_winning_line()来返回一对 tictactoe_cell,用来表示线段的两端。它的实现和is_winning很相似,它检查行、列和对角线上的状态。它可能会看起来有点冗长,但是我相信这个方法比使用循环来遍历行、列、对角线更加简单。

  1. struct tictactoe_cell 
  2.    int row; 
  3.    int col; 
  4.  
  5.    tictactoe_cell(int r = INT_MAX, int c = INT_MAX):row(r), col(c) 
  6.    {} 
  7.  
  8.    bool is_valid() const {return row != INT_MAX && col != INT_MAX;} 
  9. }; 
  10.  
  11. std::pair<tictactoe_cell, tictactoe_cell> const get_winning_line() const 
  12.    auto mark = static_cast<char>(tictactoe_player::none); 
  13.    if(is_victory(tictactoe_player::computer)) 
  14.       mark = static_cast<char>(tictactoe_player::computer); 
  15.    else if(is_victory(tictactoe_player::user)) 
  16.       mark = static_cast<char>(tictactoe_player::user); 
  17.  
  18.    if(mark != 0) 
  19.    { 
  20.       if(status[0] == mark && status[1] == mark && status[2] == mark)  
  21.          return std::make_pair(tictactoe_cell(0,0), tictactoe_cell(0,2)); 
  22.       if(status[3] == mark && status[4] == mark && status[5] == mark) 
  23.          return std::make_pair(tictactoe_cell(1,0), tictactoe_cell(1,2)); 
  24.       if(status[6] == mark && status[7] == mark && status[8] == mark) 
  25.          return std::make_pair(tictactoe_cell(2,0), tictactoe_cell(2,2)); 
  26.       if(status[0] == mark && status[4] == mark && status[8] == mark) 
  27.          return std::make_pair(tictactoe_cell(0,0), tictactoe_cell(2,2)); 
  28.       if(status[2] == mark && status[4] == mark && status[6] == mark) 
  29.          return std::make_pair(tictactoe_cell(0,2), tictactoe_cell(2,0)); 
  30.       if(status[0] == mark && status[3] == mark && status[6] == mark) 
  31.          return std::make_pair(tictactoe_cell(0,0), tictactoe_cell(2,0)); 
  32.       if(status[1] == mark && status[4] == mark && status[7] == mark) 
  33.          return std::make_pair(tictactoe_cell(0,1), tictactoe_cell(2,1)); 
  34.       if(status[2] == mark && status[5] == mark && status[8] == mark) 
  35.          return std::make_pair(tictactoe_cell(0,2), tictactoe_cell(2,2)); 
  36.    } 
  37.  
  38.    return std::make_pair(tictactoe_cell(), tictactoe_cell()); 

#p#

现在我们只剩下添加开始游戏功能和为网格放上棋子功能(电脑和玩家两者).

对于开始游戏,我们需要知道,由谁开始下第一个棋子,因此我们可以采取比较合适的策略(两种方式都需要提供,电脑先手或者玩家先手都要被支持)。同时,我 们也需要重置表示网格的数组。方法start()对开始新游戏进行初始化。可以下的棋的策略的集合被再一次的初始化, 从stategy_x 或者strategy_o进行拷贝。从下面的代码可以注意到,strategy是一个std::set, 并且strategy_x或者strategy_o都是有重复单元的数组,因为在tictoctoe表里面的一些位置是重复的。这个std::set 是一个只包含唯一值的容器并且它保证了唯一的可能的位置(例如对于strategy_o来说,有一半是重复的)。<algorithm> 中的std::copy算法在这里被用来进行数据单元的拷贝,将当前的内容拷贝到std::set中,并且使用方法assign()来将 std::array的所有的元素重置为0。

  1. void start(tictactoe_player const player) 
  2.    strategy.clear(); 
  3.    if(player == tictactoe_player::computer) 
  4.       std::copy(std::begin(strategy_x), std::end(strategy_x),  
  5.                 std::inserter(strategy, std::begin(strategy))); 
  6.    else if(player == tictactoe_player::user) 
  7.       std::copy(std::begin(strategy_o), std::end(strategy_o),  
  8.                 std::inserter(strategy, std::begin(strategy))); 
  9.                  
  10.    status.assign(0); 
  11.     
  12.    started = true

当玩家走一步时,我们需要做的是确保选择的网格是空的,并放置合适的标记。move()方法的接收参数是网格的坐标、玩家的记号,如果这一步有效时返回真,否则返回假。

  1. bool move(tictactoe_cell const cell, tictactoe_player const player) 
  2.    if(status[cell.row*3 + cell.col] == 0) 
  3.    { 
  4.       status[cell.row*3 + cell.col] = static_cast<char>(player); 
  5.        
  6.       if(is_victory(player)) 
  7.       { 
  8.          started = false
  9.       } 
  10.        
  11.       return true; 
  12.    } 
  13.  
  14.    return false; 

电脑走一步时需要更多的工作,因为我们需要找到电脑应该走的最好的下一步。重载的move()方法在可能的步骤(策略)集合中查询,然后从中选择最佳的一步。在走完这步后,会检查电脑是否赢得这场游戏,如果是的话标记游戏结束。这个方法返回电脑走下一步的位置。

  1. tictactoe_cell move(tictactoe_player const player) 
  2.    tictactoe_cell cell; 
  3.  
  4.    strategy = lookup_strategy(); 
  5.  
  6.    if(!strategy.empty()) 
  7.    { 
  8.       auto newstatus = lookup_move(); 
  9.  
  10.       for(int i = 0; i < 9; ++i) 
  11.       { 
  12.          if(status[i] == 0 && newstatus[i]==static_cast<char>(player)) 
  13.          { 
  14.             cell.row = i/3; 
  15.             cell.col = i%3; 
  16.             break; 
  17.          } 
  18.       } 
  19.  
  20.       status = newstatus
  21.  
  22.       if(is_victory(player)) 
  23.       { 
  24.          started = false
  25.       } 
  26.    } 
  27.  
  28.    return cell; 

lookup_strategy()方法在当前可能的移动位置中迭代,来找到从当前位置往哪里移动是可行的。它利用了这样的一种事实,空的网格以0来表 示,任何已经填过的网格,不是用1就是用2表示,而这两个值都大于0。一个网格的值只能从0变为1或者2。不可能从1变为2或从2变为1。

当游戏开始时的网格编码为0,0,0,0,0,0,0,0,0来表示并且当前情况下任何的走法都是可能的。这也是为什么我们要在thestart()方法 里把整个步数都拷贝出来的原因。一旦玩家走了一步,那能走的步数的set便会减少。举个例子,玩家在第一个格子里走了一步。此时网格编码为 1,0,0,0,0,0,0,0,0。这时在数组的第一个位置不可能再有0或者2的走法因此需要被过滤掉。

  1. std::set<tictactoe_status> tictactoe_game::lookup_strategy() const 
  2.    std::set<tictactoe_status> nextsubstrategy; 
  3.  
  4.    for(auto const & s : strategy) 
  5.    { 
  6.       bool match = true
  7.       for(int i = 0; i < 9 && match; ++i) 
  8.       { 
  9.          if(s[i] < status[i]) 
  10.             match = false
  11.       } 
  12.  
  13.       if(match) 
  14.       { 
  15.          nextsubstrategy.insert(s); 
  16.       } 
  17.    } 
  18.  
  19.    return nextsubstrategy; 

在选择下一步时我们需要确保我们选择的走法必须与当前的标记不同,如果当前的状态是1,2,0,0,0,0,0,0,0而我们现在要为玩家1选择走法那么 我们可以从余下的7个数组单元中选择一个,可以是:1,2,1,0,0,0,0,0,0或1,2,0,1,0,0,0,0,0... 或1,2,0,0,0,0,0,0,1。然而我们需要选择最优的走法而不是仅仅只随便走一步,通常最优的走法也是赢得比赛的关键。因此我们需要找一步能使 我们走向胜利,如果没有这样的一步,那就随便走吧。

  1. tictactoe_status tictactoe_game::lookup_move() const 
  2.    tictactoe_status newbest = {0}; 
  3.    for(auto const & s : strategy) 
  4.    { 
  5.       int diff = 0
  6.       for(int i = 0; i < 9; ++i) 
  7.       { 
  8.          if(s[i] > status[i]) 
  9.             diff++; 
  10.       } 
  11.  
  12.       if(diff == 1) 
  13.       { 
  14.          newbest = s; 
  15.          if(is_winning(newbest, tictactoe_player::computer)) 
  16.          { 
  17.             break; 
  18.          } 
  19.       } 
  20.    } 
  21.  
  22.    assert(newbest != empty_board); 
  23.  
  24.    return newbest; 

做完了这一步,我们的游戏的逻辑部分就完成了。更多细节请阅读game.hgame.cpp中的代码

#p#

一个用Win32 API实现的游戏

我将用Win32 API做用户界面来创建第一个应用程序。如果你不是很熟悉Win32 编程那么现在已经有大量的资源你可以利用学习。为了使大家理解我们如何创建一个最终的应用,我将只讲述一些必要的方面。另外,我不会把每一行代码都展现并 解释给大家,但是你可以通过下载这些代码来阅读浏览它。

一个最基本的Win32应用需要的一些内容:

  • 一个入口点,通常来说是WinMain,而不是main。它需要一些参数例如当前应用实例的句柄,命令行和指示窗口如何展示的标志。
  • 一个窗口类,代表了创建一个窗口的模板。一个窗口类包含了一个为系统所用的属性集合,例如类名,class style(不同于窗口的风格),图标,菜单,背景刷,窗口的指针等。一个窗口类是进程专用的并且必须要注册到系统优先级中来创建一个窗口。使用RegisterClassEx来注册一个窗口类。
  • 一个主窗口,基于一个窗口类来创建。使用CreateWindowEx可以创建一个窗口。
  • 一个窗口过程函数,它是一个处理所有基于窗口类创建的窗口的消息的方法。一个窗口过程函数与窗口相联,但是它不是窗口。
  • 一个消息循环。一个窗口通过两种方式来接受消息:通过SendMessage,直接调用窗口过程函数直到窗口过程函数处理完消息之后才返回,或者通过PostMessage (或 PostThreadMessage)把一个消息投送到创建窗口的线程的消息队列中并且不用等待线程处理直接返回。因此线程必须一直运行一个从消息队列接收消息和把消息发送给窗口过程函数的循环

你可以在 MSDN 中找到关于Win 32 应用程序如何注册窗口类、创建一个窗口、运行消息循环的例子。一个Win32的应用程序看起来是这样的:

  1. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) 
  2.    WNDCLASS wc;  
  3.    // set the window class attributes 
  4.    // including pointer to a window procedure 
  5.     
  6.    if (!::RegisterClass(&wc)) 
  7.       return FALSE; 
  8.        
  9.    HWND wnd = ::CreateWindowEx(...); 
  10.    if(!wnd) 
  11.       return FALSE; 
  12.        
  13.    ::ShowWindow(wnd, nCmdShow);  
  14.     
  15.    MSG msg; 
  16.    while(::GetMessage(&msg, nullptr, 0, 0)) 
  17.    { 
  18.       ::TranslateMessage(&msg); 
  19.       ::DispatchMessage(&msg); 
  20.    } 
  21.  
  22.    return msg.wParam;    

当然,这还不够,我们还需要一个窗口过程函数来处理发送给窗口的消息,比如PAINT消息,DESTORY 消息,菜单消息和其它的一些必要的消息。一个窗口过程函数看起来是这样的:

  1. LRESULT WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) 
  2.    switch(message) 
  3.    { 
  4.    case WM_PAINT: 
  5.       { 
  6.          PAINTSTRUCT ps; 
  7.          HDC dc = ::BeginPaint(hWnd, &ps); 
  8.          // paint 
  9.          ::EndPaint(hWnd, &ps); 
  10.       } 
  11.       break; 
  12.  
  13.    case WM_DESTROY: 
  14.       ::PostQuitMessage(0); 
  15.       return 0; 
  16.  
  17.    case WM_COMMAND: 
  18.       { 
  19.          ... 
  20.       } 
  21.       break; 
  22.    } 
  23.  
  24.    return ::DefWindowProc(hWnd, message, wParam, lParam); 

我更喜欢写面向对象的代码,不喜欢面向过程,所以我用几个类封装了窗口类、窗口和设备描述表。你可以在附件的代码framework.h framework.cpp  找到这些类的实现(它们非常小巧 )。

  • WindowClass类是对窗口类相关资源初始化的封装,在构造函数中,它初始化了WNDCLASSEX 的结构并且调用 RegisterClassEx 方法。在析构函数中,它通过调用 UnregisterClass 移除窗口的注册。
  • Window类是通过对HWND封装一些诸如Create,ShowWindow 和Invalidate的函数(它们的名字已经告诉了你他们是做什么的)。它还有几个虚成员代表消息句柄,它们会被窗口过程调 用 (OnPaint,OnMenuItemClicked,OnLeftButtonDown) 。这个window类将会被继承来并提供具体的实现。
  • DeviceContex类是对设备描述表(HDC)的封装。在构造函数中它调用 BeginPaint 函数并且在析构函数中调用  EndPaint 函数。

这个游戏的主要窗口是TicTacToeWindow类,它是从Window类继承而来,它重载了虚拟方法来处理消息,该类的声明是这样的:

  1. class TicTacToeWindow : public Window 
  2.    HANDLE hBmp0; 
  3.    HANDLE hBmpX; 
  4.    BITMAP bmp0; 
  5.    BITMAP bmpX; 
  6.  
  7.    tictactoe_game game; 
  8.  
  9.    void DrawBackground(HDC dc, RECT rc); 
  10.    void DrawGrid(HDC dc, RECT rc); 
  11.    void DrawMarks(HDC dc, RECT rc); 
  12.    void DrawCut(HDC dc, RECT rc); 
  13.  
  14.    virtual void OnPaint(DeviceContext* dc) override; 
  15.    virtual void OnLeftButtonUp(int x, int y, WPARAM params) override; 
  16.    virtual void OnMenuItemClicked(int menuId) override; 
  17.  
  18. public: 
  19.    TicTacToeWindow(); 
  20.    virtual ~TicTacToeWindow() override; 
  21. }; 

#p#

MethodOnPaint()函数用来绘制窗口,它用来绘制窗口背景,网格线,填充的单元格(如果有的话),如果在游戏结束,玩家赢了,一条红线在获胜 行,列或对角线的 标记。为了避免闪烁,我们使用了双缓冲技术:创建一个内存设备文本(通过调用toBeginPaint函数准备窗口的设备文本来匹配),一个内存中的位图 匹配内存设备文本,绘制该位图,然后用窗口设备文本来复制内存设备文本。

  1. void TicTacToeWindow::OnPaint(DeviceContext* dc) 
  2.    RECT rcClient; 
  3.    ::GetClientRect(hWnd, &rcClient); 
  4.  
  5.    auto memdc = ::CreateCompatibleDC(*dc); 
  6.    auto membmp = ::CreateCompatibleBitmap(*dc, rcClient.right - rcClient.left, rcClient.bottom-rcClient.top); 
  7.    auto bmpOld = ::SelectObject(memdc, membmp); 
  8.     
  9.    DrawBackground(memdc, rcClient); 
  10.  
  11.    DrawGrid(memdc, rcClient); 
  12.  
  13.    DrawMarks(memdc, rcClient); 
  14.  
  15.    DrawCut(memdc, rcClient); 
  16.  
  17.    ::BitBlt(*dc,  
  18.       rcClient.left,  
  19.       rcClient.top,  
  20.       rcClient.right - rcClient.left,  
  21.       rcClient.bottom-rcClient.top, 
  22.       memdc,  
  23.       0,  
  24.       0,  
  25.       SRCCOPY); 
  26.  
  27.    ::SelectObject(memdc, bmpOld); 
  28.    ::DeleteObject(membmp); 
  29.    ::DeleteDC(memdc); 

我不会在这里列出DrawBackground,DrawGridand和 DrawMarksfunctions的内容。他们不是很复杂,你可以阅读源代码。DrawMarksfunction使用两个位图,ttt0.bmp和tttx.bmp,绘制网格的痕迹。

我将只显示如何在获胜行,列或对角线绘制红线。首先,我们要检查游戏是否结束,如果结束那么检索获胜线。如果两端都有效,然后计算该两个小区的中心,创建和选择一个画笔(实心,15像素宽的红色线)并且绘制两个小区的中间之间的线。

  1. void TicTacToeWindow::DrawCut(HDC dc, RECT rc) 
  2.    if(game.is_finished()) 
  3.    { 
  4.       auto streak = game.get_winning_line(); 
  5.  
  6.       if(streak.first.is_valid() && streak.second.is_valid()) 
  7.       { 
  8.          int cellw = (rc.right - rc.left) / 3; 
  9.          int cellh = (rc.bottom - rc.top) / 3; 
  10.  
  11.          auto penLine = ::CreatePen(PS_SOLID, 15, COLORREF(0x2222ff)); 
  12.          auto penOld = ::SelectObject(dc, static_cast<HPEN>(penLine)); 
  13.  
  14.          ::MoveToEx( 
  15.             dc,  
  16.             rc.left + streak.first.col * cellw + cellw/2,  
  17.             rc.top + streak.first.row * cellh + cellh/2, 
  18.             nullptr); 
  19.  
  20.          ::LineTo(dc, 
  21.             rc.left + streak.second.col * cellw + cellw/2, 
  22.             rc.top + streak.second.row * cellh + cellh/2); 
  23.  
  24.          ::SelectObject(dc, penOld); 
  25.       } 
  26.    } 

主窗口有三个项目菜单, ID_GAME_STARTUSER在用户先移动时启动一个游戏, ID_GAME_STARTCOMPUTER在当电脑先移动时启动一个游戏, ID_GAME_EXIT用来关闭应用。当用户点击两个启动中的任何一个,我们就必须开始一个游戏任务。如果电脑先移动,那么我们应该是否移动,并且,在所有情况中,都要重新绘制窗口。

  1. void TicTacToeWindow::OnMenuItemClicked(int menuId) 
  2.    switch(menuId) 
  3.    { 
  4.    case ID_GAME_EXIT: 
  5.       ::PostMessage(hWnd, WM_CLOSE, 0, 0); 
  6.       break; 
  7.  
  8.    case ID_GAME_STARTUSER: 
  9.       game.start(tictactoe_player::user); 
  10.       Invalidate(FALSE); 
  11.       break; 
  12.  
  13.    case ID_GAME_STARTCOMPUTER: 
  14.       game.start(tictactoe_player::computer); 
  15.       game.move(tictactoe_player::computer); 
  16.       Invalidate(FALSE); 
  17.       break; 
  18.    } 

#p#

现在只剩下一件事了,就是留意在我们的窗口中处理用户单击鼠标的行为。当用户在我们的窗口客户区内按下鼠标时,我们要去检查是鼠标按下的地方是在哪一个网格内,如果这个网格是空的,那我们就把用户的标记填充上去。之后,如果游戏没有结束,就让电脑进行下一步的移动。

  1. void TicTacToeWindow::OnLeftButtonUp(int x, int y, WPARAM params) 
  2.    if(game.is_started() && !game.is_finished()) 
  3.    { 
  4.       RECT rcClient; 
  5.       ::GetClientRect(hWnd, &rcClient); 
  6.  
  7.       int cellw = (rcClient.right - rcClient.left) / 3; 
  8.       int cellh = (rcClient.bottom - rcClient.top) / 3; 
  9.  
  10.       int col = x / cellw; 
  11.       int row = y / cellh; 
  12.  
  13.       if(game.move(tictactoe_cell(row, col), tictactoe_player::user)) 
  14.       { 
  15.          if(!game.is_finished()) 
  16.             game.move(tictactoe_player::computer); 
  17.  
  18.          Invalidate(FALSE); 
  19.       } 
  20.    } 

最后,我们需要实现WinMain函数,这是整个程序的入口点。下面的代码与这部分开始我给出的代码非常相似,不同的之处是它使用了我对窗口和窗口类进行封装的一些类。

  1. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) 
  2.    WindowClass wndcls(hInstance, L"TicTacToeWindowClass", MAKEINTRESOURCE(IDR_MENU_TTT), CallWinProc);    
  3.  
  4.    TicTacToeWindow wnd; 
  5.    if(wnd.Create( 
  6.       wndcls.Name(),  
  7.       L"Fun C++: TicTacToe",  
  8.       WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,  
  9.       CW_USEDEFAULT,  
  10.       CW_USEDEFAULT,  
  11.       300,  
  12.       300,  
  13.       hInstance)) 
  14.    { 
  15.       wnd.ShowWindow(nCmdShow); 
  16.  
  17.       MSG msg; 
  18.       while(::GetMessage(&msg, nullptr, 0, 0)) 
  19.       { 
  20.          ::TranslateMessage(&msg); 
  21.          ::DispatchMessage(&msg); 
  22.       } 
  23.  
  24.       return msg.wParam; 
  25.    } 
  26.  
  27.    return 0; 

虽然我觉得我放在这里的代码是相当的短小精焊,但如果你不熟悉Win32 API程序设计,你仍然可能会觉得这些代码有点复杂。无论如何,你都一定要清楚的了解对象的初始化、如何创建一个窗口、如何处理窗口消息等。但愿你会觉得下一部分更有趣。

一个Windows Runtime的游戏app

Windows Runtime是Windows 8引入的一个新的Windows运行时引擎. 它依附于Win32并且有一套基于COM的API. 为Windows Runtime创建的app通常很糟糕,被人称为"Windows商店" 应用. 它们运行在Windows Runtime上, 而不是Windows商店里, 但是微软的市场营销人员可能已经没什么创造力了. Windows Runtime 应用和组件可以用C++实现,不管是用Windows Runtime C++ Template Library (WTL) 或者用 C++ Component Extensions (C++/CX)都可以. 在这里我将使用XAML和C++/CX来创建一个功能上和我们之前实现的桌面版应用类似的应用。

当你创建一个空的Windows Store XAML应用时向导创建的项目实际上并不是空的, 它包含了所有的Windows Store应用构建和运行所需要的文件和配置。但是这个应用的main page是空的。

我们要关心对这篇文章的目的,唯一的就是主界面。 XAML代码可以在应用在文件MainPage.xaml中,和背后的MainPage.xaml.h MainPage.xaml.cpp的代码。,我想建立简单的应用程序如下图。

下面是XAML的页面可能看起来的样子(在一个真实的应用中,你可能要使用应用程序栏来操作,如启动一个新的游戏,主页上没有按键,但为了简单起见,我把它们在页面上)

  1. <Page 
  2.     x:Class="TicTacToeWinRT.MainPage" 
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  5.     xmlns:local="using:TicTacToeWinRT" 
  6.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  7.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  8.     mc:Ignorable="d">    
  9.     
  10.    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> 
  11.       <Grid.RowDefinitions> 
  12.          <RowDefinition Height="Auto" /> 
  13.          <RowDefinition Height="Auto" /> 
  14.          <RowDefinition Height="Auto" /> 
  15.          <RowDefinition Height="Auto" /> 
  16.       </Grid.RowDefinitions> 
  17.        
  18.       <TextBlock Grid.Row="0" Text="Fun C++: Tic Tac Toe"  
  19.                  Foreground="White" FontSize="42" FontFamily="Segoe UI" 
  20.                  Margin="10" 
  21.                  HorizontalAlignment="Center" VerticalAlignment="Center" 
  22.                  /> 
  23.  
  24.       <TextBlock Grid.Row="1" Text="Computer wins!" 
  25.                  Name="txtStatus" 
  26.                  Foreground="LightGoldenrodYellow"  
  27.                  FontSize="42" FontFamily="Segoe UI" 
  28.                  Margin="10" 
  29.                  HorizontalAlignment="Center" VerticalAlignment="Center" /> 
  30.        
  31.       <Grid Margin="50" Width="400" Height="400" Background="White" 
  32.             Name="board" 
  33.             PointerReleased="board_PointerReleased" 
  34.             Grid.Row="2"> 
  35.          <Grid.ColumnDefinitions> 
  36.             <ColumnDefinition Width="1*" /> 
  37.             <ColumnDefinition Width="1*" /> 
  38.             <ColumnDefinition Width="1*" /> 
  39.          </Grid.ColumnDefinitions> 
  40.          <Grid.RowDefinitions> 
  41.             <RowDefinition Height="1*" /> 
  42.             <RowDefinition Height="1*" /> 
  43.             <RowDefinition Height="1*" /> 
  44.          </Grid.RowDefinitions> 
  45.  
  46.          <!-- Horizontal Lines --> 
  47.          <Rectangle Grid.Row="0" Grid.ColumnSpan="3" Height="1" VerticalAlignment="Bottom" Fill="Black"/> 
  48.          <Rectangle Grid.Row="1" Grid.ColumnSpan="3" Height="1" VerticalAlignment="Bottom" Fill="Black"/> 
  49.          <Rectangle Grid.Row="2" Grid.ColumnSpan="3" Height="1" VerticalAlignment="Bottom" Fill="Black"/> 
  50.          <!-- Vertical Lines --> 
  51.          <Rectangle Grid.Column="0" Grid.RowSpan="3" Width="1" HorizontalAlignment="Right" Fill="Black"/> 
  52.          <Rectangle Grid.Column="1" Grid.RowSpan="3" Width="1" HorizontalAlignment="Right" Fill="Black"/> 
  53.          <Rectangle Grid.Column="2" Grid.RowSpan="3" Width="1" HorizontalAlignment="Right" Fill="Black"/> 
  54.                            
  55.       </Grid> 
  56.        
  57.       <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Grid.Row="3"> 
  58.          <Button Name="btnStartUser" Content="Start user" Click="btnStartUser_Click" /> 
  59.          <Button Name="btnStartComputer" Content="Start computer" Click="btnStartComputer_Click"/> 
  60.       </StackPanel> 
  61.        
  62.    </Grid> 
  63. </Page> 

#p#

与win32桌面版的游戏不同,在Windows Runtime的程序中,我们不必关心用户界面的绘制,但我们还得创建UI元素。比如,当用户在玩游戏的时候,在其中一个格子里单击了鼠标,我们就必须创 建一个UI元素来表示一个标记。为此,我会用在桌面版(too.bmp and ttx.bmp)中用过的位图,并且在图像控件中显示它们.。我还会在获胜的行、列、或对角线上画一个红色的线,为此,我会用到Lineshape类。

我们可以直接把tictactoe_game的源代码(game.h, game.cpp, strategy_x.h and strategy_o.h)添加到工程里。或者我们可以把它们导出成一个单独的DLL。为了方便,我使用了相同的源文件。然后我们必须添加一个tictactoe_game对象到MainPage类中。

  1. #pragma once 
  2.  
  3. #include "MainPage.g.h" 
  4. #include "..\Common\game.h" 
  5.  
  6. namespace TicTacToeWinRT 
  7.    public ref class MainPage sealed 
  8.    { 
  9.    private: 
  10.       tictactoe_game game; 
  11.  
  12.       // ...  
  13.    }; 
  14. }       

这里有3类基本的事件处理handler需要我们自己实现:

  • 处理“Start user”按钮的theClickedevent事件的handler
  • 处理“Start computer”按钮的theClickedevent事件的handler
  • 处理面板网格的thePointerReleasedevent事件的handler,当指针(鼠标或者手势)从网格释放时被调用。

对这两个按钮点击的handler,在逻辑上与我们在Win32桌面应用中实现的类似。首先,我们必须要重置游戏(一会会看到这代表什么意思)。如果玩家 先开始,那么我们仅仅只需要用正确的策略来初始化游戏对象。如果是电脑先开始,那我们除了要初始化策略,还要让电脑呈现出真正走了一步并且在电脑走的那一 步的单元格上做上标记。

  1. void TicTacToeWinRT::MainPage::btnStartUser_Click(Object^ sender, RoutedEventArgs^ e) 
  2.    ResetGame(); 
  3.  
  4.    game.start(tictactoe_player::user); 
  5.  
  6. void TicTacToeWinRT::MainPage::btnStartComputer_Click(Object^ sender, RoutedEventArgs^ e) 
  7.    ResetGame(); 
  8.  
  9.    game.start(tictactoe_player::computer); 
  10.    auto cell = game.move(tictactoe_player::computer); 
  11.     
  12.    PlaceMark(cell, tictactoe_player::computer); 

PlaceMark()方法创建了一个newImagecontrol控件,设定它的Source是tttx.bmp或者ttt0.bmp,并且把它添加到所走的那一步的面板网格上。

  1. void TicTacToeWinRT::MainPage::PlaceMark(tictactoe_cell const cell, tictactoe_player const player) 
  2.    auto image = ref new Image(); 
  3.    auto bitmap = ref new BitmapImage( 
  4.       ref new Uri(player == tictactoe_player::computer ? "ms-appx:///Assets/tttx.bmp" : "ms-appx:///Assets/ttt0.bmp")); 
  5.    bitmap->ImageOpened += ref new RoutedEventHandler(  
  6.       [this, image, bitmap, cell](Object^ sender, RoutedEventArgs^ e) { 
  7.          image->Width = bitmap->PixelWidth; 
  8.          image->Height = bitmap->PixelHeight; 
  9.          image->Visibility = Windows::UI::Xaml::Visibility::Visible; 
  10.    }); 
  11.  
  12.    image->Source = bitmap
  13.  
  14.    image->Visibility = Windows::UI::Xaml::Visibility::Collapsed; 
  15.    image->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Center; 
  16.    image->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Center; 
  17.  
  18.    Grid::SetRow(image, cell.row); 
  19.    Grid::SetColumn(image, cell.col); 
  20.  
  21.    board->Children->Append(image); 

当开始一场新游戏时,这些在游戏过程中被添加到网格上的Imagecontrol控件需要被移除掉。这正是theResetGame()method方法所做的事情。此外,它还移除了游戏胜利时显示的红线和显示游戏结果的文字。

  1. void TicTacToeWinRT::MainPage::ResetGame() 
  2.    std::vector<Windows::UI::Xaml::UIElement^> children; 
  3.  
  4.    for(auto const & child : board->Children) 
  5.    { 
  6.       auto typeName = child->GetType()->FullName; 
  7.       if(typeName == "Windows.UI.Xaml.Controls.Image" || 
  8.          typeName == "Windows.UI.Xaml.Shapes.Line") 
  9.       { 
  10.          children.push_back(child); 
  11.       } 
  12.    } 
  13.  
  14.    for(auto const & child : children) 
  15.    { 
  16.       unsigned int index; 
  17.       if(board->Children->IndexOf(child, &index)) 
  18.       { 
  19.          board->Children->RemoveAt(index); 
  20.       } 
  21.    } 
  22.  
  23.    txtStatus->Text = nullptr

#p#

当玩家在一个单元格上点击了一下指针,并且这个单元格是没有被占据的,那我们就让他走这一步。如果这时游戏还没有结束,那我们也让电脑走一步。当游戏在玩 家或者电脑走过一步之后结束,我们会在一个text box中显示结果并且如果有一方胜利,会在胜利的行,列或对角上划上红线。

  1. void TicTacToeWinRT::MainPage::board_PointerReleased(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e) 
  2.    if(game.is_started() && ! game.is_finished()) 
  3.    { 
  4.       auto cellw = board->ActualWidth / 3; 
  5.       auto cellh = board->ActualHeight / 3; 
  6.  
  7.       auto point = e->GetCurrentPoint(board); 
  8.       auto row = static_cast<int>(point->Position.Y / cellh); 
  9.       auto col = static_cast<int>(point->Position.X / cellw); 
  10.  
  11.       game.move(tictactoe_cell(row, col), tictactoe_player::user); 
  12.       PlaceMark(tictactoe_cell(row, col), tictactoe_player::user); 
  13.  
  14.       if(!game.is_finished()) 
  15.       { 
  16.          auto cell = game.move(tictactoe_player::computer); 
  17.          PlaceMark(cell, tictactoe_player::computer); 
  18.  
  19.          if(game.is_finished()) 
  20.          { 
  21.             DisplayResult( 
  22.                game.is_victory(tictactoe_player::computer) ?  
  23.                tictactoe_player::computer : 
  24.                tictactoe_player::none); 
  25.          } 
  26.       } 
  27.       else 
  28.       { 
  29.          DisplayResult( 
  30.             game.is_victory(tictactoe_player::user) ?  
  31.             tictactoe_player::user : 
  32.             tictactoe_player::none); 
  33.       } 
  34.    } 
  35.  
  36. void TicTacToeWinRT::MainPage::DisplayResult(tictactoe_player const player) 
  37.    Platform::String^ text = nullptr
  38.    switch (player) 
  39.    { 
  40.    case tictactoe_player::none: 
  41.       text = "It's a draw!"
  42.       break; 
  43.    case tictactoe_player::computer: 
  44.       text = "Computer wins!"
  45.       break; 
  46.    case tictactoe_player::user: 
  47.       text = "User wins!"
  48.       break; 
  49.    } 
  50.  
  51.    txtStatus->Text = text
  52.  
  53.    if(player != tictactoe_player::none) 
  54.    { 
  55.       auto coordinates = game.get_winning_line(); 
  56.       if(coordinates.first.is_valid() && coordinates.second.is_valid()) 
  57.       { 
  58.          PlaceCut(coordinates.first, coordinates.second); 
  59.       } 
  60.    } 
  61.  
  62. void TicTacToeWinRT::MainPage::PlaceCut(tictactoe_cell const start, tictactoe_cell const end) 
  63.    auto cellw = board->ActualWidth / 3; 
  64.    auto cellh = board->ActualHeight / 3; 
  65.  
  66.    auto line = ref new Line(); 
  67.    line->X1 = start.col * cellw + cellw / 2; 
  68.    line->Y1 = start.row * cellh + cellh / 2; 
  69.  
  70.    line->X2 = end.col * cellw + cellw / 2; 
  71.    line->Y2 = end.row * cellh + cellh / 2; 
  72.  
  73.    line->StrokeStartLineCap = Windows::UI::Xaml::Media::PenLineCap::Round; 
  74.    line->StrokeEndLineCap = Windows::UI::Xaml::Media::PenLineCap::Round; 
  75.    line->StrokeThickness = 15
  76.    line->Stroke = ref new SolidColorBrush(Windows::UI::Colors::Red); 
  77.  
  78.    line->Visibility = Windows::UI::Xaml::Visibility::Visible; 
  79.  
  80.    Grid::SetRow(line, 0); 
  81.    Grid::SetColumn(line, 0); 
  82.    Grid::SetRowSpan(line, 3); 
  83.    Grid::SetColumnSpan(line, 3); 
  84.  
  85.    board->Children->Append(line); 

到这里就全部结束了,你可以build它了,启动它然后玩吧。它看起来像这样:

在这篇文章中,我们已经看到了,我们可以在C + +中使用不同的用户界面和使用不同的技术创建一个简单的游戏。首先我们写游戏思路是使用标准的C + +,来用它来构建使用完全不同的技术创建的两个应用程序:在这里我们不得不使用Win32 API来做一些工作,比如创建一个绘制窗口,并且能够在运行时使用XAML。在那里,框架做了大部分的工作,所以我们可以专注于游戏逻辑(在后面的代码里 我必须说明我们不得不去设计UI,而不仅仅使用XAML)。其中包括我们看到的如何能够使用标准的容器asstd:: arrayandstd:: setand,我们如何使用纯C++逻辑代码在C++/CX中完美的运行。

 原文链接:http://www.codeproject.com/Articles/678078/Cplusplus-is-fun-Writing-a-Tic-Tac-Toe-Game

译文链接:http://www.oschina.net/translate/cplusplus-is-fun-writing-a-tic-tac-toe-game

责任编辑:陈四芳 来源: 开源中国编译
相关推荐

2021-01-05 12:38:53

C++编程语言软件开发

2021-01-14 08:55:20

C语言编程

2021-05-04 16:38:54

Linux数学游戏

2021-04-13 06:35:13

Elixir语言编程语言软件开发

2021-01-01 19:30:21

Python编程语言

2021-02-05 16:03:48

JavaScript游戏学习前端

2024-01-15 07:47:09

井字棋游戏编程练习Python

2011-09-16 10:00:56

C++

2010-08-18 08:53:53

Scala

2021-01-03 16:30:34

Rust编程语言

2009-09-11 09:11:09

2021-05-28 18:12:51

C++设计

2024-02-26 10:22:53

2023-01-02 18:15:42

PythonC++模块

2020-02-21 10:21:42

云计算边缘计算网络

2015-08-27 13:37:29

2010-01-14 14:40:21

C++代码

2010-01-26 14:35:11

C++关键字

2013-07-18 09:58:18

C++程序员

2022-06-27 09:54:38

编程语言JavaC++
点赞
收藏

51CTO技术栈公众号