c# - Selecting indexes from Multidimensional Array where the value is 0 is not working -
please given task return indexes 2d array updating. assignment on 2048 game . when ever, random numb added, want added randomly free/empty tiles should be. thats array value 0 in case.
private static int[][] addtile() { rd = new random(); int px, py; px = rd.next(0, 4); py = rd.next(0, 4); list<int> availableind = randposition(py); int r = rd.next(0, availableind.count); int newpx = availableind[0]; if (tiles[py][newpx] == 0) { tiles[py][newpx] = rd.next(0, 20) == 0 ? rd.next(0, 15) == 0 ? 8 : 4 : 2; } else { py = py; // put break here } }
my randposition() method loks fflg;
public static list<int> randposition(int num) { list<int> indexes = new list<int>(); // var emptytiles = arr.where(x => x == 0).tolist(); indexes = tiles[num].select((s, index) => new { s, index }) .where(x => x.s == 0) .select(x => x.index) .tolist(); if (indexes.count > 0) return indexes; //incase above fails. seach row row //for empty tile (int c = 0; c < tiles.count(); c++) { indexes = tiles[c].select((s, index) => new { s, index }) .where(x => x.s == 0) .select(x => x.index) .tolist(); if (indexes.count > 0) break; } return indexes; }
first ramdomly generate y-axis , pass randposition check if there exist empty cell in said axis. if there , indexes of cells. if there not, perform advance row row search below make sure empty tiles returned. however, when put break @ else of first method, realized still occupied tiles/cells return empty. tried alot of manipulations yet no avail. please go wrong ? how best handle ? suggestion or alternative highly appreciated. thank you
this of guess, think have logic error:
randposition(num)
supposed return "empty" cells in row num
. if not find any, searches row-by-row until find empty cell.
the problem is, the caller doesn't know if original search failed. it's entirely possible indices returned represent cells of different row asked for. may why see "occupied" cells returned "empty".
here's analogy:
you're taking trip new york. go airport book flight (i know, no 1 anymore). ask empty seats on row 7 (because row 7). customer service agent looks row 7 , finds there no empty seats. instead of telling that, instead start looking through other rows , finds empty seat (c) on row 15. tells "seat c empty". problem is, you think she's talking row 7! have no indication row 7 full or row she's referring to.
either caller needs iterate through other rows (so knows row empty cells on), or method needs have sort of feedback indicates which row empty cells on.
Comments
Post a Comment