Search Results

Search found 89 results on 4 pages for 'tac'.

Page 1/4 | 1 2 3 4  | Next Page >

  • Code Golf: Tic Tac Toe

    - by Aistina
    Post your shortest code, by character count, to check if a player has won, and if so, which. Assume you have an integer array in a variable b (board), which holds the Tic Tac Toe board, and the moves of the players where: 0 = nothing set 1 = player 1 (X) 2 = player 2 (O) So, given the array b = [ 1, 2, 1, 0, 1, 2, 1, 0, 2 ] would represent the board X|O|X -+-+- |X|O -+-+- X| |O For that situation, your code should output 1 to indicate player 1 has won. If no-one has won you can output 0 or false. My own (Ruby) solution will be up soon. Edit: Sorry, forgot to mark it as community wiki. You can assume the input is well formed and does not have to be error checked. Update: Please post your solution in the form of a function. Most people have done this already, but some haven't, which isn't entirely fair. The board is supplied to your function as the parameter. The result should be returned by the function. The function can have a name of your choosing.

    Read the article

  • Ideas for extending tic-tac-toe game?

    - by pimvdb
    I'm building a 3D tic-tac-toe game and this is what I've implemented so far: 3D renderer with texture mapping Playing against the computer Playing online (multiplayer) Now I'm a little lost what I could add. Obviously, tic-tac-toe isn't that exciting or advanced, but I just miss something to salt it a little bit. Therefore, could anyone please suggest some ideas that would be worth implementing? Thanks!

    Read the article

  • tic tac toe in pascal --> a problem occurred

    - by Emese
    I don't know why my program doesn't run. I would really appreciate your help. Here's my program: USES graph,crt; type tegla=record x,y:integer; ertek:0..2; end; var gd,gm:integer; i,j:integer; c:char; jatekos:integer; a:array[1..3,1..3]of tegla; lx,ly:integer; procedure tabla; var x,y,i,j:integer; begin lx:=getmaxx div 3; ly:=getmaxy div 3; for i:=1 to 3 do begin y:=(i-1)*ly; for j:=1 to 3 do begin x:=(j-1)*lx; a[i,j].x:=x; a[i,j].y:=y; a[i,j].ertek:=0; setbkcolor(10); setcolor(9); rectangle(a[i,j].x,a[i,j].y,a[i,j].x+lx,a[i,j].y+ly); end; end; end; procedure aktival(i,j:integer); begin setcolor(red); rectangle(a[i,j].x,a[i,j].y,a[i,j].x+lx,a[i,j].y+ly); end; procedure visszaallit(i,j:integer); begin setcolor(9); rectangle(a[i,j].x,a[i,j].y,a[i,j].x+lx,a[i,j].y+ly); end; procedure rajzolx(i,j:integer); begin setcolor(5); line(a[i,j].x,a[i,j].y,a[i,j].x+lx,a[i,j].y+ly); line(a[i,j].x+lx,a[i,j].y,a[i,j].x,a[i,j].y+ly); end; procedure rajzol_0(i,j:integer); begin setcolor(13); circle(a[i,j].x+lx div 2, a[i,j].y+ly div 2, 50); end; procedure kinyer(i,j:integer); begin jatekos:=1; if a[1,1]=a[2,2] and a[3,3]=a[1,1] and a[2,2]=a[3,3] or a[3,1]=a[2,2] and a[1,3]=a[3,1] and a[1,3]=a[2,2] then if jatekos then begin cleardevice; writeln('x nyert!'); end else if jatekos+1 then begin cleardevice; writeln('O nyert!'); end else for i:=1 to 3 do begin if a[i,1]=a[i,2] and a[i,1]=a[i,3] and a[i,2]=a[i,3] or a[1,i]=a[2,i] and a[1,i]=a[3,i] and a[2,i]=a[3,i] then if jatekos then begin cleardevice; writeln('x nyert'); end else if jatekos+1 then begin cleardevice; writeln('O nyert!'); end; end; Begin initgraph(gd,gm,' '); tabla; jatekos:=1; i:=2; j:=2; aktival(i,j); repeat c:=readkey; if ord(c)=0 then begin c:=readkey; case ord(c)of 72: if i>1 then begin visszaallit(i,j); dec(i); aktival(i,j);end; 77:if j<3 then begin visszaallit(i,j); inc(j); aktival(i,j); end; 80:if i<3 then begin visszaallit(i,j); inc(i); aktival(i,j); end; 75:if j>1 then begin visszaallit(i,j); dec(j); aktival(i,j); end; end; end; if ord(c)=13 then begin if a[i,j].ertek=0 then if jatekos=1 then begin rajzolx(i,j); a[i,j].ertek:=1; jatekos:=2; end else begin rajzol_0(i,j); a[i,j].ertek:=2; jatekos:=1; end; end; until ord(c)=27; kinyer(i,j); end; end. I hope you can help me. Thank you a lot!

    Read the article

  • tic tac toe in pascal --> a problem occured

    - by Emese
    I don't know why my program doesn't run. I would really appreciate your help. here's my program: USES graph,crt; type tegla=record x,y:integer; ertek:0..2; end; var gd,gm:integer; i,j:integer; c:char; jatekos:integer; a:array[1..3,1..3]of tegla; lx,ly:integer; procedure tabla; var x,y,i,j:integer; begin lx:=getmaxx div 3; ly:=getmaxy div 3; for i:=1 to 3 do begin y:=(i-1)*ly; for j:=1 to 3 do begin x:=(j-1)*lx; a[i,j].x:=x; a[i,j].y:=y; a[i,j].ertek:=0; setbkcolor(10); setcolor(9); rectangle(a[i,j].x,a[i,j].y,a[i,j].x+lx,a[i,j].y+ly); end; end; end; procedure aktival(i,j:integer); begin setcolor(red); rectangle(a[i,j].x,a[i,j].y,a[i,j].x+lx,a[i,j].y+ly); end; procedure visszaallit(i,j:integer); begin setcolor(9); rectangle(a[i,j].x,a[i,j].y,a[i,j].x+lx,a[i,j].y+ly); end; procedure rajzolx(i,j:integer); begin setcolor(5); line(a[i,j].x,a[i,j].y,a[i,j].x+lx,a[i,j].y+ly); line(a[i,j].x+lx,a[i,j].y,a[i,j].x,a[i,j].y+ly); end; procedure rajzol_0(i,j:integer); begin setcolor(13); circle(a[i,j].x+lx div 2, a[i,j].y+ly div 2, 50); end; procedure kinyer(i,j:integer); begin jatekos:=1; if a[1,1]=a[2,2] and a[3,3]=a[1,1] and a[2,2]=a[3,3] or a[3,1]=a[2,2] and a[1,3]=a[3,1] and a[1,3]=a[2,2] then if jatekos then begin cleardevice; writeln('x nyert!'); end else if jatekos+1 then begin cleardevice; writeln('O nyert!'); end else for i:=1 to 3 do begin if a[i,1]=a[i,2] and a[i,1]=a[i,3] and a[i,2]=a[i,3] or a[1,i]=a[2,i] and a[1,i]=a[3,i] and a[2,i]=a[3,i] then if jatekos then begin cleardevice; writeln('x nyert'); end else if jatekos+1 then begin cleardevice; writeln('O nyert!'); end; end; Begin initgraph(gd,gm,' '); tabla; jatekos:=1; i:=2; j:=2; aktival(i,j); repeat c:=readkey; if ord(c)=0 then begin c:=readkey; case ord(c)of 72: if i>1 then begin visszaallit(i,j); dec(i); aktival(i,j);end; 77:if j<3 then begin visszaallit(i,j); inc(j); aktival(i,j); end; 80:if i<3 then begin visszaallit(i,j); inc(i); aktival(i,j); end; 75:if j>1 then begin visszaallit(i,j); dec(j); aktival(i,j); end; end; end; if ord(c)=13 then begin if a[i,j].ertek=0 then if jatekos=1 then begin rajzolx(i,j); a[i,j].ertek:=1; jatekos:=2; end else begin rajzol_0(i,j); a[i,j].ertek:=2; jatekos:=1; end; end; until ord(c)=27; kinyer(i,j); end; end. I hope you can help me. Thank you a lot!

    Read the article

  • tic tac toe game ai as3

    - by David Jones
    I'm looking into creating a simple tic tac toe/noughts and crosses game in actionscript3 and am trying to understand the ideas behind the ai used in a game like this. I've seen some simplistic examples online but from what I've read a game tree or something like minimax is the best way to go about this. Can anyone help explain or reference any good examples of this? I've seen that there is a library called as3ds - data structures for game developers which has a number of classes that might help tie this together? Any info/examples or help is much appreciated

    Read the article

  • Tic-Tac-Toe game AI

    - by David Jones
    I'm looking into creating a simple tic tac toe/noughts and crosses game in Actionscript3 and am trying to understand the ideas behind the AI used in a game like this. I've seen some simplistic examples online but from what I've read a game tree or something like minimax is the best way to go about this. Can anyone help explain or reference any good examples of this? I've seen that there is a library called as3ds - data structures for game developers which has a number of classes that might help tie this together? Any info/examples or help is much appreciated.

    Read the article

  • Ruby: implementing alpha-beta pruning for tic-tac-toe

    - by DerNalia
    So, alpha-beta pruning seems to be the most efficient algorithm out there aside from hard coding (for tic tac toe). However, I'm having problems converting the algorithm from the C++ example given in the link: http://www.webkinesia.com/games/gametree.php #based off http://www.webkinesia.com/games/gametree.php # (converted from C++ code from the alpha - beta pruning section) # returns 0 if draw LOSS = -1 DRAW = 0 WIN = 1 @next_move = 0 def calculate_ai_next_move score = self.get_best_move(COMPUTER, WIN, LOSS) return @next_move end def get_best_move(player, alpha, beta) best_score = nil score = nil if not self.has_available_moves? return false elsif self.has_this_player_won?(player) return WIN elsif self.has_this_player_won?(1 - player) return LOSS else best_score = alpha NUM_SQUARES.times do |square| if best_score >= beta break end if self.state[square].nil? self.make_move_with_index(square, player) # set to negative of opponent's best move; we only need the returned score; # the returned move is irrelevant. score = -get_best_move(1-player, -beta, -alpha) if (score > bestScore) @next_move = square best_score = score end undo_move(square) end end end return best_score end the problem is that this is returning nil. some support methods that are used above: WAYS_TO_WIN = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8],[0, 4, 8], [2, 4, 6]] def has_this_player_won?(player) result = false WAYS_TO_WIN.each {|solution| result = self.state[solution[0]] if contains_win?(solution) } return (result == player) end def contains_win?(ttt_win_state) ttt_win_state.each do |pos| return false if self.state[pos] != self.state[ttt_win_state[0]] or self.state[pos].nil? end return true end def make_move(x, y, player) self.set_square(x,y, player) end

    Read the article

  • Making the domain-model of tic tac toe

    - by devoured elysium
    I am trying to make the domain model of a Tic Tac Toe game. I'll try then to go on through the various steps of the Unified Process and later implement it in some language (C# or Java). I'd like to have some feedback if I'm going on the right path: I've defined the game with two actors, Player O and Player X. I'm not sure about defining both a Tile and a Tile State. Maybe I should only define a Tile and have the 3 possible states specialize from it? I'm not sure what is best: to have both Player O and Player X be associations with Tic Tac Toe or have them inherit from Player that is associated with Tic Tac Toe. Following the design shown on the pic, in theory we could have a Tic Tac Toe concept with 2 Player O's, which wouldn't be correct. What is your opinion on this? Also, am I missing something in the diagram? Although I can't see any other actors for Tic Tac Toe, should I have any other? Thanks

    Read the article

  • Tic Tac Toe Winner in Javascript and html [closed]

    - by Yehuda G
    I am writing a tic tac toe game using html, css, and JavaScript. I have my JavaScript in an external .js file being referenced into the .html file. Within the .js file, I have a function called playerMove, which allows the player to make his/her move and switches between player 'x' and 'o'. What I am trying to do is determine the winner. Here is what I have: each square, when onclick(this), references playerMove(piece). After each move is made, I want to run an if statement to check for the winner, but am unsure if the parameters would include a reference to 'piece' or a,b, and c. Any suggestions would be greatly appreciated. Javascript: var turn = 0; a = document.getElementById("topLeftSquare").innerHTML; b = document.getElementById("topMiddleSquare").innerHTML; c = document.getElementById("topRightSquare").innerHTML; function playerMove(piece) { var win; if(piece.innerHTML != 'X' && piece.innerHTML != 'O'){ if(turn % 2 == 0){ document.getElementById('playerDisplay').innerHTML= "X Plays " + printEquation(1); piece.innerHTML = 'X'; window.setInterval("X", 10000) piece.style.color = "red"; if(piece.innerHTML == 'X') window.alert("X WINS!"); } else { document.getElementById('playerDisplay').innerHTML= "O Plays " + printEquation(1); piece.innerHTML = 'O'; piece.style.color = "brown"; } turn+=1; } html: <div id="board"> <div class="topLeftSquare" onclick="playerMove(this)"> </div> <div class="topMiddleSquare" onclick="playerMove(this)"> </div> <div class="topRightSquare" onclick="playerMove(this)"> </div> <div class="middleLeftSquare" onclick="playerMove(this)"> </div> <div class="middleSquare" onclick="playerMove(this)"> </div> <div class="middleRightSquare" onclick="playerMove(this)"> </div> <div class="bottomLeftSquare" onclick="playerMove(this)"> </div> <div class="bottomMiddleSquare" onclick="playerMove(this)"> </div> <div class="bottomRightSquare" onclick="playerMove(this)"> </div> </div>

    Read the article

  • Negamax implementation doesn't appear to work with tic-tac-toe

    - by George Jiglau
    I've implemented Negamax as it can be found on wikipedia, which includes alpha/beta pruning. However, it seems to favor a losing move, which should be an invalid result. The game is Tic-Tac-Toe, I've abstracted most of the game play so it should be rather easy to spot an error within the algorithm. Here is the code, nextMove, negamax or evaluate are probably the functions that contain the fault: #include <list> #include <climits> #include <iostream> //#define DEBUG 1 using namespace std; struct Move { int row, col; Move(int row, int col) : row(row), col(col) { } Move(const Move& m) { row = m.row; col = m.col; } }; struct Board { char player; char opponent; char board[3][3]; Board() { } void read(istream& stream) { stream >> player; opponent = player == 'X' ? 'O' : 'X'; for(int row = 0; row < 3; row++) { for(int col = 0; col < 3; col++) { char playa; stream >> playa; board[row][col] = playa == '_' ? 0 : playa == player ? 1 : -1; } } } void print(ostream& stream) { for(int row = 0; row < 3; row++) { for(int col = 0; col < 3; col++) { switch(board[row][col]) { case -1: stream << opponent; break; case 0: stream << '_'; break; case 1: stream << player; break; } } stream << endl; } } void do_move(const Move& move, int player) { board[move.row][move.col] = player; } void undo_move(const Move& move) { board[move.row][move.col] = 0; } bool isWon() { if (board[0][0] != 0) { if (board[0][0] == board[0][1] && board[0][1] == board[0][2]) return true; if (board[0][0] == board[1][0] && board[1][0] == board[2][0]) return true; } if (board[2][2] != 0) { if (board[2][0] == board[2][1] && board[2][1] == board[2][2]) return true; if (board[0][2] == board[1][2] && board[1][2] == board[2][2]) return true; } if (board[1][1] != 0) { if (board[0][1] == board[1][1] && board[1][1] == board[2][1]) return true; if (board[1][0] == board[1][1] && board[1][1] == board[1][2]) return true; if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) return true; if (board[0][2] == board [1][1] && board[1][1] == board[2][0]) return true; } return false; } list<Move> getMoves() { list<Move> moveList; for(int row = 0; row < 3; row++) for(int col = 0; col < 3; col++) if (board[row][col] == 0) moveList.push_back(Move(row, col)); return moveList; } }; ostream& operator<< (ostream& stream, Board& board) { board.print(stream); return stream; } istream& operator>> (istream& stream, Board& board) { board.read(stream); return stream; } int evaluate(Board& board) { int score = board.isWon() ? 100 : 0; for(int row = 0; row < 3; row++) for(int col = 0; col < 3; col++) if (board.board[row][col] == 0) score += 1; return score; } int negamax(Board& board, int depth, int player, int alpha, int beta) { if (board.isWon() || depth <= 0) { #if DEBUG > 1 cout << "Found winner board at depth " << depth << endl; cout << board << endl; #endif return player * evaluate(board); } list<Move> allMoves = board.getMoves(); if (allMoves.size() == 0) return player * evaluate(board); for(list<Move>::iterator it = allMoves.begin(); it != allMoves.end(); it++) { board.do_move(*it, -player); int val = -negamax(board, depth - 1, -player, -beta, -alpha); board.undo_move(*it); if (val >= beta) return val; if (val > alpha) alpha = val; } return alpha; } void nextMove(Board& board) { list<Move> allMoves = board.getMoves(); Move* bestMove = NULL; int bestScore = INT_MIN; for(list<Move>::iterator it = allMoves.begin(); it != allMoves.end(); it++) { board.do_move(*it, 1); int score = -negamax(board, 100, 1, INT_MIN + 1, INT_MAX); board.undo_move(*it); #if DEBUG cout << it->row << ' ' << it->col << " = " << score << endl; #endif if (score > bestScore) { bestMove = &*it; bestScore = score; } } if (!bestMove) return; cout << bestMove->row << ' ' << bestMove->col << endl; #if DEBUG board.do_move(*bestMove, 1); cout << board; #endif } int main() { Board board; cin >> board; #if DEBUG cout << "Starting board:" << endl; cout << board; #endif nextMove(board); return 0; } Giving this input: O X__ ___ ___ The algorithm chooses to place a piece at 0, 1, causing a guaranteed loss, do to this trap(nothing can be done to win or end in a draw): XO_ X__ ___ Perhaps it has something to do with the evaluation function? If so, how could I fix it?

    Read the article

  • Awk command to print all the lines except the last three lines

    - by Avinash Raj
    I want to print all the lines except the last three lines from the input through awk only. Please note that my file contains n number of lines. For example, file.txt contains, foo bar foobar barfoo last line I want the output to be, foo bar foobar I know it could be possible through the combination of tac and sed or tac and awk $ tac file | sed '1,3d' | tac foo bar foobar $ tac file | awk 'NR==1{next}NR==2{next}NR==3{next}1' | tac foo bar foobar But i want the output through awk only.

    Read the article

  • Bridging VirtualBox over OpenVPN TAC adapter on Windows

    - by Sean Edwards
    I'm trying to configure a virtual machine (VirtualBox guest running Backtrack 4) with a bridged adapter over a VPN connection. The VPN is is hosted by the cybersecurity club at my university, and connects to a sandboxed LAN designed for penetration testing against various servers that the club has built. My host (Windows 7 Ultimate) connects to the VPN fine and is assigned an IP through DHCP, but for some reason the VM can't do the same thing, and I'm not sure why. It's like OpenVPN is filtering out packets from the MAC address it doesn't recognize. I want the virtual machine to bridge over the VPN connection, because our IT office has very strict policies about what you can and can't do on the network. I want to be able to run active attacks (ARP spoofing, nmap, Nessus scans) in the sandbox environment without risking the traffic accidentally going over the university network and getting my internet access revoked. Bridging over the VPN connection and running all attacks from inside the VM would solve that problem. Any idea why the host can use this interface, but the VM can't?

    Read the article

  • Representing game states in Tic Tac Toe

    - by dacman
    The goal of the assignment that I'm currently working on for my Data Structures class is to create a of Quantum Tic Tac Toe with an AI that plays to win. Currently, I'm having a bit of trouble finding the most efficient way to represent states. Overview of current Structure: AbstractGame Has and manages AbstractPlayers (game.nextPlayer() returns next player by int ID) Has and intializes AbstractBoard at the beginning of the game Has a GameTree (Complete if called in initialization, incomplete otherwise) AbstractBoard Has a State, a Dimension, and a Parent Game Is a mediator between Player and State, (Translates States from collections of rows to a Point representation Is a StateConsumer AbstractPlayer Is a State Producer Has a ConcreteEvaluationStrategy to evaluate the current board StateTransveralPool Precomputes possible transversals of "3-states". Stores them in a HashMap, where the Set contains nextStates for a given "3-state" State Contains 3 Sets -- a Set of X-Moves, O-Moves, and the Board Each Integer in the set is a Row. These Integer values can be used to get the next row-state from the StateTransversalPool SO, the principle is Each row can be represented by the binary numbers 000-111, where 0 implies an open space and 1 implies a closed space. So, for an incomplete TTT board: From the Set<Integer> board perspective: X_X R1 might be: 101 OO_ R2 might be: 110 X_X R3 might be: 101, where 1 is an open space, and 0 is a closed space From the Set<Integer> xMoves perspective: X_X R1 might be: 101 OO_ R2 might be: 000 X_X R3 might be: 101, where 1 is an X and 0 is not From the Set<Integer> oMoves perspective: X_X R1 might be: 000 OO_ R2 might be: 110 X_X R3 might be: 000, where 1 is an O and 0 is not Then we see that x{R1,R2,R3} & o{R1,R2,R3} = board{R1,R2,R3} The problem is quickly generating next states for the GameTree. If I have player Max (x) with board{R1,R2,R3}, then getting the next row-states for R1, R2, and R3 is simple.. Set<Integer> R1nextStates = StateTransversalPool.get(R1); The problem is that I have to combine each one of those states with R1 and R2. Is there a better data structure besides Set that I could use? Is there a more efficient approach in general? I've also found Point<-State mediation cumbersome. Is there another approach that I could try there? Thanks! Here is the code for my ConcretePlayer class. It might help explain how players produce new states via moves, using the StateProducer (which might need to become StateFactory or StateBuilder). public class ConcretePlayerGeneric extends AbstractPlayer { @Override public BinaryState makeMove() { // Given a move and the current state, produce a new state Point playerMove = super.strategy.evaluate(this); BinaryState currentState = super.getInGame().getBoard().getState(); return StateProducer.getState(this, playerMove, currentState); } } EDIT: I'm starting with normal TTT and moving to Quantum TTT. Given the framework, it should be as simple as creating several new Concrete classes and tweaking some things.

    Read the article

  • What's the best/most efficent way to create a semi-intelligent AI for a tic tac toe game?

    - by Link
    basically I am attempting to make a a efficient/smallish C game of Tic-Tac-Toe. I have implemented everything other then the AI for the computer so far. my squares are basically structs in an array with an assigned value based on the square. For example s[1].value = 1; therefore it's a x, and then a value of 3 would be a o. My question is whats the best way to create a semi-decent game playing AI for my tic-tac-toe game? I don't really want to use minimax, since It's not what I need. So how do I avoid a a lot of if statments and make it more efficient. Here is the rest of my code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> struct state{ // defined int state; // 0 is tie, 1 is user loss, 2 is user win, 3 is ongoing game int moves; }; struct square{ // one square of the board int value; // 1 is x, 3 is o char sign; // no space used }; struct square s[9]; //set up the struct struct state gamestate = {0,0}; //nothing void setUpGame(){ // setup the game int i = 0; for(i = 0; i < 9; i++){ s[i].value = 0; s[i].sign = ' '; } gamestate.moves=0; printf("\nHi user! You're \"x\"! I'm \"o\"! Good Luck :)\n"); } void displayBoard(){// displays the game board printf("\n %c | %c | %c\n", s[6].sign, s[7].sign, s[8].sign); printf("-----------\n"); printf(" %c | %c | %c\n", s[3].sign, s[4].sign, s[5].sign); printf("-----------\n"); printf(" %c | %c | %c\n\n", s[0].sign, s[1].sign, s[2].sign); } void getHumanMove(){ // get move from human int i; while(1){ printf(">>:"); char line[255]; // input the move to play fgets(line, sizeof(line), stdin); while(sscanf(line, "%d", &i) != 1) { //1 match of defined specifier on input line printf("Sorry, that's not a valid move!\n"); fgets(line, sizeof(line), stdin); } if(s[i-1].value != 0){printf("Sorry, That moves already been taken!\n\n");continue;} break; } s[i-1].value = 1; s[i-1].sign = 'x'; gamestate.moves++; } int sum(int x, int y, int z){return(x*y*z);} void getCompMove(){ // get the move from the computer } void checkWinner(){ // check the winner int i; for(i = 6; i < 9; i++){ // check cols if((sum(s[i].value,s[i-3].value,s[i-6].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;} if((sum(s[i].value,s[i-3].value,s[i-6].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;} } for(i = 0; i < 7; i+=3){ // check rows if((sum(s[i].value,s[i+1].value,s[i+2].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;} if((sum(s[i].value,s[i+1].value,s[i+2].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;} } if((sum(s[0].value,s[4].value,s[8].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;} if((sum(s[0].value,s[4].value,s[8].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;} if((sum(s[2].value,s[4].value,s[6].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;} if((sum(s[2].value,s[4].value,s[6].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;} } void playGame(){ // start playing the game gamestate.state = 3; //set-up the gamestate srand(time(NULL)); int temp = (rand()%2) + 1; if(temp == 2){ // if two comp goes first temp = (rand()%2) + 1; if(temp == 2){ s[4].value = 2; s[4].sign = 'o'; gamestate.moves++; }else{ s[2].value = 2; s[2].sign = 'o'; gamestate.moves++; } } displayBoard(); while(gamestate.state == 3){ if(gamestate.moves<10); getHumanMove(); if(gamestate.moves<10); getCompMove(); checkWinner(); if(gamestate.state == 3 && gamestate.moves==9){ printf("The game is a tie :p\n"); break; } displayBoard(); } } int main(int argc, const char *argv[]){ printf("Welcome to Tic Tac Toe\nby The Elite Noob\nEnter 1-9 To play a move, standard numpad\n1 is bottom-left, 9 is top-right\n"); while(1){ // while game is being played printf("\nPress 1 to play a new game, or any other number to exit;\n>>:"); char line[255]; // input whether or not to play the game fgets(line, sizeof(line), stdin); int choice; // user's choice about playing or not while(sscanf(line, "%d", &choice) != 1) { //1 match of defined specifier on input line printf("Sorry, that's not a valid option!\n"); fgets(line, sizeof(line), stdin); } if(choice == 1){ setUpGame(); // set's up the game playGame(); // Play a Game }else {break;} // exit the application } printf("\nThank's For playing!\nHave a good Day!\n"); return 0; }

    Read the article

  • Python: does it make sense to refactor this check into it's own method?

    - by Jeff Fry
    I'm still learning python. I just wrote this method to determine if a player has won a game of tic-tac-toe yet, given a board state like:'[['o','x','x'],['x','o','-'],['x','o','o']]' def hasWon(board): players = ['x', 'o'] for player in players: for row in board: if row.count(player) == 3: return player top, mid, low = board for i in range(3): if [ top[i],mid[i],low[i] ].count(player) == 3: return player if [top[0],mid[1],low[2]].count(player) == 3: return player if [top[2],mid[1],low[0]].count(player) == 3: return player return None It occurred to me that I check lists of 3 chars several times and could refactor the checking to its own method like so: def check(list, player): if list.count(player) == 3: return player ...but then realized that all that really does is change lines like: if [ top[i],mid[i],low[i] ].count(player) == 3: return player to: if check( [top[i],mid[i],low[i]], player ): return player ...which frankly doesn't seem like much of an improvement. Do you see a better way to refactor this? Or in general a more Pythonic option? I'd love to hear it!

    Read the article

  • Guide to reduce TFS database growth using the Test Attachment Cleaner

    - by terje
    Recently there has been several reports on TFS databases growing too fast and growing too big.  Notable this has been observed when one has started to use more features of the Testing system.  Also, the TFS 2010 handles test results differently from TFS 2008, and this leads to more data stored in the TFS databases. As a consequence of this there has been released some tools to remove unneeded data in the database, and also some fixes to correct for bugs which has been found and corrected during this process.  Further some preventive practices and maintenance rules should be adopted. A lot of people have blogged about this, among these are: Anu’s very important blog post here describes both the problem and solutions to handle it.  She describes both the Test Attachment Cleaner tool, and also some QFE/CU releases to fix some underlying bugs which prevented the tool from being fully effective. Brian Harry’s blog post here describes the problem too This forum thread describes the problem with some solution hints. Ravi Shanker’s blog post here describes best practices on solving this (TBP) Grant Holidays blogpost here describes strategies to use the Test Attachment Cleaner both to detect space problems and how to rectify them.   The problem can be divided into the following areas: Publishing of test results from builds Publishing of manual test results and their attachments in particular Publishing of deployment binaries for use during a test run Bugs in SQL server preventing total cleanup of data (All the published data above is published into the TFS database as attachments.) The test results will include all data being collected during the run.  Some of this data can grow rather large, like IntelliTrace logs and video recordings.   Also the pushing of binaries which happen for automated test runs, including tests run during a build using code coverage which will include all the files in the deployment folder, contributes a lot to the size of the attached data.   In order to handle this systematically, I have set up a 3-stage process: Find out if you have a database space issue Set up your TFS server to minimize potential database issues If you have the “problem”, clean up the database and otherwise keep it clean   Analyze the data Are your database( s) growing ?  Are unused test results growing out of proportion ? To find out about this you need to query your TFS database for some of the information, and use the Test Attachment Cleaner (TAC) to obtain some  more detailed information. If you don’t have too many databases you can use the SQL Server reports from within the Management Studio to analyze the database and table sizes. Or, you can use a set of queries . I find queries often faster to use because I can tweak them the way I want them.  But be aware that these queries are non-documented and non-supported and may change when the product team wants to change them. If you have multiple Project Collections, find out which might have problems: (Disclaimer: The queries below work on TFS 2010. They will not work on Dev-11, since the table structure have been changed.  I will try to update them for Dev-11 when it is released.) Open a SQL Management Studio session onto the SQL Server where you have your TFS Databases. Use the query below to find the Project Collection databases and their sizes, in descending size order.  use master select DB_NAME(database_id) AS DBName, (size/128) SizeInMB FROM sys.master_files where type=0 and substring(db_name(database_id),1,4)='Tfs_' and DB_NAME(database_id)<>'Tfs_Configuration' order by size desc Doing this on one of our SQL servers gives the following results: It is pretty easy to see on which collection to start the work   Find out which tables are possibly too large Keep a special watch out for the Tfs_Attachment table. Use the script at the bottom of Grant’s blog to find the table sizes in descending size order. In our case we got this result: From Grant’s blog we learnt that the tbl_Content is in the Version Control category, so the major only big issue we have here is the tbl_AttachmentContent.   Find out which team projects have possibly too large attachments In order to use the TAC to find and eventually delete attachment data we need to find out which team projects have these attachments. The team project is a required parameter to the TAC. Use the following query to find this, replace the collection database name with whatever applies in your case:   use Tfs_DefaultCollection select p.projectname, sum(a.compressedlength)/1024/1024 as sizeInMB from dbo.tbl_Attachment as a inner join tbl_testrun as tr on a.testrunid=tr.testrunid inner join tbl_project as p on p.projectid=tr.projectid group by p.projectname order by sum(a.compressedlength) desc In our case we got this result (had to remove some names), out of more than 100 team projects accumulated over quite some years: As can be seen here it is pretty obvious the “Byggtjeneste – Projects” are the main team project to take care of, with the ones on lines 2-4 as the next ones.  Check which attachment types takes up the most space It can be nice to know which attachment types takes up the space, so run the following query: use Tfs_DefaultCollection select a.attachmenttype, sum(a.compressedlength)/1024/1024 as sizeInMB from dbo.tbl_Attachment as a inner join tbl_testrun as tr on a.testrunid=tr.testrunid inner join tbl_project as p on p.projectid=tr.projectid group by a.attachmenttype order by sum(a.compressedlength) desc We then got this result: From this it is pretty obvious that the problem here is the binary files, as also mentioned in Anu’s blog. Check which file types, by their extension, takes up the most space Run the following query use Tfs_DefaultCollection select SUBSTRING(filename,len(filename)-CHARINDEX('.',REVERSE(filename))+2,999)as Extension, sum(compressedlength)/1024 as SizeInKB from tbl_Attachment group by SUBSTRING(filename,len(filename)-CHARINDEX('.',REVERSE(filename))+2,999) order by sum(compressedlength) desc This gives a result like this:   Now you should have collected enough information to tell you what to do – if you got to do something, and some of the information you need in order to set up your TAC settings file, both for a cleanup and for scheduled maintenance later.    Get your TFS server and environment properly set up Even if you have got the problem or if have yet not got the problem, you should ensure the TFS server is set up so that the risk of getting into this problem is minimized.  To ensure this you should install the following set of updates and components. The assumption is that your TFS Server is at SP1 level. Install the QFE for KB2608743 – which also contains detailed instructions on its use, download from here. The QFE changes the default settings to not upload deployed binaries, which are used in automated test runs. Binaries will still be uploaded if: Code coverage is enabled in the test settings. You change the UploadDeploymentItem to true in the testsettings file. Be aware that this might be reset back to false by another user which haven't installed this QFE. The hotfix should be installed to The build servers (the build agents) The machine hosting the Test Controller Local development computers (Visual Studio) Local test computers (MTM) It is not required to install it to the TFS Server, test agents or the build controller – it has no effect on these programs. If you use the SQL Server 2008 R2 you should also install the CU 10 (or later).  This CU fixes a potential problem of hanging “ghost” files.  This seems to happen only in certain trigger situations, but to ensure it doesn’t bite you, it is better to make sure this CU is installed. There is no such CU for SQL Server 2008 pre-R2 Work around:  If you suspect hanging ghost files, they can be – with some mental effort, deduced from the ghost counters using the following SQL query: use master SELECT DB_NAME(database_id) as 'database',OBJECT_NAME(object_id) as 'objectname', index_type_desc,ghost_record_count,version_ghost_record_count,record_count,avg_record_size_in_bytes FROM sys.dm_db_index_physical_stats (DB_ID(N'<DatabaseName>'), OBJECT_ID(N'<TableName>'), NULL, NULL , 'DETAILED') The problem is a stalled ghost cleanup process.  Restarting the SQL server after having stopped all components that depends on it, like the TFS Server and SPS services – that is all applications that connect to the SQL server. Then restart the SQL server, and finally start up all dependent processes again.  (I would guess a complete server reboot would do the trick too.) After this the ghost cleanup process will run properly again. The fix will come in the next CU cycle for SQL Server R2 SP1.  The R2 pre-SP1 and R2 SP1 have separate maintenance cycles, and are maintained individually. Each have its own set of CU’s. When it comes I will add the link here to that CU. The "hanging ghost file” issue came up after one have run the TAC, and deleted enourmes amount of data.  The SQL Server can get into this hanging state (without the QFE) in certain cases due to this. And of course, install and set up the Test Attachment Cleaner command line power tool.  This should be done following some guidelines from Ravi Shanker: “When you run TAC, ensure that you are deleting small chunks of data at regular intervals (say run TAC every night at 3AM to delete data that is between age 730 to 731 days) – this will ensure that small amounts of data are being deleted and SQL ghosted record cleanup can catch up with the number of deletes performed. “ This rule minimizes the risk of the ghosted hang problem to occur, and further makes it easier for the SQL server ghosting process to work smoothly. “Run DBCC SHRINKDB post the ghosted records are cleaned up to physically reclaim the space on the file system” This is the last step in a 3 step process of removing SQL server data. First they are logically deleted. Then they are cleaned out by the ghosting process, and finally removed using the shrinkdb command. Cleaning out the attachments The TAC is run from the command line using a set of parameters and controlled by a settingsfile.  The parameters point out a server uri including the team project collection and also point at a specific team project. So in order to run this for multiple team projects regularly one has to set up a script to run the TAC multiple times, once for each team project.  When you install the TAC there is a very useful readme file in the same directory. When the deployment binaries are published to the TFS server, ALL items are published up from the deployment folder. That often means much more files than you would assume are necessary. This is a brute force technique. It works, but you need to take care when cleaning up. Grant has shown how their settings file looks in his blog post, removing all attachments older than 180 days , as long as there are no active workitems connected to them. This setting can be useful to clean out all items, both in a clean-up once operation, and in a general There are two scenarios we need to consider: Cleaning up an existing overgrown database Maintaining a server to avoid an overgrown database using scheduled TAC   1. Cleaning up a database which has grown too big due to these attachments. This job is a “Once” job.  We do this once and then move on to make sure it won’t happen again, by taking the actions in 2) below.  In this scenario you should only consider the large files. Your goal should be to simply reduce the size, and don’t bother about  the smaller stuff. That can be left a scheduled TAC cleanup ( 2 below). Here you can use a very general settings file, and just remove the large attachments, or you can choose to remove any old items.  Grant’s settings file is an example of the last one.  A settings file to remove only large attachments could look like this: <!-- Scenario : Remove large files --> <DeletionCriteria> <TestRun /> <Attachment> <SizeInMB GreaterThan="10" /> </Attachment> </DeletionCriteria> Or like this: If you want only to remove dll’s and pdb’s about that size, add an Extensions-section.  Without that section, all extensions will be deleted. <!-- Scenario : Remove large files of type dll's and pdb's --> <DeletionCriteria> <TestRun /> <Attachment> <SizeInMB GreaterThan="10" /> <Extensions> <Include value="dll" /> <Include value="pdb" /> </Extensions> </Attachment> </DeletionCriteria> Before you start up your scheduled maintenance, you should clear out all older items. 2. Scheduled maintenance using the TAC If you run a schedule every night, and remove old items, and also remove them in small batches.  It is important to run this often, like every night, in order to keep the number of deleted items low. That way the SQL ghost process works better. One approach could be to delete all items older than some number of days, let’s say 180 days. This could be combined with restricting it to keep attachments with active or resolved bugs.  Doing this every night ensures that only small amounts of data is deleted. <!-- Scenario : Remove old items except if they have active or resolved bugs --> <DeletionCriteria> <TestRun> <AgeInDays OlderThan="180" /> </TestRun> <Attachment /> <LinkedBugs> <Exclude state="Active" /> <Exclude state="Resolved"/> </LinkedBugs> </DeletionCriteria> In my experience there are projects which are left with active or resolved workitems, akthough no further work is done.  It can be wise to have a cleanup process with no restrictions on linked bugs at all. Note that you then have to remove the whole LinkedBugs section. A approach which could work better here is to do a two step approach, use the schedule above to with no LinkedBugs as a sweeper cleaning task taking away all data older than you could care about.  Then have another scheduled TAC task to take out more specifically attachments that you are not likely to use. This task could be much more specific, and based on your analysis clean out what you know is troublesome data. <!-- Scenario : Remove specific files early --> <DeletionCriteria> <TestRun > <AgeInDays OlderThan="30" /> </TestRun> <Attachment> <SizeInMB GreaterThan="10" /> <Extensions> <Include value="iTrace"/> <Include value="dll"/> <Include value="pdb"/> <Include value="wmv"/> </Extensions> </Attachment> <LinkedBugs> <Exclude state="Active" /> <Exclude state="Resolved" /> </LinkedBugs> </DeletionCriteria> The readme document for the TAC says that it recognizes “internal” extensions, but it does recognize any extension. To run the tool do the following command: tcmpt attachmentcleanup /collection:your_tfs_collection_url /teamproject:your_team_project /settingsfile:path_to_settingsfile /outputfile:%temp%/teamproject.tcmpt.log /mode:delete   Shrinking the database You could run a shrink database command after the TAC has run in cases where there are a lot of data being deleted.  In this case you SHOULD do it, to free up all that space.  But, after the shrink operation you should do a rebuild indexes, since the shrink operation will leave the database in a very fragmented state, which will reduce performance. Note that you need to rebuild indexes, reorganizing is not enough. For smaller amounts of data you should NOT shrink the database, since the data will be reused by the SQL server when it need to add more records.  In fact, it is regarded as a bad practice to shrink the database regularly.  So on a daily maintenance schedule you should NOT shrink the database. To shrink the database you do a DBCC SHRINKDATABASE command, and then follow up with a DBCC INDEXDEFRAG afterwards.  I find the easiest way to do this is to create a SQL Maintenance plan including the Shrink Database Task and the Rebuild Index Task and just execute it when you need to do this.

    Read the article

  • How do I go from a simple html5 tic tac toe game to an online 2 player game?

    - by phi1o
    I've been working on an online 2 player Tic Tac Toe solution for blackberries. both old and new. And so far I have html5 code that has a 3 x 3 layout that switches between x and o for the game mechanics. I believe I'm still missing a check for win function but my question is about the server side of this game. I'm not sure how to go about learning what exactly I want. how do you take what I have now, and make this into a functioning online game? I've been told WAMP is a good solution, as well as IIS. and its all really over my head, so i'm hoping to get a little more clarity as far as what I should focus on to bring this game to life.

    Read the article

  • TicTacToe AI Making Incorrect Decisions

    - by Chris Douglass
    A little background: as a way to learn multinode trees in C++, I decided to generate all possible TicTacToe boards and store them in a tree such that the branch beginning at a node are all boards that can follow from that node, and the children of a node are boards that follow in one move. After that, I thought it would be fun to write an AI to play TicTacToe using that tree as a decision tree. TTT is a solvable problem where a perfect player will never lose, so it seemed an easy AI to code for my first time trying an AI. Now when I first implemented the AI, I went back and added two fields to each node upon generation: the # of times X will win & the # of times O will win in all children below that node. I figured the best solution was to simply have my AI on each move choose and go down the subtree where it wins the most times. Then I discovered that while it plays perfect most of the time, I found ways where I could beat it. It wasn't a problem with my code, simply a problem with the way I had the AI choose it's path. Then I decided to have it choose the tree with either the maximum wins for the computer or the maximum losses for the human, whichever was more. This made it perform BETTER, but still not perfect. I could still beat it. So I have two ideas and I'm hoping for input on which is better: 1) Instead of maximizing the wins or losses, instead I could assign values of 1 for a win, 0 for a draw, and -1 for a loss. Then choosing the tree with the highest value will be the best move because that next node can't be a move that results in a loss. It's an easy change in the board generation, but it retains the same search space and memory usage. Or... 2) During board generation, if there is a board such that either X or O will win in their next move, only the child that prevents that win will be generated. No other child nodes will be considered, and then generation will proceed as normal after that. It shrinks the size of the tree, but then I have to implement an algorithm to determine if there is a one move win and I think that can only be done in linear time (making board generation a lot slower I think?) Which is better, or is there an even better solution?

    Read the article

  • Tic-Tac-Toe AI: How to Make the Tree?

    - by cam
    I'm having a huge block trying to understand "trees" while making a Tic-Tac-Toe bot. I understand the concept, but I can't figure out to implement them. Can someone show me an example of how a tree should be generated for such a case? Or a good tutorial on generating trees? I guess the hard part is generating partial trees. I know how to implement generating a whole tree, but not parts of it.

    Read the article

  • wamp installed can't find localhost

    - by Tac
    I installed a WAMP package on a Windows 7 machine and everything ( Apache, php, mySql, phpMyAdmin) appear to have installed correctly. However when I try to access localhost or phpMyAdmin via the browser, I get "Server Not Found". I've tried using localhost, 127.0.0.1 in the browser. I've checked the httpd file it says "Listen 80". C:\Windows\System32\drivers\etc\hosts says "127.0.0.1 localhost" Apache log file doen't show any errors. Suggestions appreciated.

    Read the article

  • Can't import my module when start my twisted application under root

    - by kepkin
    Here is absolutely minimal application so you could try to reproduce it on your machine. Having two files for example in /home/aln/tmp/tw_test: server.tac MyLib.py MyLib.py class Solver(object): def solve(self): """ do extremely complex stuff here """ print "Hello from solve" server.tac #!/usr/bin/python import MyLib from twisted.application import internet, service from twisted.internet import protocol, reactor, defer, utils, threads from twisted.protocols import basic class MyProtocol(basic.LineReceiver): def lineReceived(self, line): if line=="new job": self.transport.write("started a job" + '\r\n') self.factory.run_defered() class MyFactory(protocol.ServerFactory, MyLib.Solver): protocol = MyProtocol def run_defered_helper(self): self.solve() def run_defered(self): d = threads.deferToThread(self.run_defered_helper) application = service.Application('MyApplication') factory = MyFactory() internet.TCPServer(1079, factory).setServiceParent(service.IServiceCollection(application)) Everything works fine when I start it under non-root user. aln@aln-laptop:tw_test$ twistd -ny server.tac 2010-03-03 22:42:55+0300 [-] Log opened. 2010-03-03 22:42:55+0300 [-] twistd 8.2.0 (/usr/bin/python 2.6.4) starting up. 2010-03-03 22:42:55+0300 [-] reactor class: twisted.internet.selectreactor.SelectReactor. 2010-03-03 22:42:55+0300 [-] <class 'MyFactory'> starting on 1079 2010-03-03 22:42:55+0300 [-] Starting factory <MyFactory object at 0x2d5ea50> 2010-03-03 22:42:59+0300 [MyProtocol,0,127.0.0.1] Hello from solve ^C2010-03-03 22:43:01+0300 [-] Received SIGINT, shutting down. 2010-03-03 22:43:01+0300 [-] (Port 1079 Closed) 2010-03-03 22:43:01+0300 [-] Stopping factory <MyFactory object at 0x2d5ea50> 2010-03-03 22:43:01+0300 [-] Main loop terminated. 2010-03-03 22:43:02+0300 [-] Server Shut Down. But if try to start it under root (which is going to happen in my real application) I receive the following exception: aln@aln-laptop:tw_test$ sudo twistd -ny server.tac [sudo] password for aln: Traceback (most recent call last): File "/usr/lib/python2.6/dist-packages/twisted/application/app.py", line 694, in run runApp(config) File "/usr/lib/python2.6/dist-packages/twisted/scripts/twistd.py", line 23, in runApp _SomeApplicationRunner(config).run() File "/usr/lib/python2.6/dist-packages/twisted/application/app.py", line 411, in run self.application = self.createOrGetApplication() File "/usr/lib/python2.6/dist-packages/twisted/application/app.py", line 494, in createOrGetApplication application = getApplication(self.config, passphrase) --- <exception caught here> --- File "/usr/lib/python2.6/dist-packages/twisted/application/app.py", line 505, in getApplication application = service.loadApplication(filename, style, passphrase) File "/usr/lib/python2.6/dist-packages/twisted/application/service.py", line 390, in loadApplication application = sob.loadValueFromFile(filename, 'application', passphrase) File "/usr/lib/python2.6/dist-packages/twisted/persisted/sob.py", line 215, in loadValueFromFile exec fileObj in d, d File "server.tac", line 2, in <module> import MyLib exceptions.ImportError: No module named MyLib Failed to load application: No module named MyLib If I try to load MyLib module in the python intepreter under root, it works fine: aln@aln-laptop:tw_test$ sudo python Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MyLib >>> import sys >>> print(sys.path) ['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/local/lib/python2.6/dist-packages'] >>> sys.path is absolutely the same for aln user. I tried sudo -E too. Any suggestions?

    Read the article

  • Filtering python string through external program

    - by Peter
    What's the cleanest way of filtering a Python string through an external program? In particular, how do you write the following function? def filter_through(s, ext_cmd): # Filters string s through ext_cmd, and returns the result. # Example usage: # filter a multiline string through tac to reverse the order. filter_through("one\ntwo\nthree\n", "tac") # => returns "three\ntwo\none\n" Note: the example is only that - I realize there are much better ways of reversing lines in python.

    Read the article

  • Code Golf: Connect 4

    - by Matthieu M.
    If you don't know the Connect 4 game, follow the link :) I used to play it a lot when I was a child. At least until my little sister got bored with me winning... Anyway I was reading the Code Golf: Tic Tac Toe the other day and I thought that solving the Tic Tac Toe problem was simpler than solving the Connect 4... and wondered how much this would reflect on the number of characters a solution would yield. I thus propose a similar challenge: Find the winner The grid is given under the form of a string meant to passed as a parameter to a function. The goal of the code golf is to write the body of the function, the parameter will be b, of string type The image in the wikipedia article leads to the following representation: "....... ..RY... ..YYYR. ..RRYY. ..RYRY. .YRRRYR" (6 rows of 7 elements) but is obviously incomplete (Yellow has not won yet) There is a winner in the grid passed, no need to do error checking Remember that it might not be exactly 4 The expected output is the letter representing the winner (either R or Y) I expect perl mongers to produce the most unreadable script (along with Ook and whitespace, of course), but I am most interested in reading innovative solutions. I must admit the magic square solution for Tic Tac Toe was my personal fav and I wonder if there is a way to build a similar one with this. Well, happy Easter weekend :) Now I just have a few days to come up with a solution of my own!

    Read the article

  • [Python/Tkinter] Grid within a frame?

    - by Sam
    Is it possible to place a grid of buttons in Tkinter inside another frame? I'm wanting to create a tic-tac-toe like game and want to use the grid feature to put gamesquares (that will be buttons). However, I'd like to have other stuff in the GUI other than just the game board so it's not ideal to just have everything in the one grid. To illustrate: O | X | X | ---------- | O | O | X | Player 2 wins! ---------- | X | O | X | The tic tac toe board is in a grid that is made up of all buttons and the 'player 2 wins' is a label inside a frame. This is an oversimplification of what I'm trying to do so bear with me, for the way I've designed the program so far (the board is dynamically created) a grid makes the most sense.

    Read the article

  • MiniMax function throws null pointer exception

    - by Sven
    I'm working on a school project, I have to build a tic tac toe game with the AI based on the MiniMax algorithm. The two player mode works like it should. I followed the code example on http://ethangunderson.com/blog/minimax-algorithm-in-c/. The only thing is that I get a NullPointer Exception when I run the code. And I can't wrap my finger around it. I placed a comment in the code where the exception is thrown. The recursive call is returning a null pointer, what is very strange because it can't.. When I place a breakpoint on the null return with the help of a if statement, then I see that there ARE still 2 to 3 empty places.. I probably overlooking something. Hope someone can tell me what I'm doing wrong. Here is the MiniMax code (the tic tac toe code is not important): /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package MiniMax; import Game.Block; import Game.Board; import java.util.ArrayList; public class MiniMax { public static Place getBestMove(Board gameBoard, Block.TYPE player) { Place bestPlace = null; ArrayList<Place> emptyPlaces = gameBoard.getEmptyPlaces(); Board newBoard; //loop trough all the empty places for(Place emptyPlace : emptyPlaces) { newBoard = gameBoard.clone(); newBoard.setBlock(emptyPlace.getRow(), emptyPlace.getCell(), player); //no game won and still room to move if(newBoard.getWinner() == Block.TYPE.NONE && newBoard.getEmptyPlaces().size() > 0) { //is an node (has children) Place tempPlace = getBestMove(newBoard, invertPlayer(player)); //ERROR is thrown here! tempPlace is null. emptyPlace.setScore(tempPlace.getScore()); } else { //is an leaf if(newBoard.getWinner() == Block.TYPE.NONE) { emptyPlace.setScore(0); } else if(newBoard.getWinner() == Block.TYPE.X) { emptyPlace.setScore(-1); } else if(newBoard.getWinner() == Block.TYPE.O) { emptyPlace.setScore(1); } //if this move is better then our prev move, take it! if((bestPlace == null) || (player == Block.TYPE.X && emptyPlace.getScore() < bestPlace.getScore()) || (player == Block.TYPE.O && emptyPlace.getScore() > bestPlace.getScore())) { bestPlace = emptyPlace; } } } //This should never be null, but it does.. return bestPlace; } private static Block.TYPE invertPlayer(Block.TYPE player) { if(player == Block.TYPE.X) { return Block.TYPE.O; } return Block.TYPE.X; } }

    Read the article

1 2 3 4  | Next Page >