我正在开发一个tic tac toe游戏,需要创建一个根据用户输入创建棋盘的功能。可以是3x3或更大我到目前为止有这个,但是当我运行时打印内存位置。
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
// Array which creates boeard based on user input
int *drawboard(int width, int height)
{
int* board_data = new int[width * height];
int** board = new int* [width];
for (int i = 0; i < width; ++i)
{
board[i] = board_data + height * i;
}
return board_data;
}
void main()
{
int width = 0;
int height = 0;
cout << " Welcome to Tic Tac Toe v1! " << endl;
cout << " Choose your board size, enter width: " << endl;
cin >> width;
cout << " Choose your height: " << endl;
cin >> height;
cout << drawboard << endl;
int *board = drawboard(width, height);
delete[] board;
system("pause");
}
答案 0 :(得分:0)
我认为this post会帮助你很多。看来你只是试图声明一个动态的2D整数数组,然后使用虚拟2D数组作为tic tac toe board,对吗?
不完全确定drawboard()
的含义,但这是一种打印网格的简单方法:
void printGrid(int y, int x) {
for (int j = 0; j < y; j++) {
for (int i = 0; i < x; i++) cout << " ---";
cout << endl;
for (int i = 0; i < x; i++) cout << "| ";
cout << "|" << endl;
}
for (int i = 0; i < x; i++) cout << " ---";
cout << endl;
}
答案 1 :(得分:0)
这是我的代码,当我运行它我的输出是 AAA BBB CCC 如果我输入3x3板
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <iomanip>
using namespace std;
// Array which creates boeard based on user input
char **createboard(int rows, int cols)
{
char** boardArray = new char*[rows];
for (int i = 0; i < rows; ++i) {
boardArray[i] = new char[cols];
}
// Fill the array
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
boardArray[i][j] = char(i + 65);
}
}
// Output the array
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << boardArray[i][j];
}
cout << endl;
}
// Deallocate memory by deleting
for (int i = 0; i < rows; ++i) {
delete[] boardArray[i];
}
delete[] boardArray;
return boardArray;
}
int main()
{
int rows = 0;
int cols = 0;
char **boardArray = createboard(rows, cols);
cout << " Welcome to Tic Tac Toe v1! " << endl;
cout << " Choose your board width: " << endl;
cin >> rows;
cout << " Choose your board height " << endl;
cin >> cols;
cout << endl;
createboard(rows, cols);
system("pause");
}