Jump to content

I have only winCheck method to be done but Í am in no state to think how its done. I have been up for almost 24 hours and have to catch a bus to school in 3 hours. Can someone here help me make method that checks who won. If board is 5 =< you need five in row to win, if board is under 5 you need 3. here is the code.

 

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package TicTacToe;

import java.util.*;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.concurrent.ThreadLocalRandom;

class TicTacToe {
    
    private static boolean first = false;
    private static int aiScore = 0;
    private static int playerScore = 0;
    public static boolean error = false;
    public static int size = 0;
    public static char circle = 'O';
    public static char cross = 'X';
    public static int victory = 0;
    
    public static void compTurnErr(Scanner console, char[][] board) {
        
        compTurn(console, board, circle, cross);
    }
            
    public static void compTurn(Scanner console, char[][] board, char circle,
                                char cross){

        System.out.println("Now it's my turn");
        System.out.println("");
        
        int size = board.length;
        
        int aiMoveVertical = ThreadLocalRandom.current().nextInt(1, size);
        
        int aiMoveHorizontal = ThreadLocalRandom.current().nextInt(1, size);

        if(board[aiMoveVertical][aiMoveHorizontal] == ' ') {

            board[aiMoveVertical][aiMoveHorizontal] = circle;
            createBoard(board);
            } else {
                compTurnErr(console, board);
            }
        userTurn(console, board);
    }
    
    public static void userTurnErr(Scanner console, char[][] board) {
        
        userTurn(console, board);
    }
    
    public static void userTurn(Scanner console, char[][] board){
        
        size = board.length;
        
        System.out.println("Select row");

        int row = console.nextInt() - 1;
        
        System.out.println("Select column");
        
        int col = console.nextInt() - 1;
        
        if(row > size || col > size || row > size && col > size) {
            System.out.println("That doesn't fit on the board dummy!");
            userTurnErr(console, board);
        } else if(board[row][col] == ' '){
            board[row][col] = 'X';
            createBoard(board);
        } else {
            System.out.println("That space is already occupied");
          userTurnErr(console, board);
            
        }
        whoWon(board, victory);
        compTurn(console, board, circle, cross);
    }
   
    public static int askSize() {
        
        try {
                
            Scanner input = new Scanner(System.in);

            System.out.println("Enter the size of the board.");

            size = input.nextInt();
                
            error = false;
            
                while(size < 3) {
                    
                            
                        System.out.println("You silly man or woman..Tic Tac Toe" + 
                                           " can't be played with board under 3x3." +
                                           " the game will be played on 3x3");
                        System.out.println();
                size++;

                }
                             
            } catch(InputMismatchException  e) {
                
            }
        return size;
    }
    
    public static char[][] initialitzeBoard() {
        
        char[][] board = new char[size][size];
        
        for(int row = 0; row < size; row++){
            for(int col = 0; col < size; col++){
                board[row][col] = ' ';
            }
        }
        return board;
    }
    
    public static void createBoard(char[][] board) {
        
    
        int numRow = board.length ;
        int numCol = board[0].length;
        
            System.out.print("     ");
    
        for (int i = 0; i < numCol; i++){
    	
	System.out.print(i + "   ");
        }
        System.out.println(); // blank line after the header
        System.out.println("");
        
        for (int i = 0; i < numRow; i++) { // Prints the game board
        
            System.out.print(i + "  ");
        
            for (int j = 0; j < numCol; j++) {
                    

            
                    System.out.print("|");
                    System.out.print(" " + board[i][j] + " ");
                
            }
            System.out.print("|");
            System.out.println();

            if (i != (numRow - 1)) {
            
                System.out.print("   ");        // separator line
                
                for (int j = 0; j < numCol + 1; j++) {
                    
                    if (j != 0){
                    
                    System.out.print("-");
                    System.out.print("---");
                    }
                    
                }
                System.out.println();
            }
            
        }
  System.out.println();
    }
   
    public static void startGame(Scanner console,char[][] board){

        //clears the board to start the game


        if(first == true){
            userTurn(console, board);
        }else{
            compTurn(console, board, circle, cross);
        }
    }
    
    public static void startMenu(){

        Scanner console = new Scanner(System.in);

        System.out.println();
        System.out.println("Welcome to Tic-Tac-Toe " + "\n" + 
                           "To play this game," +
                           "\n" +
                           "You will choose where to" +
                           " place you mark using coordinates" + 
                           "\n" + " 1-10, " +
                           "you are the X");
        System.out.println();
        System.out.println("On boards under 5 you need 3 in row to win.y" + 
                           " On boards 5 required in row  is 5!");
        
       
        System.out.println("Would you like to go first? Yes or No.");
        
        String goFirst = console.nextLine();

        if(goFirst.substring(0,1).equalsIgnoreCase("y")){
            first = true;
        }
        
        askSize();
        char[][] board = initialitzeBoard();
        createBoard(board);
        startGame(console, board);
    }
    
    public static int victory(char[][] board) {
        int victory = 0;
        if(size >=5){
            victory = 5;
        } else {
            victory = 3;
        }
     return victory;       
    }
    
   
    public static void main(String[] args) {
        
        startMenu();

    }
}

//end of file

 

Link to comment
https://linustechtips.com/topic/1006791-tictactoe-dynamic-victory-method/
Share on other sites

Link to post
Share on other sites

Without looking through your code, I would suggest recursion that will start in a given square and check in the vertical and horizontal directions (1 space at a time) if the piece in that spot (if it exists) matches the origin spot. If the count at any point hits 3 (or whatever the threshold for winning is), then that person wins. 

PSU Tier List | CoC

Gaming Build | FreeNAS Server

Spoiler

i5-4690k || Seidon 240m || GTX780 ACX || MSI Z97s SLI Plus || 8GB 2400mhz || 250GB 840 Evo || 1TB WD Blue || H440 (Black/Blue) || Windows 10 Pro || Dell P2414H & BenQ XL2411Z || Ducky Shine Mini || Logitech G502 Proteus Core

Spoiler

FreeNAS 9.3 - Stable || Xeon E3 1230v2 || Supermicro X9SCM-F || 32GB Crucial ECC DDR3 || 3x4TB WD Red (JBOD) || SYBA SI-PEX40064 sata controller || Corsair CX500m || NZXT Source 210.

Link to post
Share on other sites

Just now, 79wjd said:

Without looking through your code, I would suggest recursion that will start in a given square and check in the vertical and horizontal directions (1 space at a time) if the piece in that spot (if it exists) matches the origin spot. If the count at any point hits 3 (or whatever the threshold for winning is), then that person wins. 

Thanks for the suggestion can you give small piece of code for example? This is just introduction to programmin courses final work and I'm so sleep deprived that I can barely think lol

Link to post
Share on other sites

18 minutes ago, Teemu249 said:

Thanks for the suggestion can you give small piece of code for example? This is just introduction to programmin courses final work and I'm so sleep deprived that I can barely think lol

Something like this: https://stackoverflow.com/questions/10038585/a-recursive-check-for-a-winner-in-tictactoe-using-a-two-dimensional-array

PSU Tier List | CoC

Gaming Build | FreeNAS Server

Spoiler

i5-4690k || Seidon 240m || GTX780 ACX || MSI Z97s SLI Plus || 8GB 2400mhz || 250GB 840 Evo || 1TB WD Blue || H440 (Black/Blue) || Windows 10 Pro || Dell P2414H & BenQ XL2411Z || Ducky Shine Mini || Logitech G502 Proteus Core

Spoiler

FreeNAS 9.3 - Stable || Xeon E3 1230v2 || Supermicro X9SCM-F || 32GB Crucial ECC DDR3 || 3x4TB WD Red (JBOD) || SYBA SI-PEX40064 sata controller || Corsair CX500m || NZXT Source 210.

Link to post
Share on other sites

Well, if you think about it a bit ... it's quite simple.

The simplest method would be to go one cell at a time, and go straight down, down to left at 45 degrees, down to right at 45 degrees and to the right and count the number of cells with same "color". You don't have search in the up direction since you already went through the cells above you.

 

Here's something I quickly wrote in php right now ... added function to read board from text file or from text string in code, simply use # for empty , O and X for players 1 and 2 

 

<?php 

// x = player 1, o = player 2, # empty cell

$board_text = ''.
"##########\n".
"##########\n".
"####o#####\n".
"#####o####\n".
"###o##o###\n".
"###o###o##\n".
"###o####o#\n".
"###o######\n".
"##########\n".
"##########".


$board_x = 0;
$board_y = 0;

$ret = load_from_text($board_text);  // load the board and determine size from the text string above
$result = find_winner(); // search and return the first match of 5 or more

if ($result['found']== FALSE) {
	echo "No results found!";
} else {
	echo "Found a winner at position ".$result['x'].",".$result['y']." in the direction ".$result['direction']."!";
}

// functions... the program basically is done here.

function find_winner() {
	global $board,  $board_x, $board_y;
	$result = array('found'=>FALSE, 'x' => 0, 'y' => 0, 'color' =>'#','direction' => '');
	// you can make this smarter by not searching to the right if you can't possibly have 5 in a row
	// to the right, or not search down if there's too few vertical rows below, but unless you're coding
	// this for a potato (like let's say a 1mhz microcontroller), the number of instructions in pointless
	// tests is so small it's basically not worth my time right now. if you're perfectionist, add the checks
	for ($j=0;$j<$board_y;$j++) {
		for ($i=0;$i<$board_x;$i++) {
			if (($board[$j][$i] == 'o') || ($board[$j][$i]=='x')) {
				
				$color = $board[$j][$i];
				$d=1; $x=$i; $y=$j; while (is_cell($x,$y+1,$color)==TRUE) { $y++;$d++;}
				$r=1; $x=$i; $y=$j; while (is_cell($x+1,$y,$color)==TRUE) { $x++;$r++;}
				$dl=1; $x=$i; $y=$j; while (is_cell($x-1,$y+1,$color)==TRUE) { $x--;$y++;$dl++;}
				$dr=1; $x=$i; $y=$j; while (is_cell($x+1,$y+1,$color)==TRUE) { $x++;$y++;$dr++;}
				if (($d>=5) || ($r>=5) || ($dl>=5) || ($dr>= 5)) {
					$result['found']=TRUE;
					$result['x']=$i;
					$result['y']=$j;
					if ($d>=5) $result['direction'] = 'down';
					if ($r>=5) $result['direction'] = 'right';
					if ($dl>=5) $result['direction'] = 'down-left';
					if ($dr>=5) $result['direction'] = 'down-right';
					return $result;
				}
			}
		}
	}
	return $result; // no matches found, return the default $result created at the start of function
}
// helper function, so I don't have to check if outside range four times (for each direction) in the function above
function is_cell($i,$j,$color='#') {
	global $board,$board_x,$board_y;
	if (($i<0) || ($i>=$board_x) || ($j<0) || ($j>=$board_y)) return FALSE; // is i,j outside board?
	if ($board[$j][$i] == $color) return TRUE;
	return FALSE;
}

function load_from_file($filename) {
	$text = file_get_contents($filename);
	return load_from_text($text);
}
function load_from_text($text) {
	
	global $board,$board_x,$board_y; 
	$text = str_replace("\0x0D0x0A","\n",$text); // replace ENTER (two char combo) with just \n
	$text = strtolower($text); //so you can use xX oO # without worry
	$lines = explode("\n",$text);// split lines in text into an array 
	// determine the height and width, if less than 5 make them both at least 5.
	$board_y = count($lines); if ($board_y<5) $board_y = 5;
	$board_x = strlen($lines[0]); if ($board_x<5) $board_x = 5;
	// fill the board with the empty cells which are the "#" character 
	$board = array();
	for ($j=0;$j<$board_y;$j++) {
		$board[$j] = array();
		for ($i=0;$i<$board_x;$i++) {
			$board[$j][$i] = '#';
		}
	}
	$i=0;$j=0;
	foreach ($lines as $j => $line) {
		// make sure all horizontal lines read have all the cells, pad them with # if needed
		if (strlen($line) < $board_x) $line = str_pad($line,$board_x,"#",STR_PAD_RIGHT); 
		for ($i=0;$i<$board_x;$i++) {
			$board[$j][$i] = $line[$i]; // technically, substr($line,$i,1) but same thing
		}
	}
}


?>

 

and for the board in the code above, you get something like this:

 

d:\Programs\php7>php board.php
Found a winner at position 4,2 in the direction down-right!

 

Link to post
Share on other sites

The logic check is very simple. You need to check each player board.

1 - Get all marker of the player on the outer ring. If there is none, there is no possible wins

2 - for each marker on the outer ring test them. Check if the row or column is filled with his marker then he wins. If the marker you are testing is one of the 4 corners check the appropriate diagonal. top-left and bottom-right use the same diagonal and the 2 others corners use the other one

3 - done

 

there are alot of optimization that can be done but that is a very easy approach.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×