Reputation: 69
I am making a simple text based game, but when i try to compile it, it gives me an error on the for loop. It doesn't recognize it and gives me an error the word for and on the end brackets.
using System;
namespace ThreeDGame {
class Player {
private int px=1;
private int py=1;
private int pz=1;
public Player(int x, int y, int z) {
px=x;
py=y;
pz=z;
}
public void xp() {
if (++px=10) {
px=1;
}
}
public void xn() {
if (--px=0) {
px=9;
}
}
public void yp() {
if (++py=10) {
py=1;
}
}
public void yn() {
if (--py=0) {
py=9;
}
}
public void zp() {
if (++pz=10) {
pz=1;
}
}
public void zn() {
if (--pz=0) {
pz=9;
}
}
}
class Board {
string[] board = new string[9,9,9];
for (int x=0; x<9; x++) {
for (int y=0; y<9; y++) {
for (int z=0; z<9; z++) {
board[x,y,z] = "~";
}
}
}
public void DispBoard(int z) {
for (int a=1; a>=9; a++) {
Console.WriteLine();
for (int b=1; b>=9; b++) {
Console.Write(board[a-1,b-1,z-1]);
}
}
}
}
class Game {
static void Main() {
Board b = new Board();
b.DispBoard(1);
}
}
}
If anyone knows how to solve this, please share.
Upvotes: 0
Views: 276
Reputation: 186833
You have to implement Board
class constructor:
class Board {
//DONE: string[,,] - you want a 3d array, right?
string[,,] board = new string[9, 9, 9];
//DONE: you can't just run loop within the class, but within a constructor (or method)
public Board() {
//DONE: do not use magic values (9), but GetLength(dimension)
for (int x = 0; x < board.GetLength(0); ++x)
for (int y = 0; y < board.GetLength(1); ++y)
for (int z = 0; z < board.GetLength(2); ++z)
board[x, y, z] = "~";
}
public void DispBoard(int z) {
//DONE: validate public methods' values
if ((z < 1) || (z > board.GetLength(2)))
throw new ArgumentOutOfRangeException("z");
//DONE: wrong condition ">= 9" changed into right one "< board.GetLength(0)"
for (int x = 0; x < board.GetLength(0); ++x) {
Console.WriteLine();
//DONE: wrong condition ">= 9" changed into right one "< board.GetLength(1)"
for (int y = 0; y < board.GetLength(1); ++y)
Console.Write(board[x, y, z - 1]);
}
}
}
Upvotes: 2
Reputation: 1
You can create a contractor and call the method of loop.
class Board {
public Board(){
dosometing();
}
public void dosometing(){
string[] board = new string[9,9,9];
for (int x=0; x<9; x++) {
for (int y=0; y<9; y++) {
for (int z=0; z<9; z++) {
board[x,y,z] = "~";
}
}
}
public void DispBoard(int z) {
for (int a=1; a>=9; a++) {
Console.WriteLine();
for (int b=1; b>=9; b++) {
Console.Write(board[a-1,b-1,z-1]);
}
}
}
}
}
Upvotes: 0
Reputation: 5745
your first loop is not part of a method this part : for (int x=0; x<9; x++) ...
created a method and insert the loops into it
Upvotes: 2