Question

Please help me code the following in: JAVA

Please create the code in as basic way as possible, so I can understand it better :)

Full points will be awarded, thanks in advance!

Program Description Write a program that demonstrates the skills weve learned throughout this quarter. This type of project offers only a few guidelines, allowing you to invest as much time and polish as you want, as long as you meet the program requirements described below. You can write a simple game (e.g., tic-tac-toe, Battleship), a simulation (e.g., a zero-dimensional energy balance model of the climate), or an application (e.g., a mortgage calculator). Your main requirement is that you demonstrate six of the following features in your software program and that you comment and document your code well 1. Functional Decomposition: Use methods (a.k.a., functions) to break up a large program into 2. Looping with Repetition Control Structures: Use two of the following structures: for, while 3. Nested Loops: Use a loop within a loop in your program. Note that this is automatically 4. Branching with Selection Control Structures: Use multiple (i.e., more than one) if/else and/or meaningful chunks, using input to and output from those functions where appropriate do/while, foreach accomplished when using Multi-Dimensional Arrays switch statements in your code. (You dont need to use both kinds of statements. if/else means any kind of if/else statement.) File I/O: Read from or write to a file in your software. Examples of this include be reading in a preset pattern for the computer opponents answers in a game of rock/paper/scissors, or writing a file that logs each move the player makes, effectively recording a history of the game Using Multiple Classes: Build and use more than one class in your project. Note that a class that only has a main method and does not have any instance variables or methods does not count as a class 5. 6.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
 
public class TicTacToe
{
        public static void main(String[] args)
        {
                TicTacToe now=new TicTacToe();
                now.startGame();
        }
 
        private int[][] points;
        private int[][] winp;
        private int[] wval;
        private char[][] grid;
        private final int kcounter=3;
        private final int crosscounterer=4;
        private final int totalcount=5;
        private final int playerid=0;
        private final int compid=1;
        private final int truceid=2;
        private final int playingid=3;
        private String movesPlayer;
        private byte override;
        private char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}};
        private char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}};
        private Hashtable<Integer,Integer> csetter;
        private Hashtable<Integer,Integer> ksetter;
 
        public void startGame()
        {
                BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                System.out.print("Start?(y/n):");
                char choice='y';
                try
                {
                        choice=br.readLine().charAt(0);
                }
                catch(Exception e)
                {
                        System.out.println(e.getMessage());
                }
                if(choice=='n'||choice=='N')
                {
                        return;
                }
 
                System.out.println("Enter Grid Values, as so:\n ");
                display(numpad);
                System.out.println("Begin");
                int playerscore=0;
                int compscore=0;
                do
                {
                        int result=startGame();
                        if(result==playerid)
                                playerscore++;
                        else if(result==compid)
                                compscore++;
                        System.out.println("Score: Player-"+playerscore+" AI-"+compscore);
                        System.out.print("Another?(y/n):");
                        try
                        {
                                choice=br.readLine().charAt(0);
                        }
                        catch(Exception e)
                        {
                                System.out.println(e.getMessage());
                        }
 
                }while(choice!='n'||choice=='N');
 
                System.out.println("Game over.");
        }
        private void put(int cell,int player)
        {
                int i=-1,j=-1;;
                switch(cell)
                {
                case 1:i=2;j=0;break;
                case 2:i=2;j=1;break;
                case 3:i=2;j=2;break;
                case 4:i=1;j=0;break;
                case 5:i=1;j=1;break;
                case 6:i=1;j=2;break;
                case 7:i=0;j=0;break;
                case 8:i=0;j=1;break;
                case 9:i=0;j=2;break;
                default:display(overridegrid);return;
                }
                char mark='x';
                if(player==0)
                        mark='o';
                grid[i][j]=mark;
                display(grid);
        }
        private int startGame()
        {
                init();
                display(grid);
                int status=playingid;
                while(status==playingid)
                {
                        put(playerMove(),0);
                        if(override==1)
                        {
                                System.out.println("O winp.");
                                return playerid;
                        }
                        status=checkForWin();
                        if(status!=playingid)
                                break;
                        try{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());}
                        put(compMove(),1);
                        status=checkForWin();
                }
                return status;
        }
        private void init()
        {
                movesPlayer="";
                override=0;
                points=new int[8][6];
                winp=new int[][]        //new int[8][3];
                {       
                                {7,8,9},
                                {4,5,6},
                                {1,2,3},
                                {7,4,1},
                                {8,5,2},
                                {9,6,3},
                                {7,5,3},
                                {9,5,1}
                };
                wval=new int[]{3,2,3,2,4,2,3,2,3};
                grid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};
                csetter=new Hashtable<Integer,Integer>();
                ksetter=new Hashtable<Integer,Integer>();
        }
        private void mark(int m,int player)
        {
                for(int i=0;i<winp.length;i++)
                        for(int j=0;j<winp[i].length;j++)
                                if(winp[i][j]==m)
                                {
                                        points[i][j]=1;
                                        if(player==playerid)
                                                points[i][kcounter]++;
                                        else
                                                points[i][crosscounterer]++;
                                        points[i][totalcount]++;
                                }
        }
        private void fixwval()
        {
                for(int i=0;i<3;i++)
                        for(int j=0;j<3;j++)
                                if(points[i][j]==1)
                                        if(wval[winp[i][j]-1]!=Integer.MIN_VALUE)
                                                wval[winp[i][j]-1]=Integer.MIN_VALUE;
 
                for(int i=0;i<8;i++)
                {
                        if(points[i][totalcount]!=2)
                                continue;
                        if(points[i][crosscounterer]==2)
                        {
                                int p=i,q=-1;
                                if(points[i][0]==0)
                                        q=0;
                                else if(points[i][1]==0)
                                        q=1;
                                else if(points[i][2]==0)
                                        q=2;
 
                                if(wval[winp[p][q]-1]!=Integer.MIN_VALUE)
                                {
                                        wval[winp[p][q]-1]=6;
                                }
                        }
                        if(points[i][kcounter]==2)
                        {
                                int p=i,q=-1;
                                if(points[i][0]==0)
                                        q=0;
                                else if(points[i][1]==0)
                                        q=1;
                                else if(points[i][2]==0)
                                        q=2;
 
                                if(wval[winp[p][q]-1]!=Integer.MIN_VALUE)
                                {
                                        wval[winp[p][q]-1]=5;
                                }
                        }
                }
        }
        private int compMove()
        {
                int cell=move();
                System.out.println("Computer plays: "+cell);
                //wval[cell-1]=Integer.MIN_VALUE;
                return cell;
        }
        private int move()
        {
                int max=Integer.MIN_VALUE;
                int cell=0;
                for(int i=0;i<wval.length;i++)
                        if(wval[i]>max)
                        {
                                max=wval[i];
                                cell=i+1;
                        }
 
                //This section ensures the computer never loses
                //Remove it for a fair match
                //Dirty kluge
                if(movesPlayer.equals("76")||movesPlayer.equals("67"))
                        cell=9;
                else if(movesPlayer.equals("92")||movesPlayer.equals("29"))
                        cell=3;
                else if (movesPlayer.equals("18")||movesPlayer.equals("81"))
                        cell=7;
                else if(movesPlayer.equals("73")||movesPlayer.equals("37"))
                        cell=4*((int)(Math.random()*2)+1);
                else if(movesPlayer.equals("19")||movesPlayer.equals("91"))
                        cell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2)));
 
                mark(cell,1);
                fixwval();
                csetter.put(cell, 0);
                return cell;
        }
        private int playerMove()
        {
                System.out.print("What's your move?: ");
                BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                int cell=0;
                int okay=0;
                while(okay==0)
                {
                        try
                        {
                                cell=Integer.parseInt(br.readLine());
                        }
                        catch(Exception e)
                        {
                                System.out.println(e.getMessage());
                        }
                        if(cell==7494)
                        {
                                override=1;
                                return -1;
                        }
                        if((cell<1||cell>9)||wval[cell-1]==Integer.MIN_VALUE)
                                System.out.print("Invalid move. Try again:");
                        else
                                okay=1;
                }
                playerMoved(cell);
                System.out.println();
                return cell;
        }
        private void playerMoved(int cell)
        {
                movesPlayer+=cell;
                mark(cell,0);
                fixwval();
                ksetter.put(cell, 0);
        }
        private int checkForWin()
        {
                int crossflag=0,knotflag=0;
                for(int i=0;i<winp.length;i++)
                {
                        if(csetter.containsKey(winp[i][0]))
                                if(csetter.containsKey(winp[i][1]))
                                        if(csetter.containsKey(winp[i][2]))
                                        {
                                                crossflag=1;
                                                break;
                                        }
                        if(ksetter.containsKey(winp[i][0]))
                                if(ksetter.containsKey(winp[i][1]))
                                        if(ksetter.containsKey(winp[i][2]))
                                        {
                                                knotflag=1;
                                                break;
                                        }
                }
                if(knotflag==1)
                {
                        display(grid);
                        System.out.println("O winp.");
                        return playerid;
                }
                else if(crossflag==1)
                {
                        display(grid);
                        System.out.println("X winp.");
                        return compid;
                }
 
                for(int i=0;i<wval.length;i++)
                        if(wval[i]!=Integer.MIN_VALUE)
                                return playingid;
                System.out.println("Truce");
 
                return truceid;
        }
        private void display(char[][] grid)
        {
                for(int i=0;i<3;i++)
                {
                        System.out.println("\n-------");
                        System.out.print("|");
                        for(int j=0;j<3;j++)
                                System.out.print(grid[i][j]+"|");
                }
                System.out.println("\n-------");
        }
}
Add a comment
Know the answer?
Add Answer to:
Please help me code the following in: JAVA Please create the code in as basic way...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Create the Python code for a program that will simulate a basic car radio with 3...

    Create the Python code for a program that will simulate a basic car radio with 3 presets and 5 stations to tune in. You will create methods (class functions) for the following: __init__ AND __str__ seekNext longPressPreset1 through 3 shortPressPreset1 through 3 displayLCD You will create program functions for the following: main displayMenuGetOption Additional notes: You MUST use the program template. Your messages and prompts should look EXACTLY like those in the sample. Duplicating all blank lines and spacing. You...

  • Create the Python code for a program that will simulate a basic car radio with 3 presets and 5 st...

    Create the Python code for a program that will simulate a basic car radio with 3 presets and 5 stations to tune in. You will create methods (class functions) for the following: __init__ AND __str__ seekNext longPressPreset1 through 3 shortPressPreset1 through 3 displayLCD You will create program functions for the following: main displayMenuGetOption Additional notes: You MUST use the program template. Your messages and prompts should look EXACTLY like those in the sample. Duplicating all blank lines and spacing. You...

  • For your final project you will incorporate all your knowledge of Java that you learned in this class by programming the game of PIG. The game of Pig is a very simple jeopardy dice game in which two p...

    For your final project you will incorporate all your knowledge of Java that you learned in this class by programming the game of PIG. The game of Pig is a very simple jeopardy dice game in which two players race to reach 100 points. Each turn, a player repeatedly rolls a die until either a 1 is rolled or the player holds and scores the sum of the rolls (i.e. the turn total). At any time during a player's turn,...

  • THIS IS IN THE JAVA SCRIPT CODE ALSO PLEASE SEND ME THE CODE TYPED THANK YOU....

    THIS IS IN THE JAVA SCRIPT CODE ALSO PLEASE SEND ME THE CODE TYPED THANK YOU. Program 1 Write an inheritance hierarchy of three-dimensional shapes. Make a top-level shape interface that has methods for getting information such as the volume and the surface area of a three-dimensional shape. Then make classes and subclasses that implement various shapes such as cube, cylinders and spheres. Place common behavior in superclasses whenever possible, and use abstract classes as appropriate. Add methods to the...

  • Code a Java program to create and use OO classes. Comment your code throughout. Create a...

    Code a Java program to create and use OO classes. Comment your code throughout. Create a Super class named Home Properties address SF (this is the number of Square feet) value (this is the dollar value of the home) Methods Set and get methods for all properties calcValue() - calculate the value as sf * 400 displayCondo() - displays all properties of a condo Create a sub class named Condo Properties HOAfee (home owners association fee) Methods Set and get...

  • Summary Write a program that demonstrates the skills you’ve learned throughout this quarter. This type of...

    Summary Write a program that demonstrates the skills you’ve learned throughout this quarter. This type of project offers only a few guidelines and requirements, allowing you to invest as much time, effort and imagination as you want.  Submit your java programs (*.java) and any other I/O (*.txt) via Canvas  You’ve worked quite hard to make it this far, so have a bit of fun with this project! Design Brief: Use Case Scenario You are hired to develop a...

  • his assignment will help the student by: Create shapes using Java code Using and creating colors...

    his assignment will help the student by: Create shapes using Java code Using and creating colors with Java Coding JFrames and using the Graphics g method Using Loops (to draw) Your program will generate a drawing using java. You should draw an object that makes sense, not just spare shapes and colors. You must use at least 3 different shapes You must use at least 2 different fonts You must use at least 2 predefined java colors and one custom-made...

  • I need this in java please Create an automobile class that will be used by a...

    I need this in java please Create an automobile class that will be used by a dealership as a vehicle inventory program. The following attributes should be present in your automobile class: private string make private string model private string color private int year private int mileage. Your program should have appropriate methods such as: default constructor parameterized constructor add a new vehicle method list vehicle information (return string array) remove a vehicle method update vehicle attributes method. All methods...

  • Help please, write code in c++. The assignment is about making a hangman game. Instructions: This...

    Help please, write code in c++. The assignment is about making a hangman game. Instructions: This program is part 1 of a larger program. Eventually, it will be a complete Hangman game. For this part, the program will Prompt the user for a game number, Read a specific word from a file, Loop through and display each stage of the hangman character I recommend using a counter while loop and letting the counter be the number of wrong guesses. This...

  • i need this in C# please can any one help me out and write the full...

    i need this in C# please can any one help me out and write the full code start from using system till end i am confused and C# is getting me hard.I saw codes from old posts in Chegg but i need the ful complete code please thanks. Module 4 Programming Assignment – OO Design and implementation (50 points) Our Battleship game needs to store a set of ships. Create a new class called Ships. Ships should have the following...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT