2016-03-16 3 views
0

Я создаю игру Sudoku с ASP.NET и C#. Я должен использовать классы и наследование, чтобы полностью построить структуру на странице с кодом (т. Е. Элементы asp: TextBox на странице aspx отсутствуют).Очистка TextBoxes в C#

У меня ужасное время, пытаясь очистить входные данные, когда я начинаю новую игру. Я создаю новое решение для головоломок, но мои предыдущие ящики не ясны, и я пробовал все, что мог придумать.

Ниже приведены несколько фрагментов кода, которые относятся к проблеме.



код, который строит головоломки и сохраняет его в головоломку объекта.

private Puzzle newPuzzle(int[,] solution, int numbersVisible, int maxNumbersPerBox, int maxOccurancesPerNumber) 
{ 
    Puzzle newPuzzle = new Puzzle(); 
    SudokuTextBox newTextbox; 
    Number newNumber; 

    Random randomRC = new Random(); 

    //variable to hold the correct answer at the given location 
    int answer; 
    //variables to hold the location within the answers array 
    int rowLoc; 
    int colLoc; 
    //counter to count the number of times we while loop 
    int counter = 0; 
    //variables to hold the randomly-chosen rows & col values 
    int row; 
    int col; 
    //array to hold the positions of the numbers we are going to show 
    string[] show; 
    show = new string[numbersVisible]; 

    while(counter < numbersVisible) 
    { 
     //generate random numbers that gives us the location of the numbers in the solution array that we are going to show 
     row = randomRC.Next(0, 9); 
     col = randomRC.Next(0, 9); 

     //if the random numbers are not already in the array 
     if (!show.Contains(row.ToString() + ":" + col.ToString())) 
     { 
      //add them to the array 
      show[counter] = row.ToString() + ":" + col.ToString(); 

      //increase the counter 
      counter++; 
     } //end if...contains 

    } //end while 


    // BUILDING THE PUZZLE 
    //start looping through the puzzle rows 
    for (int pr = 0; pr < 3; pr++) 
    { 
     //another loop for puzzle columns 
     for (int pc = 0; pc < 3; pc++) 
     { 
      box = new Box();    //create a new Box object 
      //another loop for box rows 
      for (int br = 0; br < 3; br++) 
      { 
       //another loop for box columns 
       for (int bc = 0; bc < 3; bc++) 
       { 
        newTextbox = new SudokuTextBox(); 
        newNumber = new Number(); 

        //grab the answer to this particular SudokuTextBox from the solutions array 
        rowLoc = (pr + br + (2 * pr)); 
        colLoc = (pc + bc + (2 * pc)); 
        answer = solution[rowLoc, colLoc]; 
        newNumber.setNumber(answer);      //set the Number to the found answer 
        newTextbox.setTextBoxValue(newNumber);    //fill in the textbox with Number 

        //if this SudokuTextBox is chosen to be given at the start of the puzzle 
        if (show.Contains((rowLoc + ":" + colLoc).ToString())) 
        { 
         //make this SudokuTextBox visible 
         newTextbox.setVisibility(true); 
        } 
        else { 
         newTextbox.setVisibility(false); 
        } //end if 

        box.setItem(newTextbox, br, bc);     //add the SudokuTextBox to the correct position inside Box 
       } //end box column loop 
      } //end box row loop 
      newPuzzle.setItem(box, pr, pc);  //add the Box to the correct position inside Puzzle 
     } //end puzzle column loop 
    } //end puzzle row loop 

    return newPuzzle; 
} //end easy() 



Сохранение новой головоломки в сессии:

//when the Easy button is pressed 
protected void btnEasy_Click(object sender, EventArgs e) 
{ 
    //generate a new random number 
    Random newRandomSoln = new Random(); 


    //keep picking new solutions until we get one that's different than the last one 
    do 
    { 
     solution = chooseSolution(newRandomSoln.Next(1, 11)); 
    } 
    while (solution == Session["solution"]); 

    //store the new solution 
    Session["solution"] = solution; 

    //generate a new puzzle 
    Session["puzzle"] = newPuzzle((int[,])Session["solution"], 32, 4, 4); 
} 



код, который строит структуру таблицы, заполняет его ответы хранятся в головоломки, и добавляет его на страницу aspx:

//////////////////////////////// 
    // CREATING THE PUZZLE 
    /////////////////////////////// 
    Table structure = new Table();  //table to be the outer structure of the puzzle 
    TableRow row;      //row variable to make new rows 
    TableCell cell;      //cell variable to make new cells 
    Table boxTable;      //table that will hold individual Boxes 
    TableRow boxRow;     //row that will hold 3 SudokuTextBoxes 
    TableCell boxCell;     //cell that will hold a single SudokuTextBoxes 
    TextBox input;      //textbox that will hold the textbox in SudokuTextBox 
    int answer;       //int to hold the answer to a particular textbox 


    //start looping through the puzzle rows 
    for (int pr = 0; pr < 3; pr++) 
    { 
     row = new TableRow();   //create a new outer row 

     //another loop for puzzle columns 
     for (int pc = 0; pc < 3; pc++) 
     { 
      cell = new TableCell();   //create a new outer cell 
      boxTable = new Table();   //create a new inner table 
      box = new Box();    //create a new Box object 

      box = ((Puzzle)Session["puzzle"]).getItem(pr, pc); //find the box at the current location in the puzzle 

      //another loop for box rows 
      for (int br = 0; br < 3; br++) 
      { 
       boxRow = new TableRow(); //create a new inner row 

       //another loop for box columns 
       for(int bc = 0; bc < 3; bc++) 
       { 
        boxCell = new TableCell();      //create a new inner cell 
        textbox = new SudokuTextBox();     //create a new SudokuTextBox object 

        textbox = box.getItem(br, bc);     //find the SudokuTextBox at the current location in the box 
        //grab the answer to this particular SudokuTextBox from the solutions array 
        answer = ((int[,])Session["solution"])[ (pr + br + (2 * pr)), (pc + bc + (2 * pc)) ]; 

        input = textbox.getTextBox();     //grab the textbox inside SudokuTextBox and store it 
        input.MaxLength = 1;       //only allow 1 character to be typed into the textbox 
        //give the textbox an ID so we can find it later 
        input.ID = ("tb" + (pr + br + (2 * pr)) + "_" + (pc + bc + (2 * pc))).ToString(); 

        boxCell.Controls.Add(input);     //add the textbox to the inner cell 
        boxRow.Controls.Add(boxCell);     //add the inner cell to the inner row 
       } //end box column loop 

       boxTable.Controls.Add(boxRow); //add the inner row to the inner table 

      } //end box row loop 
      cell.Controls.Add(boxTable);  //add the inner table to the outer cell 
      row.Controls.Add(cell);    //add the outer cell to the outer row 
     } //end puzzle column loop 
     structure.Controls.Add(row);   //add the outer row to the outer table 
    } //end puzzle row loop 

    pnlPuzzle.Controls.Add(structure); 

    //////////////////////////////// 
    // end puzzle 
    /////////////////////////////// 




А код класса SudokuTextBox:

public class SudokuTextBox 
{ 
private System.Web.UI.WebControls.TextBox textbox; 
private bool visible; 
private Number number; 

public SudokuTextBox() 
{ 
    textbox = new System.Web.UI.WebControls.TextBox(); 
    visible = false; 
    number = new Number(); 
} //end constructor 

//function to make a new textbox 
public System.Web.UI.WebControls.TextBox getTextBox() 
{ 
    return textbox; 
} 

//function to get the value of a textbox 
public Number getTextBoxValue() 
{ 
    return number; 
} 

//???????????? 
public void setTextBoxValue(Number newNumber) 
{ 
    this.number.setNumber(newNumber.getNumber()); 
} 

//function to get the visibility of a textbox 
public bool getVisibility() 
{ 
    return visible; 
} 

//function to change the visibility of a textbox 
public void setVisibility(bool newVisible) 
{ 
    if (newVisible) 
    { 
     //if the textbox is visible 
     //get the number 
     //and make it disabled 
     textbox.Text = number.getNumber().ToString(); 
     textbox.ReadOnly = true; 
     textbox.BackColor = System.Drawing.Color.FromArgb(150, 148, 115); 
    } else 
    { 
     //if it is not visible 
     //hide the number 
     //and make it enabled 
     textbox.ReadOnly = false; 
     textbox.Text = ""; 
     textbox.BackColor = System.Drawing.Color.White; 
    } 
} 

//function to change the color of the textbox if it is wrong 
public void setWrongNumber() 
{ 
    textbox.BackColor = System.Drawing.Color.FromArgb(5, 156, 202, 252); 
} 

//function to change the color of the textbox if it is correct 
public void setCorrectNumber() 
{ 
    //but don't change disable text boxes 
    if(textbox.ReadOnly != true) 
    { 
     textbox.BackColor = System.Drawing.Color.White; 
    } 
} 

//function to change the color of the textbox if it is blank 
public void setBlankNumber() 
{ 
    //but don't change disable text boxes 
    if (textbox.ReadOnly != true) 
    { 
     textbox.BackColor = System.Drawing.Color.White; 
    } 
} 

//function to show the value of a textbox when clicking the "Hint" button 
//also changes the color of the textbox so we know it was shown with a hint 
public void setHint() 
{ 
    setVisibility(true); 
} 

} //end class 
+0

Это ** много ** кода, но я не вижу код, который должен очистить предыдущую головоломку и сгенерировать новую. – CodingGorilla

+0

Это может иметь хороший ответ: http://stackoverflow.com/questions/2613778/how-to-clear-all-form-fields-from-code-behind –

+0

@CodingGorilla Я обновлю, чтобы показать этот код. – LakeJeffler

ответ

0

Спасибо всем, кто отдал свои два цента. Я просто хотел, чтобы все знали, что я решил проблему:

Я закончил тем, что отделил код, который строит структуру таблицы, вынимая ее из Page_Load и помещая ее в свою собственную функцию. Затем я вызывал эту функцию из Page_Load. Я также назвал эту функцию, когда я нажимаю кнопку «новая головоломка». Я также добавил подобную логику к тому, что я заметил выше, чтобы очистить предыдущую структуру таблицы перед созданием нового:

foreach(Control c in pnlPuzzle.Controls){ 

    pnlPuzzle.Controls.Remove(c); 
} 

Я точно не знаю, почему это решить мою проблему, но это сработало!