Question:
How do i make a grid layout using a 2D array?
Andy B
2009-01-12 12:28:42 UTC
I have to make a connect 4 game for my computer programming class and i have to use a 2D array to make the buttons in a grid layout except I don't know how. Please help me.
Three answers:
[ J ] a [ Y ]
2009-01-12 12:40:43 UTC
bool MyGrid[x][y]; (c, c++)



dim MyGrid(x,y) as Boolean (Visual Basic)



where x = the number of positions horizontally, and y = the number of positions vertically. I chose a bool just because really you only need to store weather or not somebody has placed a connect 4 piece in that spot yet (assuming you dont want to be graphical).



If you do want to use graphics, i'd say you probably arent ready if you're posting this question, but SDL is nice to use.
Jeremy T
2009-01-12 12:47:38 UTC
conceptually, the first or outer array stores a bunch of arrays. The second or inner arrays stores individual places for that arrays row.



so myArray[4][2]



would be the 5th array from the bottom (0, 1, 2, 3, 4) and 3rd element from the left (0, 1, 2).



Counting whether your counting from the top, bottom, left, or right, depends entirely on how you implement your print function (the code to display the board to a user). Just be sure your consistent throughout the program.



Assuming there are 2 players, you can't use booleans like the other answer suggested. boolean only allows 0 or 1. You 3 options, empty, player1, or player2.
anonymous
2009-01-12 12:42:06 UTC
Each element becomes an array of four, not knowing what language you are using but basicly its no different than any other array - just each element is also an array.



Let me show you what a 2D array can look like. This is in C



char FamilyNames[4][5] = { "Dave", "Jill", "Chris", "Ben"; };



in the above example, to access any specific name I would use



FamilyNames[ELEMENT] - and that would return the whole array. If I wanted to access the i in jill I would do this:

FamilyNames[1][1].



Note that in teh above example, all the names must be 5 characters long because the longest, Dave is 4 chars + null terminator. Same with Jill and Chris. Ben however could be shorter, but since this is a 2D array, the memory must be equal for all. In C i can get around this by creating an array of pointers to arrays



char *FamilyNames[4] = {"Dave", "Jill", "Chris", "Ben" };



In the above I prevent from wastin the memory of the extra char in ben.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...