Creating a game board using a one dimensional array

Does anyone know how to make a game board using a one dimensional array.
Last edited on
Let's say you have a grid with dimensions 10 * 10.
You could access such a grid using (x,y) coordinates.

If you replace that with a linear array of size 100 (that is, 10 * 10), you could still access it using (x,y) coordinates, but you would use something like (x + 10*y) as the array subscript.

If you use functions to handle this, then the detail of how the board is actually stored becomes relatively unimportant, the function would be called in exactly the same way in either case.
@GhostCas

Here's a bit of clarification on Chervil's solution. I didn't use a function, but it would easy enough to convert.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Battleship.cpp : main project file.

#include <iostream>

using namespace std;

int main()
{
	int board[100] = { 0 };// Board is a 10x10. 100 spaces
	int row = 0, column = 0, location=0;
	cout << "Show enpty board." << endl;
	for (int x = 0; x < 100; x++)
	{
		cout << board[x] << " ";// Putting a space between numbers
		if ((x + 1) % 10 == 0)
			cout << endl; // Start a new line
	}
	cout << "Which row [1 to 10] ? " << endl; // Not doing error check.
	// Up to you to enter ONLY 1 thru 10
	cin >> row;
	cout << "Which column [1 to 10] ? " << endl; // Still not doing error check.
	cin >> column;
	cout << "Putting the number 2, at location "<<row << ", " << column << endl;
	location = ((row - 1) * 10) + (column-1);
	// Subtract 1 from row and column, since array starts at zero
	board[location] = 2;
	for (int x = 0; x < 100; x++)
	{
		cout << board[x] << " ";// Putting a space between numbers
		if ((x + 1) % 10 == 0)
			cout << endl; // Start a new line
	}
	cin >> row;// Just to keep console open
	return 0;
}
Really helped thanx a lot
Topic archived. No new replies allowed.