【发布时间】:2018-01-26 12:34:49
【问题描述】:
我正在阅读用 C++ (Link) 实现的“15 Puzzle Game”的代码。
代码
#include <time.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include <iostream>
class p15 {
public :
void play() {
bool p = true;
std::string a;
while( p ) {
createBrd();
while( !isDone() ) { drawBrd();getMove(); }
drawBrd();
std::cout << "\n\nCongratulations!\nPlay again (Y/N)?";
std::cin >> a; if( a != "Y" && a != "y" ) break;
}
}
private:
void createBrd() {
int i = 1; std::vector<int> v;
for( ; i < 16; i++ ) { brd[i - 1] = i; }
brd[15] = 0; x = y = 3;
for( i = 0; i < 1000; i++ ) {
getCandidates( v );
move( v[rand() % v.size()] );
v.clear();
}
}
void move( int d ) {
int t = x + y * 4;
switch( d ) {
case 1: y--; break;
case 2: x++; break;
case 4: y++; break;
case 8: x--;
}
brd[t] = brd[x + y * 4];
brd[x + y * 4] = 0;
}
void getCandidates( std::vector<int>& v ) {
if( x < 3 ) v.push_back( 2 ); if( x > 0 ) v.push_back( 8 );
if( y < 3 ) v.push_back( 4 ); if( y > 0 ) v.push_back( 1 );
}
void drawBrd() {
int r; std::cout << "\n\n";
for( int y = 0; y < 4; y++ ) {
std::cout << "+----+----+----+----+\n";
for( int x = 0; x < 4; x++ ) {
r = brd[x + y * 4];
std::cout << "| ";
if( r < 10 ) std::cout << " ";
if( !r ) std::cout << " ";
else std::cout << r << " ";
}
std::cout << "|\n";
}
std::cout << "+----+----+----+----+\n";
}
void getMove() {
std::vector<int> v; getCandidates( v );
std::vector<int> p; getTiles( p, v ); unsigned int i;
while( true ) {
std::cout << "\nPossible moves: ";
for( i = 0; i < p.size(); i++ ) std::cout << p[i] << " ";
int z; std::cin >> z;
for( i = 0; i < p.size(); i++ )
if( z == p[i] ) { move( v[i] ); return; }
}
}
void getTiles( std::vector<int>& p, std::vector<int>& v ) {
for( unsigned int t = 0; t < v.size(); t++ ) {
int xx = x, yy = y;
switch( v[t] ) {
case 1: yy--; break;
case 2: xx++; break;
case 4: yy++; break;
case 8: xx--;
}
p.push_back( brd[xx + yy * 4] );
}
}
bool isDone() {
for( int i = 0; i < 15; i++ ) {
if( brd[i] != i + 1 ) return false;
}
return true;
}
int brd[16], x, y;
};
int main( int argc, char* argv[] ) {
srand( ( unsigned )time( 0 ) );
p15 p; p.play(); return 0;
}
/*
Possible Output:
+----+----+----+----+
| 11 | 5 | 12 | 3 |
+----+----+----+----+
| 10 | 7 | 6 | 4 |
+----+----+----+----+
| 13 | | 2 | 1 |
+----+----+----+----+
| 15 | 14 | 8 | 9 |
+----+----+----+----+
Possible moves: 2 13 14 7
*/
虽然我理解了大部分代码,但有些部分对我来说似乎不清楚:
A.为什么 for 循环会迭代 1000 次?为什么选择数字 1000?
for( i = 0; i < 1000; i++ )
B.在上面的循环中,为什么每次迭代都会调用一次v.clear();?
C.代码中的数字1、2、4和8有什么意义(用于开关块)?
D. getCandidates() 函数是如何工作的?
【问题讨论】:
-
B、C 和 D 无法回答,因为代码不在问题中。
-
1) 所有相关代码必须在问题本身中,而不是在外部链接中。 2) 你为什么要问我们,而不是代码的作者?
-
@Blacktempel 代码大约有 90 行,所以我不知道是否应该发布链接或代码本身。我已经编辑了问题。
-
@aks "代码大约有 90 行,所以我不知道应该发布链接还是代码本身。" 然后,请仔细阅读 help center和How to Ask。关于代码的问题,必须始终包含minimal reproducible example,作为文本。
-
了解代码在做什么;使用调试器。您遇到了 90 行的问题;想象一下,最后还有 5 或 6 个 0 会是什么样子!您逐步了解您不理解的部分,当您最终找到在线记录的内容时,您可以建立您的理解。