C# - Why is the execution of these different codes giving me the same result? -
C# - Why is the execution of these different codes giving me the same result? -
my first code executes , after create move, computer tries bottom right-hand spot of tic tac toe board:
private void computersturn() { control.controlcollection coll = this.controls; foreach (control c in coll)//for each button in form { if ((c != null) && (c button))//if c button , c has value { if ((c.name != "btnnewgame") && (c.name != "btnexit")) // if button isnt btn new game or exit { if (c.enabled == true) //if button has x { c.text = "o"; //place o c.enabled = false; //in empty button checkcomputerwinner(); //check if wins return; //return result }//end of if }//end of if 2 }//end of if 1 }//end of foreach }//end of computersturn the sec code, got help with...does same exact thing:
private void computersturn() { control.controlcollection coll = this.controls; foreach (control c in coll)//for each button in form { if ((c != null) && (c button))//if c button , c has value { if ((c.name != "btnnewgame") && (c.name != "btnexit")) // if button isnt btn new game or exit { gamefield = new button[] { btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9 }; int freecount = gamefield.count(b => b.text != "x"); int offset = randomgenerator.genrand(0 - 8, freecount - 1); button target = gamefield.where(b => b.text != "x").skip(offset).firstordefault(); ; if (target != null)//if target has x { // check if (c.enabled == true) { c.text = "o"; //o within button c.enabled = false; //button can no long used checkcomputerwinner(); //check if finishes task return; } } } } } }//end of computersturn random generator
public static class randomgenerator { private static readonly random _random = new random(); public static int genrand(int x, int y) { homecoming _random.next(x, y); } } i don't understand why. sec 1 aimed computer random, first 1 set predictable. why both doing same thing?
the sec solution never uses target value. uses current looped value c. alter check logic utilize target instead of c. can eliminate outer loop , 2 outer if statements together.
c#
Comments
Post a Comment