import javautil This file includes 1 Solution to P3 2 Que

import java.util.*;

/* This file includes:
*    1. Solution to P3
* 2. Questions for P4. Comments starting with REQ represent the questions.
*

Features:
- We have from 1 to 3 players
- We have many questions grouped in 3 categories . Each player chooses a category before being asked.
- Each player may be asked more than one question from different categories.
- User can play many rounds of the game.

Focus:
    - 2-D arrays

Aim:
    - Build more complex programs that involves the use of 2-D arrays

REQ:
You should build on your code from part P4 and satisfy the following requirements:
1. Create three categories of questions in a 2D array (rows=categories, col=questions).
in each player\'s turn, ask the player about the required category and then ask a question from that category.
make all necessary changes to your program (e.g. shuffle method should now work for 2D array)
2. If we are out of questions in a category (i.e., all questions in this category were offered and answered correctly), inform the player to choose another category.

public class Main {              
   static Game game;          
  
   //Two arrays for questions and answers (both are global, i.e., accessible by all code in the class).
   static String[] questions = {\"what class is this?\",\"What year is this?\", \"What is the best show?\", \"Best movie?\", \"Subject that relates to comp sci?\", \"Who won the Valisimar game?\", \"Staple college food?\", \"Place to get Coffee?\", \"Cheap Place to get Coffee?\"};
   static String[] answers =    {\"COSC\", \"2016\", \"Suits\", \"Mulan\", \"Math\", \"Val\", \"KD\", \"Starbucks\", \"Tim\'s\"};
  
   public static void main(String[] args) {
       String ans;
       do{                              
           //Reset the game
           game = new Game();          
          
           //Get number of players (from 1 to 3)
           int numPlayers = game.askForInt(\"How many players\", 1, 3);

           //Add up to 3 players to the game
           for (int i = 0; i < numPlayers; i++) {
               String name = game.askForText(\"What is player \" + (i+1) + \" name?\");
               game.addPlayer(name);              
           }

int MaxQuestion=questions.length/numPlayers;   
int numQuestions=game.askForInt(\"How many questions should be given to each player?\", 1, MaxQuestion);
  
if(numQuestions>MaxQuestion)
   numQuestions=MaxQuestion;
  
int temp=0;

for (int i = 0; i < numPlayers; i++) {
               game.setCurrentPlayer(i);//draw rectangle around player 0, and currentPlayer = player0
               String answer = game.askForText(questions[i]);
               for(int kk=0;kk<numQuestions;kk++){

                  
                   while(true){ //Loop the ask the question repeatedly if user answered wrongly

                      

if(temp==questions.length)//If all questions are asked then start from the first question.
temp=0;

//ask the player the next unanswered question

answer = game.askForText(questions[temp]);

//Check answer is correct
  
if(answers[temp].equals(answer)){

   game.correct();
   temp++;
break;

}else //keep asking until someone answers correctly.
   game.incorrect();
   ++i;
   if (i>=numPlayers){
       i=0;
       game.setCurrentPlayer(i);
   }
   game.setCurrentPlayer(i);
  
  
}

} }
                      
           //Do you want to play again? make sure you get valid input
           ans = game.askForText(\"Play again? (Y/N)\");
           while(ans != null && !ans.toUpperCase().equals(\"Y\") && !ans.toUpperCase().equals(\"N\"))
               ans = game.askForText(\"Invalid input. Play again? (Y/N)\");
           }while(ans.toUpperCase().equals(\"Y\"));   //play again if the user answers \"Y\" or \"y\"
          
           System.exit(1);   //This statement terminates the program
       }
       public static void shuffleQuestions ()

{

//Generate random variable

Random rk=new Random();

//find length of the questions array

int nlen=questions.length;

for(int kk=0;kk<nlen;kk++)

{


int tt=kk+rk.nextInt(nlen-kk);

//swap questions

String temp=questions[kk];

questions[kk]=questions[tt];

questions[tt]=temp;

//also swap answers

temp=answers[kk];

answers[kk]=answers[tt];

answers[tt]=temp;

          
       }
   }
}

//end of main class

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

@SuppressWarnings(\"serial\")
public class BDialog extends JDialog {
  
private JButton btnAnswer = new JButton(\"Answer\");
private JButton btnExit = new JButton(\"Exit\");
private JTextField txtAnswer = new JTextField(10);
private JLabel lblMsg = new JLabel(\"This is a message\");
private String result;
public BDialog(JFrame frame) {
super(frame, true);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
setUndecorated(true);
setLayout(new GridLayout(2, 1));
getContentPane().setBackground(Color.black);
  
//set font and color
Font font = new Font(\"Arial\", Font.BOLD, 20);
lblMsg.setFont(font);
lblMsg.setForeground(Color.CYAN);
txtAnswer.setFont(font);
btnAnswer.setFont(font);
btnExit.setFont(font);
  
JPanel tmpPanel = new JPanel();
//tmpPanel.setBackground(Color.black);
tmpPanel.setOpaque(false);
tmpPanel.add(lblMsg);
add(tmpPanel);
tmpPanel = new JPanel();
//tmpPanel.setBackground(Color.black);
tmpPanel.setOpaque(false);
tmpPanel.add(txtAnswer);
tmpPanel.add(btnAnswer);
tmpPanel.add(btnExit);
add(tmpPanel);

//pack();
MyHandler handler = new MyHandler();
btnAnswer.addActionListener(handler);
txtAnswer.addActionListener(handler);
btnExit.addActionListener(handler);
}
public String showInputDialog(String msg){
   lblMsg.setText(msg);
   setVisible(true);
   return result;
}
public void showMessageDialog(String msg){
   lblMsg.setText(msg);
   setVisible(true);
}
private class MyHandler implements ActionListener{
       public void actionPerformed(ActionEvent e) {
           if(e.getSource() == btnExit){
               if(JOptionPane.showConfirmDialog(null, \"Really want to exit?\",\"Confirmation\", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
                   System.exit(0);
           }else{
               result = txtAnswer.getText();
               txtAnswer.setText(\"\");
               setVisible(false);
           }
       }
}
}

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.util.ArrayList;

public class Game {
   public static final int WIDTH = 800, HEIGHT = 500, MAX_PLAYERS = 3, PLAYER_Y = 50;
   protected ArrayList<Player> players = new ArrayList<Player>(MAX_PLAYERS);
   private GameFrame frame = new GameFrame(this, \"COSC 111 Jeopardy\", WIDTH, HEIGHT);
   private BDialog dialog = new BDialog(frame);
   private Player currentPlayer;
   private Color responseColor = Color.white;
  
   public Game(){
       frame.setLocationRelativeTo(null);
       dialog.setLocationRelativeTo(frame);
       dialog.setSize(WIDTH-10, 100);
       dialog.setLocation(frame.getX()+5, frame.getY() + HEIGHT - 105);
       frame.setVisible(true);
   }
   public void print(String msg){
       frame.repaint();
       dialog.showMessageDialog(msg);
   }
   public String askForText(String msg){
       frame.repaint();
       String response = dialog.showInputDialog(msg);
       return (response==null || response.length()==0)? \"\" : response.trim();
   }
   public int askForInt(String msg, int min, int max){
       msg += \"(\" + min + \" to \" + max + \")\";
       boolean found = false, msgModified = false;
       int num = 0;
       while(!found){
           try{
               num = Integer.parseInt(askForText(msg));
               if(num<min || num>max)
                   throw new Exception();
               found = true;
           }catch(Exception e){
               if(!msgModified) msg = \"Invlid input. \" + msg;
               msgModified = true;
           }
       }
       return num;
   }
  
   public void addPlayer(String name){
       Player player = new Player(name);
       int playerWidth = player.getImg().getWidth();
       int distanceBetweenPlayers = (WIDTH - MAX_PLAYERS * playerWidth) / (MAX_PLAYERS + 1);
       int x = (players.size()+1) * distanceBetweenPlayers + players.size() * playerWidth;
       player.setX(x);
       player.setY(PLAYER_Y);
       players.add(player);
       frame.repaint();
   }
   public void clearPlayers(){
       players.clear();
   }
   public void paint(Graphics2D g2){
       //draw players
       for (int i = 0; i < players.size(); i++)
           players.get(i).paint(g2);
       //draw frame around selected player
       if(currentPlayer != null){
           int px = currentPlayer.getX()-4;
           int py = currentPlayer.getY()-4;
           int pw = currentPlayer.getImg().getWidth()+8;
           int ph = currentPlayer.getImg().getHeight()+8;
           g2.setStroke(new BasicStroke(8));
           g2.setColor(responseColor);
           g2.drawRect(px, py, pw, ph);
       }
       //who is turn it is
       if(currentPlayer != null){
           g2.setColor(Color.yellow);
           String name = currentPlayer.getName() + \"\'s turn\";
           Font font = new Font(\"Arial\", Font.BOLD, 28);
           g2.setFont(font);
           FontMetrics metrics = g2.getFontMetrics(font);
           int txtWidth = metrics.stringWidth(name);
           g2.drawString(name, (WIDTH-txtWidth)/2, 35);
       }
   }
   public void setCurrentPlayer(int pl) {
       currentPlayer = players.get(pl);
       responseColor = new Color(255, 160, 255);
   }
   public void correct() {
       responseColor = Color.green;
       frame.repaint();
       if(currentPlayer != null)
           currentPlayer.incrementScore();
       print(\"Correct (press Enter to continue).\");
   }
   public void incorrect() {
       responseColor = Color.red;
       frame.repaint();
       print(\"Sorry, that is incorrect answer (press Enter to continue).\");
   }
}

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings(\"serial\")
public class GameFrame extends JFrame{
   private Game game;
   public GameFrame(Game game, String title, int width, int height) {
       this.game = game;
       //attributes
       setSize(width, height);
       setTitle(title);
       setUndecorated(true);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
       //create and add objects
       add(new GamePanel());
   }
  
   private class GamePanel extends JPanel{
       BufferedImage myImage;
       public GamePanel() {
           //setBackground(Color.BLACK);
           try {
               myImage = ImageIO.read(new File(\"background.jpg\"));
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       public void paint(Graphics g) {
           super.paint(g);
           g.drawImage(myImage, 0, 0, this);
           game.paint((Graphics2D)g);
       }

   }

}

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Player {
   private String name;
   private int score, x, y;
   //private static Image img = Toolkit.getDefaultToolkit().getImage(\"MisterX.jpg\");
   private BufferedImage img;
   public Player(String name){
       this.name = name;
       try {
           img = ImageIO.read(new File(\"MisterX.jpg\"));
       } catch (IOException e) {}
   }
      
   public void paint(Graphics2D g2){
       g2.drawImage(img, x, y, null);
       g2.setColor(new Color(255, 210, 0));
       Font font = new Font(\"Arial\", Font.PLAIN, 18);
       FontMetrics metrics = g2.getFontMetrics(font);
       int nameWidth = metrics.stringWidth(name);
       g2.setFont(font);
       g2.drawString(name, x + (img.getWidth(null)-nameWidth)/2, y + img.getHeight(null)-5);

       g2.setFont(new Font(\"Arial\", Font.BOLD, 22));
       g2.setColor(new Color(150, 255, 255));
       g2.drawString(\"$\" + score, x+10, y + img.getHeight(null)+55);
   }

   public String getName() {
       return name;
   }
   public int getScore() {
       return score;
   }
   public void incrementScore(){
       score+=100;
   }
   public int getX() {
       return x;
   }
   public int getY() {
       return y;
   }
   public BufferedImage getImg() {
       return img;
   }
   public void setX(int x) {
       this.x = x;
   }
   public void setY(int y) {
       this.y = y;
   }
   public void setImg(BufferedImage img) {
       this.img = img;
   }
}

Solution

PROGRAM CODE:

package samplepro;

import java.util.Random;

public class Main {

static Game game;

  

//Two arrays for questions and answers (both are global, i.e., accessible by all code in the class).

static String[] questions = {\"what class is this?\",\"What year is this?\", \"What is the best show?\", \"Best movie?\", \"Subject that relates to comp sci?\", \"Who won the Valisimar game?\", \"Staple college food?\", \"Place to get Coffee?\", \"Cheap Place to get Coffee?\"};

static String[] answers = {\"COSC\", \"2016\", \"Suits\", \"Mulan\", \"Math\", \"Val\", \"KD\", \"Starbucks\", \"Tim\'s\"};

static String categories[][] = new String[3][3];

public static void main(String[] args) {

String ans;
int counter = 0;
for(int i=0; i<3; i++)
{
   categories[i] = new String[3];
   for(int j=0; j<3; j++)
   {
       categories[i][j] = questions[counter];
       counter++;
   }
}
//this is how you would relate the 2D array and the answer array - comment this code later.
//this is just for your understanding
for(int i=0; i<3; i++)
{
   for(int j=0; j<3; j++)
   {
       System.out.println(categories[i][j]);
       System.out.println(answers[(j)+(i*3)]);
   }
}

do{

//Reset the game

game = new Game();

  

//Get number of players (from 1 to 3)

int numPlayers = game.askForInt(\"How many players\", 1, 3);

//Add up to 3 players to the game

for (int i = 0; i < numPlayers; i++) {

String name = game.askForText(\"What is player \" + (i+1) + \" name?\");

game.addPlayer(name);

}

int MaxQuestion=questions.length/numPlayers;

int numQuestions=game.askForInt(\"How many questions should be given to each player?\", 1, MaxQuestion);

  

if(numQuestions>MaxQuestion)

numQuestions=MaxQuestion;

  

int temp=0, m = 0, n = 0;

for (int i = 0; i < numPlayers; i++) {

game.setCurrentPlayer(i);//draw rectangle around player 0, and currentPlayer = player0

String answer = game.askForText(categories[i][0]); //category is selected based on the players and the first question in that category is asked

for(int kk=0;kk<numQuestions;kk++){

  

while(true){ //Loop the ask the question repeatedly if user answered wrongly

  

if(temp==categories.length * categories[0].length)//If all questions are asked then start from the first question.
   temp=0;

//calculating the row and column values using temp and the length of the category array
m = temp/categories.length;
n = temp%categories[0].length;
//ask the player the next unanswered question
   answer = game.askForText(categories[m][n]);
//answer = game.askForText(questions[temp]);

//Check answer is correct

  

if(answers[temp].equals(answer)){

game.correct();

temp++;

break;

}else //keep asking until someone answers correctly.

game.incorrect();

++i;

if (i>=numPlayers){

i=0;

game.setCurrentPlayer(i);

}

game.setCurrentPlayer(i);

  

  

}

} }

  

//Do you want to play again? make sure you get valid input

ans = game.askForText(\"Play again? (Y/N)\");

while(ans != null && !ans.toUpperCase().equals(\"Y\") && !ans.toUpperCase().equals(\"N\"))

ans = game.askForText(\"Invalid input. Play again? (Y/N)\");

}while(ans.toUpperCase().equals(\"Y\")); //play again if the user answers \"Y\" or \"y\"

  

System.exit(1); //This statement terminates the program

}

public static void shuffleQuestions ()

{

//Generate random variable

Random rk=new Random();

//find length of the questions array

int nlen=categories.length * categories[0].length;

for(int kk=0;kk<nlen;kk++)

{

int tt=kk+rk.nextInt(nlen-kk);

//getting the m and n value using the existing values of tt and kk
int mtt = tt/categories.length;
int ntt= tt%categories[0].length;
int mkk = kk/categories.length;
int nkk = kk%categories[0].length;
//swap questions

String temp=categories[mkk][nkk];

categories[mkk][nkk]=categories[mtt][ntt];

categories[mtt][ntt]=temp;

//also swap answers

temp=answers[kk];

answers[kk]=answers[tt];

answers[tt]=temp;

  

}

}

}

//end of main class

Modified the Main class to work on 2D arrays. This includes the shuffle function as well.

import java.util.*; /* This file includes: * 1. Solution to P3 * 2. Questions for P4. Comments starting with REQ represent the questions. * Features: - We have
import java.util.*; /* This file includes: * 1. Solution to P3 * 2. Questions for P4. Comments starting with REQ represent the questions. * Features: - We have
import java.util.*; /* This file includes: * 1. Solution to P3 * 2. Questions for P4. Comments starting with REQ represent the questions. * Features: - We have
import java.util.*; /* This file includes: * 1. Solution to P3 * 2. Questions for P4. Comments starting with REQ represent the questions. * Features: - We have
import java.util.*; /* This file includes: * 1. Solution to P3 * 2. Questions for P4. Comments starting with REQ represent the questions. * Features: - We have
import java.util.*; /* This file includes: * 1. Solution to P3 * 2. Questions for P4. Comments starting with REQ represent the questions. * Features: - We have
import java.util.*; /* This file includes: * 1. Solution to P3 * 2. Questions for P4. Comments starting with REQ represent the questions. * Features: - We have
import java.util.*; /* This file includes: * 1. Solution to P3 * 2. Questions for P4. Comments starting with REQ represent the questions. * Features: - We have
import java.util.*; /* This file includes: * 1. Solution to P3 * 2. Questions for P4. Comments starting with REQ represent the questions. * Features: - We have
import java.util.*; /* This file includes: * 1. Solution to P3 * 2. Questions for P4. Comments starting with REQ represent the questions. * Features: - We have
import java.util.*; /* This file includes: * 1. Solution to P3 * 2. Questions for P4. Comments starting with REQ represent the questions. * Features: - We have

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site