2017-07-26 69 views
1

我正在進行井字棋遊戲,需要創建一個基於用戶輸入創建棋盤的功能。可以是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

看起來像它應該那樣工作。你正在打印一個指針。 – Borgleader

+0

是的,它的工作原理,但是當我輸入我的寬度和高度時,它打印歡迎來到Tic Tac Toe v1! 選擇您的板尺寸,輸入寬度:選擇您的高度: 00CB14A1 – Krowe3

+0

正如我所說的,您正在將drawboard的函數指針傳遞給標準輸出。這樣做沒什麼意義,但輸出是我所期望的。即使你通過了drawboard的結果,你也會得到類似的結果。如果你想在一個漂亮的2D網格中打印實際的電路板,你必須爲它編寫代碼。我不確定你的問題在這裏,因爲你還沒有問過。 – Borgleader

回答

0

我認爲this post會幫你出了很多。看起來你只是試圖聲明一個動態的二維整數數組,然後使用虛擬二維數組作爲井字遊戲板,對吧? 不太清楚你的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; 
} 
+0

是的,我卡住了,我想寫一個打印數組的代碼,所以如果用戶輸入一個3x3的數組,它會打印出網格形狀的{「123456789」} – Krowe3

+0

您是否認識到我有超鏈接,我說「this後「?我認爲你可能錯過了 – Lindens

+0

謝謝你現在幫助了很多,我所要做的就是爲玩家移動x和o創建一個函數 – Krowe3

0

這是我的代碼,當我運行它,我的輸出是 AAA BBB CCC 如果我輸入的3×3板

#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"); 

}