import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class Checkers extends JPanel {
public static void main(String[] args) {
JFrame window = new JFrame(\"Checkers\");
Checkers content = new Checkers();
window.setContentPane(content);
window.pack();
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screensize.width - window.getWidth())/2,
(screensize.height - window.getHeight())/2 );
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setResizable(false);
window.setVisible(true);
}
private JButton newGameButton; // Button for starting a new game.
private JButton resignButton; // Button that a player can use to end
// the game by resigning.
private JLabel message; // Label for displaying messages to the user.
public Checkers() {
setLayout(null); // I will do the layout myself.
setPreferredSize( new Dimension(350,250) );
setBackground(new Color(0,150,0)); // Dark green background.
/* Create the components and add them to the applet. */
Board board = new Board(); // Note: The constructor for the
// board also creates the buttons
// and label.
add(board);
add(newGameButton);
add(resignButton);
add(message);
/* Set the position and size of each component by calling
its setBounds() method. */
board.setBounds(20,20,164,164); // Note: size MUST be 164-by-164 !
newGameButton.setBounds(210, 60, 120, 30);
resignButton.setBounds(210, 120, 120, 30);
message.setBounds(0, 200, 350, 30);
} // end constructor
private static class CheckersMove {
int fromRow, fromCol; // Position of piece to be moved.
int toRow, toCol; // Square it is to move to.
CheckersMove(int r1, int c1, int r2, int c2) {
// Constructor. Just set the values of the instance variables.
fromRow = r1;
fromCol = c1;
toRow = r2;
toCol = c2;
}
boolean isJump() {
// Test whether this move is a jump. It is assumed that
// the move is legal. In a jump, the piece moves two
// rows. (In a regular move, it only moves one row.)
return (fromRow - toRow == 2 || fromRow - toRow == -2);
}
} // end class CheckersMove.
private class Board extends JPanel implements ActionListener, MouseListener {
CheckersData board; // The data for the checkers board is kept here.
// This board is also responsible for generating
// lists of legal moves.
boolean gameInProgress; // Is a game currently in progress?
/* The next three variables are valid only when the game is in progress. */
int currentPlayer; // Whose turn is it now? The possible values
// are CheckersData.RED and CheckersData.BLACK.
int selectedRow, selectedCol; // If the current player has selected a piece to
// move, these give the row and column
// containing that piece. If no piece is
// yet selected, then selectedRow is -1.
CheckersMove[] legalMoves; // An array containing the legal moves for the
// current player.
Board() {
setBackground(Color.BLACK);
addMouseListener(this);
resignButton = new JButton(\"Resign\");
resignButton.addActionListener(this);
newGameBu.
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfanjandavid
In Java using Eclipse, I\'m suppose to write a class that encapsulates a tic tac toe board using two
dimensional arrays. It should only involve the human player vs. the computer, and should
randomly select who should use \'X\' or \'O\' and whether the human player or the computer
should go first. Verify that all moves by the human player are to a valid space on the tic-tac-toe
board, and an incorrect choice should not halt or terminate the game. Below is my Java program
that is currently a work in progress. Can you help me remodify it? Thanks.
import java.util.Scanner;
public class LeavinesTicTacToe
{
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
final int SIZE = 3;
char[][] board = new char[SIZE][SIZE]; // game board
resetBoard(board); // initialize the board (with \' \' for all cells)
// First, welcome message and display the board.
System.out.println(\"===== WELCOME TO THE TIC-TAC-TOE GAME!! =====\ \");
showBoard(board);
// Then ask the user which symbol (x or o) he/she wants to play.
System.out.print(\" Which symbol do you want to play, \\\"x\\\" or \\\"o\\\"? \");
char userSymbol = sc.next().toLowerCase().charAt(0);
char compSymbol = (userSymbol == \'x\') ? \'o\' : \'x\';
// Also ask whether or not the user wants to go first.
System.out.println();
System.out.print(\" Do you want to go first (y/n)? \");
char ans = sc.next().toLowerCase().charAt(0);
int turn; // 0 -- the user, 1 -- the computer
int remainCount = SIZE * SIZE; // empty cell count
// THE VERY FIRST MOVE.
if (ans == \'y\') {
turn = 0;
userPlay(board, userSymbol); // user puts his/her first tic
}
else {
turn = 1;
compPlay(board, compSymbol); // computer puts its first tic
}
// Show the board, and decrement the count of remaining cells.
showBoard(board);
remainCount--;
// Play the game until either one wins.
boolean done = false;
int winner = -1; // 0 -- the user, 1 -- the computer, -1 -- draw
while (!done && remainCount > 0) {
// If there is a winner at this time, set the winner and the done flag to true.
done = isGameWon(board, turn, userSymbol, compSymbol); // Did the turn won?
if (done)
winner = turn; // the one who made the last move won the game
else {
// No winner yet. Find the next turn and play.
turn = (turn + 1 ) % 2;
if (turn == 0)
userPlay(board, userSymbol);
else
compPlay(board, compSymbol);
// Show the board after one tic, and decrement the rem count.
showBoard(board);
remainCount--;
}
}
// Winner is found. Declare the winner.
if (winner == 0)
System.out.println(\"\ ** YOU WON. CONGRATULATIONS!! **\");
else if (winner == 1)
System.out.println(\"\ ** YOU LOST.. Maybe next time :) **\");
else
System.out.println(\"\ ** DRAW... **\");
}
public static void resetBoard(char[][] brd)
{
for (int i = 0; i < brd.length; i++)
for (int j = 0; j < brd[0].length; j++)
brd[i][j] = \' \';
}
public static void showBoard(char[][] brd)
{
int numRow = brd.length;
int numCol = brd[0].length;
System.out.println();
// First write the column he.
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdfflashfashioncasualwe
Need to make a Reversi/Othello Board game in JAVA
The board size can be N x N (so 4x4 is default, and it could be larger like 5x5, 6x6 etc. NEEDS
TO BE ABLE TO WORK WITH ODD SIZE)
Player 1 is going to be you and your going to be the black tiles, and the AI is going to be the
white tiles. Black tiles will start the game, and then white will go after them, then back to black,
repeat. The players must put a disc of their color on an empty square, adjacent to their
opponent\'s disc. Any of the oppponents tiles in between the tile put down, and another of your
tiles will cause them to flip to your color. The winner is decided when the board is completely
filled or no viable moves are left, and whoever has the most pieces.
This program is meant to be simple design (no GUI or big interface designs), broken into
multiple classes (can be extension\'s off the class or abstract interface off each other), and the
user will be entering the coordinates of where to put the pieces (so just using scanner method)?.
The start of the game must always have 4 tiles put down in the center (so the center can change
depending on the size of the board), and the gameplay would look something like this
Again, coding done in JAVA is what I\'m looking for.
Scenario in which the game ends early.
JAVA code BW Success: Black move at C1, 0) BW Score: Black: 4, White: 1 Success: White
move at C2, 0D
Solution
package Reversi_Othello_GameReversiOthello;
import java.awt.*;
import java.applet.*;
public class Reversi_Othello_GameReversiOthello extends Applet implements Runnable {
Thread runner; // declare a thread for this GameReversiOthello
boolean black_shown = false; // flag to signal pause
boolean show_em = false;
final int BLACK = 1; // declare state of each square
final int WHITE = 2;
final int EMPTY = 0;
final int OFFBOARD = -1;
final static int GameReversiOthello[][] = new int[10][10]; //10x10 matrix of squares
protected int Count_Black = 0;
protected int Count_White = 0;
Event evt;
int x, y;
public void start() // create a thread and start it
{
if (runner == null) {
black_shown = false;
runner = new Thread(this);
runner.start();
}
}
public void stop() // stop the thread
{
if (runner != null) {
runner.stop();
runner = null;
black_shown = false;
}
}
public synchronized void run() // initialize screen
{
setBackground(Color.green);
for (int i = 0; i < 10; i++) // initialize off-board squares
{
GameReversiOthello[i][0] = OFFBOARD;
GameReversiOthello[i][9] = OFFBOARD;
GameReversiOthello[0][i] = OFFBOARD;
GameReversiOthello[9][i] = OFFBOARD;
}
for (int i = 1; i < 9; i++) // initialize GameReversiOthello board to be empty
{
for (int j = 1; j < 9; j++) {
GameReversiOthello[i][j] = EMPTY;
}
}
GameReversiOthello[4][4] = WHITE; // except for initial set up
GameReversiOthello[5][4] = BLACK;
GameReversiOthello[4][5] = BLACK;
GameReversiOthello[5][5] = WHITE;
while (runner != null) // signal thread to wait after painting
{ // black and before white responds
while (!black_shown) {
try {
w.
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfrajkumarm401
Objective:
Create a graphical game of minesweeper IN JAVA. The board should consist of 10x10 buttons.
Of the 100 spaces there should be at least 20 randomly placed mines. If the button is clicked and
it is not a mine then it clears itself. If a space has been cleared then it should indicate how many
of its eight neighbors are mines. If a space is clicked and it is a mine then the game is over and
the player is asked if they want to play again. Finally, if all the non-mine spaces have been
clicked then the player is prompted that they won.
Solution
2 files need to be made.
First Game.Java which will have the gaming logic and User Interface and Main.Java which will
have have the main method and object of Game.java Number of rows and cols is customizable so
user can change that as and when needed.
import java.awt.*;
import java.awt.Dimension;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Game extends JFrame implements ActionListener, ContainerListener {
int fw, fh, blockr, blockc, var1, var2, num_of_mine, detectedmine = 0, savedlevel = 1,
savedblockr, savedblockc, savednum_of_mine = 10;
int[] r = {-1, -1, -1, 0, 1, 1, 1, 0};
int[] c = {-1, 0, 1, 1, 1, 0, -1, -1};
JButton[][] blocks;
int[][] countmine;
int[][] colour;
ImageIcon[] ic = new ImageIcon[14];
JPanel panelb = new JPanel();
JPanel panelmt = new JPanel();
JTextField tf_mine, tf_time;
JButton reset = new JButton(\"\");
Random ranr = new Random();
Random ranc = new Random();
boolean check = true, starttime = false;
Point framelocation;
Stopwatch sw;
MouseHendeler mh;
Point p;
Game() {
super(\"Game\");
setLocation(400, 300);
setic();
setpanel(1, 0, 0, 0);
setmanue();
sw = new Stopwatch();
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
sw.stop();
setpanel(savedlevel, savedblockr, savedblockc, savednum_of_mine);
} catch (Exception ex) {
setpanel(savedlevel, savedblockr, savedblockc, savednum_of_mine);
}
reset();
}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
show();
}
public void reset() {
check = true;
starttime = false;
for (int i = 0; i < blockr; i++) {
for (int j = 0; j < blockc; j++) {
colour[i][j] = \'w\';
}
}
}
public void setpanel(int level, int setr, int setc, int setm) {
if (level == 1) {
fw = 200;
fh = 300;
blockr = 10;
blockc = 10;
num_of_mine = 10;
} else if (level == 2) {
fw = 320;
fh = 416;
blockr = 16;
blockc = 16;
num_of_mine = 70;
} else if (level == 3) {
fw = 400;
fh = 520;
blockr = 20;
blockc = 20;
num_of_mine = 150;
} else if (level == 4) {
fw = (20 * setc);
fh = (24 * setr);
blockr = setr;
blockc = setc;
num_of_mine = setm;
}
savedblockr = blockr;
savedblockc = blockc;
savednum_of_mine = num_of_mine;
setSize(fw, fh);
setResizable(false);
detectedmine = num_of_mine;
p = this.getLocation();
blocks = new JButton[blockr][blockc];
countmine = new int[blockr][blockc];
colour = new int[blockr][blockc];
mh = new MouseHendeler();
getContentPane().removeAll();
panelb.removeAll();
tf_mine = new JTe.
Hello!This is Java assignment applet.Can someone help me writing.pdfjyothimuppasani1
Hello!
This is Java assignment applet.
Can someone help me writing a code how to exit the game when I press no in question( would
you like to play again?). Also if no one wins or draws i would like to pop up the question ( would
you like to play again?). I have the code below i would like someone to add it
Thanks in advance!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TicTacToe extends Applet implements ActionListener{
// Array to store buttons
JButton button[][] = new JButton[3][3];
boolean isNewGame =false;
// To switch player either X or O
boolean isZero = true; //first turn is always 0
// Setup size
// Set layout to grid
// Create buttons through loop
// Add buttons to layout
// Add listener
public void init(){
setSize(500, 500);
setLayout(new GridLayout(3,3));
// if it is not a new game
if(isNewGame==false) {
// Adding buttons to layout
//initialize the Grid and add ActionListener to each Button
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
// init jButton
button[i][j] = new JButton(\"\");
// Setup Font and Size here
button[i][j].setFont(new Font(\"Lucida Grande\", Font.PLAIN, 28));
// Add is a method from applet to add buttons in layout
add(button[i][j]);
// Listener
button[i][j].addActionListener(this);
}
}
}
else {
// If we need to restart the game, then we only set text to empty
// Back to black color
// add listener
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
button[i][j].setText(\"\");
button[i][j].setForeground(Color.BLACK);
button[i][j].removeActionListener(this);
button[i][j].addActionListener(this);
}
}
}
}
// Go all the buttons in arrsy
// Check the event with button in array
// if player O is true, set button text O. Otherwise. X
// Remove Listerner. Why? only once you can click
// Change player by isZero
// Check for winner
public void actionPerformed(ActionEvent event){
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++){
if((event.getSource() == button[i][j])){
if(isZero){
button[i][j].setText(\"O\");
}
else{
button[i][j].setText(\"X\");
}
button[i][j].removeActionListener(this); //you cannot click on one tile more than
once
isZero = !isZero;
checkForWinners(); //check if any winner after each move
}
}
}
public void checkForWinners(){
//3 horizontal lines
for(int i = 0; i < 3; i++){
if(button[i][0].getText().equals(button[i][1].getText())
&& button[i][1].getText().equals(button[i][2].getText())
&& !button[i][0].getText().equals(\"\")){
String player = button[i][0].getText();
button[i][0].setForeground(Color.RED);
button[i][1].setForeground(Color.RED);
button[i][2].setForeground(Color.RED);
int reply =JOptionPane.showConfirmDialog(null, player + \" wins!\"+\"\ Would like
to play again?\",\"Game over\",JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
isNewGame = true;
init();
return;
}
else {
System.exit(0);
return;
}
}
}
//3 vertical lines
for(int i = 0; i < 3; i++){
if(button[0][i].getText().equals(button[1][i].getText())
&& .
Need help writing the code for a basic java tic tac toe game Tic.pdfhainesburchett26321
Need help writing the code for a basic java tic tac toe game
// Tic-Tac-Toe: Complete the FIX-ME\'s to have a working version of Tic-Tac-Toe.
// Note: the basis of the game is a two-dimensional \'board\' array, with 3 rows
// and 3 columns. A value of +1 indicates an \'X\' on the board; and a value of
// -1 indicates an \'O\'
// Group Member names:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.*;
public class TicTacToe implements ActionListener{
// FIX ME #5: set CPU_PAUSE to true when ready to play
final boolean CPU_PAUSE = true; // does the CPU pause to think?
JButton [][] buttons = new JButton[3][3];
int [][] board = new int[3][3];
JLabel status = new JLabel(\"Player\'s turn\", JLabel.CENTER);
JFrame frame = new JFrame();
JPanel buttonPanel = new JPanel();
JPanel labelPanel = new JPanel();
Timer timer = null;
// draw X or O depending on \'x\' values
void refresh(int [][] x) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (x[i][j] == 1) {
buttons[i][j].setForeground(Color.blue);
buttons[i][j].setText(\"X\");
} else if (x[i][j] == -1) {
buttons[i][j].setForeground(Color.pink);
buttons[i][j].setText(\"O\");
} else {
buttons[i][j].setText(\" \");
}
}
}
}
boolean have_winner(int checkVal) {
boolean winner = false;
// FIX ME #1: if there are three \'checkVal\' values in-a-row across,
// then set \'winner\' to true
// FIX ME #2: if there are three \'checkVal\' values in-a-row vertically,
// then set \'winner\' to true
int checkSum = 0;
if (checkSum == 3 * checkVal){
winner = true;
}
// FIX ME #3: if there are three \'checkVal\' values in-a-row diagonally,
// then set \'winner\' to true
return winner;
}
boolean playerMove(ActionEvent e) {
JButton btn = (JButton) e.getSource();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (btn.equals(buttons[i][j])) {
if (board[i][j] != 0) {
return false;
}
board[i][j] = 1;
refresh(board);
return true;
}
}
}
return false;
}
boolean board_is_full() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == 0) return false;
}
}
return true;
}
ActionListener refreshListener = new ActionListener(){
int delayCount = 0;
public void actionPerformed(ActionEvent event){
delayCount++;
if (delayCount > 5) {
delayCount = 0;
timer.stop();
enableButtons(false);
}
if (delayCount % 2 == 0) {
refresh(board);
} else {
int [][] x = new int[3][3];
refresh(x);
}
}
};
void enableButtons(boolean enable) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setEnabled(enable);
}
}
}
ActionListener computerMove = new ActionListener(){
public void actionPerformed(ActionEvent event){
/* FIX ME #4: The computer moves by placing an \'O\' on the board
* (i.e.), assigning a -1 to a valid element of the board array
* The computer can play randomly, by randomly selecting a
* row and column to play .
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfanjandavid
In Java using Eclipse, I\'m suppose to write a class that encapsulates a tic tac toe board using two
dimensional arrays. It should only involve the human player vs. the computer, and should
randomly select who should use \'X\' or \'O\' and whether the human player or the computer
should go first. Verify that all moves by the human player are to a valid space on the tic-tac-toe
board, and an incorrect choice should not halt or terminate the game. Below is my Java program
that is currently a work in progress. Can you help me remodify it? Thanks.
import java.util.Scanner;
public class LeavinesTicTacToe
{
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
final int SIZE = 3;
char[][] board = new char[SIZE][SIZE]; // game board
resetBoard(board); // initialize the board (with \' \' for all cells)
// First, welcome message and display the board.
System.out.println(\"===== WELCOME TO THE TIC-TAC-TOE GAME!! =====\ \");
showBoard(board);
// Then ask the user which symbol (x or o) he/she wants to play.
System.out.print(\" Which symbol do you want to play, \\\"x\\\" or \\\"o\\\"? \");
char userSymbol = sc.next().toLowerCase().charAt(0);
char compSymbol = (userSymbol == \'x\') ? \'o\' : \'x\';
// Also ask whether or not the user wants to go first.
System.out.println();
System.out.print(\" Do you want to go first (y/n)? \");
char ans = sc.next().toLowerCase().charAt(0);
int turn; // 0 -- the user, 1 -- the computer
int remainCount = SIZE * SIZE; // empty cell count
// THE VERY FIRST MOVE.
if (ans == \'y\') {
turn = 0;
userPlay(board, userSymbol); // user puts his/her first tic
}
else {
turn = 1;
compPlay(board, compSymbol); // computer puts its first tic
}
// Show the board, and decrement the count of remaining cells.
showBoard(board);
remainCount--;
// Play the game until either one wins.
boolean done = false;
int winner = -1; // 0 -- the user, 1 -- the computer, -1 -- draw
while (!done && remainCount > 0) {
// If there is a winner at this time, set the winner and the done flag to true.
done = isGameWon(board, turn, userSymbol, compSymbol); // Did the turn won?
if (done)
winner = turn; // the one who made the last move won the game
else {
// No winner yet. Find the next turn and play.
turn = (turn + 1 ) % 2;
if (turn == 0)
userPlay(board, userSymbol);
else
compPlay(board, compSymbol);
// Show the board after one tic, and decrement the rem count.
showBoard(board);
remainCount--;
}
}
// Winner is found. Declare the winner.
if (winner == 0)
System.out.println(\"\ ** YOU WON. CONGRATULATIONS!! **\");
else if (winner == 1)
System.out.println(\"\ ** YOU LOST.. Maybe next time :) **\");
else
System.out.println(\"\ ** DRAW... **\");
}
public static void resetBoard(char[][] brd)
{
for (int i = 0; i < brd.length; i++)
for (int j = 0; j < brd[0].length; j++)
brd[i][j] = \' \';
}
public static void showBoard(char[][] brd)
{
int numRow = brd.length;
int numCol = brd[0].length;
System.out.println();
// First write the column he.
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdfflashfashioncasualwe
Need to make a Reversi/Othello Board game in JAVA
The board size can be N x N (so 4x4 is default, and it could be larger like 5x5, 6x6 etc. NEEDS
TO BE ABLE TO WORK WITH ODD SIZE)
Player 1 is going to be you and your going to be the black tiles, and the AI is going to be the
white tiles. Black tiles will start the game, and then white will go after them, then back to black,
repeat. The players must put a disc of their color on an empty square, adjacent to their
opponent\'s disc. Any of the oppponents tiles in between the tile put down, and another of your
tiles will cause them to flip to your color. The winner is decided when the board is completely
filled or no viable moves are left, and whoever has the most pieces.
This program is meant to be simple design (no GUI or big interface designs), broken into
multiple classes (can be extension\'s off the class or abstract interface off each other), and the
user will be entering the coordinates of where to put the pieces (so just using scanner method)?.
The start of the game must always have 4 tiles put down in the center (so the center can change
depending on the size of the board), and the gameplay would look something like this
Again, coding done in JAVA is what I\'m looking for.
Scenario in which the game ends early.
JAVA code BW Success: Black move at C1, 0) BW Score: Black: 4, White: 1 Success: White
move at C2, 0D
Solution
package Reversi_Othello_GameReversiOthello;
import java.awt.*;
import java.applet.*;
public class Reversi_Othello_GameReversiOthello extends Applet implements Runnable {
Thread runner; // declare a thread for this GameReversiOthello
boolean black_shown = false; // flag to signal pause
boolean show_em = false;
final int BLACK = 1; // declare state of each square
final int WHITE = 2;
final int EMPTY = 0;
final int OFFBOARD = -1;
final static int GameReversiOthello[][] = new int[10][10]; //10x10 matrix of squares
protected int Count_Black = 0;
protected int Count_White = 0;
Event evt;
int x, y;
public void start() // create a thread and start it
{
if (runner == null) {
black_shown = false;
runner = new Thread(this);
runner.start();
}
}
public void stop() // stop the thread
{
if (runner != null) {
runner.stop();
runner = null;
black_shown = false;
}
}
public synchronized void run() // initialize screen
{
setBackground(Color.green);
for (int i = 0; i < 10; i++) // initialize off-board squares
{
GameReversiOthello[i][0] = OFFBOARD;
GameReversiOthello[i][9] = OFFBOARD;
GameReversiOthello[0][i] = OFFBOARD;
GameReversiOthello[9][i] = OFFBOARD;
}
for (int i = 1; i < 9; i++) // initialize GameReversiOthello board to be empty
{
for (int j = 1; j < 9; j++) {
GameReversiOthello[i][j] = EMPTY;
}
}
GameReversiOthello[4][4] = WHITE; // except for initial set up
GameReversiOthello[5][4] = BLACK;
GameReversiOthello[4][5] = BLACK;
GameReversiOthello[5][5] = WHITE;
while (runner != null) // signal thread to wait after painting
{ // black and before white responds
while (!black_shown) {
try {
w.
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfrajkumarm401
Objective:
Create a graphical game of minesweeper IN JAVA. The board should consist of 10x10 buttons.
Of the 100 spaces there should be at least 20 randomly placed mines. If the button is clicked and
it is not a mine then it clears itself. If a space has been cleared then it should indicate how many
of its eight neighbors are mines. If a space is clicked and it is a mine then the game is over and
the player is asked if they want to play again. Finally, if all the non-mine spaces have been
clicked then the player is prompted that they won.
Solution
2 files need to be made.
First Game.Java which will have the gaming logic and User Interface and Main.Java which will
have have the main method and object of Game.java Number of rows and cols is customizable so
user can change that as and when needed.
import java.awt.*;
import java.awt.Dimension;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Game extends JFrame implements ActionListener, ContainerListener {
int fw, fh, blockr, blockc, var1, var2, num_of_mine, detectedmine = 0, savedlevel = 1,
savedblockr, savedblockc, savednum_of_mine = 10;
int[] r = {-1, -1, -1, 0, 1, 1, 1, 0};
int[] c = {-1, 0, 1, 1, 1, 0, -1, -1};
JButton[][] blocks;
int[][] countmine;
int[][] colour;
ImageIcon[] ic = new ImageIcon[14];
JPanel panelb = new JPanel();
JPanel panelmt = new JPanel();
JTextField tf_mine, tf_time;
JButton reset = new JButton(\"\");
Random ranr = new Random();
Random ranc = new Random();
boolean check = true, starttime = false;
Point framelocation;
Stopwatch sw;
MouseHendeler mh;
Point p;
Game() {
super(\"Game\");
setLocation(400, 300);
setic();
setpanel(1, 0, 0, 0);
setmanue();
sw = new Stopwatch();
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
sw.stop();
setpanel(savedlevel, savedblockr, savedblockc, savednum_of_mine);
} catch (Exception ex) {
setpanel(savedlevel, savedblockr, savedblockc, savednum_of_mine);
}
reset();
}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
show();
}
public void reset() {
check = true;
starttime = false;
for (int i = 0; i < blockr; i++) {
for (int j = 0; j < blockc; j++) {
colour[i][j] = \'w\';
}
}
}
public void setpanel(int level, int setr, int setc, int setm) {
if (level == 1) {
fw = 200;
fh = 300;
blockr = 10;
blockc = 10;
num_of_mine = 10;
} else if (level == 2) {
fw = 320;
fh = 416;
blockr = 16;
blockc = 16;
num_of_mine = 70;
} else if (level == 3) {
fw = 400;
fh = 520;
blockr = 20;
blockc = 20;
num_of_mine = 150;
} else if (level == 4) {
fw = (20 * setc);
fh = (24 * setr);
blockr = setr;
blockc = setc;
num_of_mine = setm;
}
savedblockr = blockr;
savedblockc = blockc;
savednum_of_mine = num_of_mine;
setSize(fw, fh);
setResizable(false);
detectedmine = num_of_mine;
p = this.getLocation();
blocks = new JButton[blockr][blockc];
countmine = new int[blockr][blockc];
colour = new int[blockr][blockc];
mh = new MouseHendeler();
getContentPane().removeAll();
panelb.removeAll();
tf_mine = new JTe.
Hello!This is Java assignment applet.Can someone help me writing.pdfjyothimuppasani1
Hello!
This is Java assignment applet.
Can someone help me writing a code how to exit the game when I press no in question( would
you like to play again?). Also if no one wins or draws i would like to pop up the question ( would
you like to play again?). I have the code below i would like someone to add it
Thanks in advance!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TicTacToe extends Applet implements ActionListener{
// Array to store buttons
JButton button[][] = new JButton[3][3];
boolean isNewGame =false;
// To switch player either X or O
boolean isZero = true; //first turn is always 0
// Setup size
// Set layout to grid
// Create buttons through loop
// Add buttons to layout
// Add listener
public void init(){
setSize(500, 500);
setLayout(new GridLayout(3,3));
// if it is not a new game
if(isNewGame==false) {
// Adding buttons to layout
//initialize the Grid and add ActionListener to each Button
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
// init jButton
button[i][j] = new JButton(\"\");
// Setup Font and Size here
button[i][j].setFont(new Font(\"Lucida Grande\", Font.PLAIN, 28));
// Add is a method from applet to add buttons in layout
add(button[i][j]);
// Listener
button[i][j].addActionListener(this);
}
}
}
else {
// If we need to restart the game, then we only set text to empty
// Back to black color
// add listener
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
button[i][j].setText(\"\");
button[i][j].setForeground(Color.BLACK);
button[i][j].removeActionListener(this);
button[i][j].addActionListener(this);
}
}
}
}
// Go all the buttons in arrsy
// Check the event with button in array
// if player O is true, set button text O. Otherwise. X
// Remove Listerner. Why? only once you can click
// Change player by isZero
// Check for winner
public void actionPerformed(ActionEvent event){
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++){
if((event.getSource() == button[i][j])){
if(isZero){
button[i][j].setText(\"O\");
}
else{
button[i][j].setText(\"X\");
}
button[i][j].removeActionListener(this); //you cannot click on one tile more than
once
isZero = !isZero;
checkForWinners(); //check if any winner after each move
}
}
}
public void checkForWinners(){
//3 horizontal lines
for(int i = 0; i < 3; i++){
if(button[i][0].getText().equals(button[i][1].getText())
&& button[i][1].getText().equals(button[i][2].getText())
&& !button[i][0].getText().equals(\"\")){
String player = button[i][0].getText();
button[i][0].setForeground(Color.RED);
button[i][1].setForeground(Color.RED);
button[i][2].setForeground(Color.RED);
int reply =JOptionPane.showConfirmDialog(null, player + \" wins!\"+\"\ Would like
to play again?\",\"Game over\",JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
isNewGame = true;
init();
return;
}
else {
System.exit(0);
return;
}
}
}
//3 vertical lines
for(int i = 0; i < 3; i++){
if(button[0][i].getText().equals(button[1][i].getText())
&& .
Need help writing the code for a basic java tic tac toe game Tic.pdfhainesburchett26321
Need help writing the code for a basic java tic tac toe game
// Tic-Tac-Toe: Complete the FIX-ME\'s to have a working version of Tic-Tac-Toe.
// Note: the basis of the game is a two-dimensional \'board\' array, with 3 rows
// and 3 columns. A value of +1 indicates an \'X\' on the board; and a value of
// -1 indicates an \'O\'
// Group Member names:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.*;
public class TicTacToe implements ActionListener{
// FIX ME #5: set CPU_PAUSE to true when ready to play
final boolean CPU_PAUSE = true; // does the CPU pause to think?
JButton [][] buttons = new JButton[3][3];
int [][] board = new int[3][3];
JLabel status = new JLabel(\"Player\'s turn\", JLabel.CENTER);
JFrame frame = new JFrame();
JPanel buttonPanel = new JPanel();
JPanel labelPanel = new JPanel();
Timer timer = null;
// draw X or O depending on \'x\' values
void refresh(int [][] x) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (x[i][j] == 1) {
buttons[i][j].setForeground(Color.blue);
buttons[i][j].setText(\"X\");
} else if (x[i][j] == -1) {
buttons[i][j].setForeground(Color.pink);
buttons[i][j].setText(\"O\");
} else {
buttons[i][j].setText(\" \");
}
}
}
}
boolean have_winner(int checkVal) {
boolean winner = false;
// FIX ME #1: if there are three \'checkVal\' values in-a-row across,
// then set \'winner\' to true
// FIX ME #2: if there are three \'checkVal\' values in-a-row vertically,
// then set \'winner\' to true
int checkSum = 0;
if (checkSum == 3 * checkVal){
winner = true;
}
// FIX ME #3: if there are three \'checkVal\' values in-a-row diagonally,
// then set \'winner\' to true
return winner;
}
boolean playerMove(ActionEvent e) {
JButton btn = (JButton) e.getSource();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (btn.equals(buttons[i][j])) {
if (board[i][j] != 0) {
return false;
}
board[i][j] = 1;
refresh(board);
return true;
}
}
}
return false;
}
boolean board_is_full() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == 0) return false;
}
}
return true;
}
ActionListener refreshListener = new ActionListener(){
int delayCount = 0;
public void actionPerformed(ActionEvent event){
delayCount++;
if (delayCount > 5) {
delayCount = 0;
timer.stop();
enableButtons(false);
}
if (delayCount % 2 == 0) {
refresh(board);
} else {
int [][] x = new int[3][3];
refresh(x);
}
}
};
void enableButtons(boolean enable) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setEnabled(enable);
}
}
}
ActionListener computerMove = new ActionListener(){
public void actionPerformed(ActionEvent event){
/* FIX ME #4: The computer moves by placing an \'O\' on the board
* (i.e.), assigning a -1 to a valid element of the board array
* The computer can play randomly, by randomly selecting a
* row and column to play .
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfudit652068
Working with Layout Managers. Notes: 1. In part 2, note that the Game class inherits from
JPanel. Therefore, the panel you are asked to add to the center of the content pane is the \"game\"
object. 2. In part 4, at the end of the function, call validate(). This is not mentioned in the book,
but it is mentioned in the framework comments.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JPanel
{
private JButton [][] squares;
private TilePuzzle game;
public Game( int newSide )
{
game = new TilePuzzle( newSide );
setUpGameGUI( );
}
public void setUpGame( int newSide )
{
game.setUpGame( newSide );
setUpGameGUI( );
}
public void setUpGameGUI( )
{
removeAll( ); // remove all components
setLayout( new GridLayout( game.getSide( ),
game.getSide( ) ) );
squares = new JButton[game.getSide( )][game.getSide( )];
ButtonHandler bh = new ButtonHandler( );
// for each button: generate button label,
// instantiate button, add to container,
// and register listener
for ( int i = 0; i < game.getSide( ); i++ )
{
for ( int j = 0; j < game.getSide( ); j++ )
{
squares[i][j] = new JButton( game.getTiles( )[i][j] );
add( squares[i][j] );
squares[i][j].addActionListener( bh );
}
}
setSize( 300, 300 );
setVisible( true );
}
private void update( int row, int col )
{
for ( int i = 0; i < game.getSide( ); i++ )
{
for ( int j = 0; j < game.getSide( ); j++ )
{
squares[i][j].setText( game.getTiles( )[i][j] );
}
}
if ( game.won( ) )
{
JOptionPane.showMessageDialog( Game.this,
\"Congratulations! You won!\ Setting up new game\" );
// int sideOfPuzzle = 3 + (int) ( 4 * Math.random( ) );
// setUpGameGUI( );
}
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed( ActionEvent ae )
{
for( int i = 0; i < game.getSide( ); i++ )
{
for( int j = 0; j < game.getSide( ); j++ )
{
if ( ae.getSource( ) == squares[i][j] )
{
if ( game.tryToPlay( i, j ) )
update( i, j );
return;
} // end if
} // end inner for loop
} // outer for loop
} // end actionPerformed method
} // end ButtonHandler class
} // end Game class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NestedLayoutPractice extends JFrame
{
private Container contents;
private Game game;
private BorderLayout bl;
private JLabel bottom;
// ***** Task 1: declare a JPanel named top
// also declare three JButton instance variables
// that will be added to the JPanel top
// these buttons will determine the grid size of the game:
// 3-by-3, 4-by-4, or 5-by-5
// Part 1 student code starts here:
// Part 1 student code ends here.
public NestedLayoutPractice()
{
super(\"Practicing layout managers\");
contents = getContentPane();
// ***** Task 2:
// instantiate the BorderLayout manager bl
// Part 2 student code starts here:
// set the layout manager of the content pane contents to bl:
game = new Game(3); // instantiating the GamePanel object
// add panel (game) to the center of the content pane
// Part 2 student code ends here.
bottom = new JLabel(.
I dont know what is wrong with this roulette program I cant seem.pdfarchanaemporium
I don\'t know what is wrong with this roulette program I can\'t seem to get it to run.
Game Class:
public class Game {
public static void main(String[] args) {
Table table = new Table();
BinBuilder bb = new BinBuilder();
Outcome black = new Outcome(\"Black\", 35);
Bet bet = new Bet(10, black);
table.placeBet(bet);
Bin bin = bb.wheel.get(8);
System.out.println(bin.toString());
System.out.println(table.bets.toString());
System.out.println(black.toString());
ListIterator i = table.bets.listIterator();
Iterator b = bin.outcomes.iterator();
while(i.hasNext()) {
System.out.println(i.next().outcome.name.toString());
while(b.hasNext()){
System.out.println(b.next().name.toString());
if(i.next().outcome.equals(b.next())){
System.out.println(\"Win!\");
}
else{
System.out.println(\"Win :/\");
}
}
}
}
}
Player Class
public class Player {
public Table table;
public Outcome black;
public Bet bet;
public Player(Table table) {
table = new Table();
black = new Outcome(\"Black\", 1);
}
void placeBets() {
Bet bet = new Bet(100, black);
table.placeBet(bet);
}
void win(Bet bet) {
System.out.println(\"You\'ve won: \" + bet.winAmount());
}
void lose(Bet bet) {
System.out.println(\"You lost!\" + bet.loseAmount() + \":/\");
}
}
Outcome class
public class Outcome implements Comparable {
public String name;
public int odds;
public Outcome(String name, int odds){
this.name = name;
this.odds = odds;
}
public int winAmount(int amount){
return amount*this.odds;
}
public boolean equals(Outcome other){
return (this.name.equals(other.name));
}
public String toString() {
Object[] values= { name, new Integer(odds) };
String msgTempl= \"{0} ({1}:1)\";
return MessageFormat.format( msgTempl, values );
}
@Override
public int compareTo(E arg0) {
if(this.equals(arg0)){
return 0;
}
return 1;
}
}
Table Class
public class Table {
public int limit = 1000;
public LinkedList bets;
public Table() {
bets = new LinkedList();
}
public boolean isValid(Bet bet) {
int sum = 0;
for(Bet bett: bets) {
sum += bett.amountBet;
}
return (sum>limit);
}
public void placeBet(Bet bet) {
bets.add(bet);
}
ListIterator iterator() {
return bets.listIterator();
}
}
Wheel Class
public class Wheel extends TreeSet {
Vector bins;
NonRandom rng;
Set all_outcomes;
Wheel(NonRandom rng){
this.rng = rng;
rng = new NonRandom();
all_outcomes = new TreeSet();
bins = new Vector(38);
for (int i=0; i<38; i++){
bins.add(i, new Bin());
}
}
Bin next(){
int rand = rng.next(38);
return bins.elementAt(rand);
}
Bin get(int bin){
return bins.elementAt(bin);
}
public Outcome getOutcome( String name ){
TreeSet result= new TreeSet();
for( Iterator i = all_outcomes.iterator(); i.hasNext(); ) {
Outcome oc= i.next();
if( oc.name.contains(name) ) {result.add( oc );}
}
return result.first();
}
public void addOutcome(int bin, Outcome outcome) {
all_outcomes.add(outcome);
this.bins.elementAt(bin).add(outcome);
}
}
Bet Class
public class Bet {
public int amountBet;
public Outcome outcome;
public Bet(int amount, Outcome outcome) {
this.outcome = o.
Here is the code for youimport java.util.Scanner; import java.u.pdfanithareadymade
Here is the code for you:
import java.util.Scanner;
import java.util.Random;
public class TicTacToeGame {
static char[] [] board = new char[3][3];
static Scanner input=new Scanner(System.in);
//Object of Stats class to maintain statistics
static Stats stat = new Stats();
/**
* Prints the TicTacToe board
* @param arr: The board so far
*/
public static void printBoard(char [][] arr){
System.out.println();
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
System.out.print(arr[i][j]);
if(j!=2)
//Print the | for readable output
System.out.print(\" \" + \"|\" + \" \");
}
System.out.println();
if(i!=2) {
System.out.print(\"_ _ _ \"); // Print _ for readability
System.out.println();;
}
}
}
/**
* Clear the TicTacToe board before starting a new game
* @param arr: The board so far
*/
public static void clearBoard(char [][] arr){
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
arr[i][j]=\' \';
}
}
}
/** Determines if the player with the specified token wins
*
* @param symbol: Specifies whether the player is X or O
* @return true if player has won, false otherwise
*/
public static boolean isWon(char symbol) {
for (int i = 0; i < 3; i++) //horizontal
if (board[i][0] == symbol
&& board[i][1] == symbol
&& board[i][2] == symbol) {
return true;
}
//TODO!!! Also check for vertical and the two diagonals
for (int i = 0; i < 3; i++) //vertical
if (board[0][i] == symbol
&& board[1][i] == symbol
&& board[2][i] == symbol) {
return true;
}
//Leading diagonal
if (board[0][0] == symbol
&& board[1][1] == symbol
&& board[2][2] == symbol) {
return true;
}
//Trailing diagonal
if (board[0][2] == symbol
&& board[1][1] == symbol
&& board[2][0] == symbol) {
return true;
}
return false;
}
/** Determines if the cell is occupied
*
* @param row: Row of the cell to be checked
* @param col: Column of the cell to be checked
* @return true if the cell is occupied, false otherwise
*/
public static boolean isOccupied(int row, int col){
if (board[row][col]!=\' \') return false;
else return true;
}
/** Determines who starts the game
*/
public static int whoStarts(){
//TODO: Randomly chooses between 0 and 1 and returns the choice
return (int)(Math.random() + 0.5 );
}
/** takes care of the human\'s move
* 1. Prompt for a cell, then column
* 2. Puts a symbol (X or O) on the board
* 3. Prints the updated board
* 4. If a human wins: prints, updates stats and returns true
* 5. If not a win yet, returns false */
public static boolean humanTurn(char symbol){
//Prompt for a cell. User must enter
//row and column with a space in between.
System.out.print(\"\ \ Enter your move: (row column): \" );
int row = input.nextInt();
int col = input.nextInt();
//TODO!!! Mark user move in the board, print
//the board and check if user has won!
board[row][col] = symbol;
printBoard(board);
if(isWon(symbol))
return true;
return false;
}
/** takes care of the computer\'s move
* 1. Generates numbers until finds an empty cell
* 2. Puts a symbol (X or O) on the board
* 3. Prints the updated board
* 4. If a comp .
i need a taking turn method for a player vs computer battleship game.pdfpetercoiffeur18
i need a taking turn method for a player vs computer battleship game in java. when a user slects
on players board then computer should be able to pick one on the computer board. this should
continue to repeat the order until the first one finds all the ship on their board first.
Solution
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*;
import java.io.*; import java.lang.Integer; import java.util.Vector; import java.net.*; public class
Battleship extends JFrame { private static JButton ok = new
JButton(\"OK\"),//closes stats menu done =new
JButton(\"Done\");//closes options menu private static JFrame statistics= new
JFrame(\"Statistics\"),//holds stats options=new
JFrame(\"Options\");//holds opts private static JLabel data,//used for stats menu
title;//used for options menu private static JPanel stats=new
JPanel(),//used for stats menu opts,//used for options menu
inputpanel;//for manually inputting ships private static Container
b,c,d;//board and input panel private JPanel input;//input bar private static
JMenuItem m,pvp,pvc,cvc;//menu items private static String[] cletters = {\"
\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\"}, //array of letters used for combo
boxes cnumbers = {\"
\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\"}, //array of numbers used for
combo boxes ships =
{\"Carrier\",\"Battleship\",\"Submarine\",\"Destroyer\", \"Patrol
Boat\"},//strings used for ship combo box direction =
{\"Horizontal\",\"Vertical\"},//directions level={\"Normal\",
\"Ridiculously Hard\"}, layout={\"Manual\",\"Automatic\"},
colors={\"Cyan\", \"Green\", \"Yellow\", \"Magenta\", \"Pink\", \"Red\",
\"White\"}, first={\"Player 1\", \"Player 2\",
\"Random\"};//used for options private JComboBox cshi = new JComboBox(ships),//ships
cdir = new JComboBox(direction);//directions private static
JComboBox aiLevel=new JComboBox(level), shipLayout=new
JComboBox(layout), shipColor=new JComboBox(colors),
playsFirst=new JComboBox(first);//used
//for options menu private JTextField mbar = new JTextField();//message bar
private static int enemy=1, i,j,//counters
length=5, you=0,
prevcolor=0,//index of previous color prevFirst=0,
prevLayout=0, prevLevel=0,//tracks changes in corresponding comboboxes
ready=0, sindex=0,//stores index of array
dindex=0;//direction private static Player players[]=new Player[2]; private static
JButton deploy=new JButton(\"DEPLOY\"); private static int
w=0,a=0,s=0,t=0,e=0;//counters to track the use of all ships private static String[][]
shiphit=new String[10][10]; private static String user,user2; private static Color[]
color={Color.cyan,Color.green,Color.yellow,Color.magenta,
Color.pink, Color.red, Color.white}; private static Object
selectedValue=\" \", gametype; private static
BattleshipClient me; private static boolean gameover=false; public Battleship()
{ setTitle(\"Battleship\");
setDefaultCloseOperation(EXIT_ON_CLOSE); setJMenuBar(createMenuBar());
setResizabl.
An introduction to making browser based games in JavaScript and HTML5.
This workshop was presented at an open day for the Academy of Interactive Entertainment in Sydney, Australia on November 17, 2012.
Java ProgrammingImplement an auction application with the followin.pdfatulkapoor33
Java Programming
Implement an auction application with the following features/functionality:
Inputs for an item and minimum bid amount.
Inputs for bidder name, bid amount and maximum bid. You will implement a class called Bid to
hold this information.
Label controls to show the current high bidder’s name, bid amount and maximum bid. For bid
amounts, you may assume all bids will be a whole dollar value just to simplify things a bit.
A list box to show all entries when the auction is over. You will use the pop() method to retrieve
each bid off the stack and display it. This feature is intended more for test/debug purposes.
You will implement a Stack class that will keep the highest bid at the top of the stack. It must
have the classic stack operations of push() to place an item on the stack, pop() to remove the top
item from the stack, and top() to view the top item on the stack but not remove it. You may use a
linked list of your own design, an array, or the built-in Java Array List or Linked List classes as
the underlying data structure. You may also add an item count property if you want.
The auction will work by the following rules:
When the initial bid is made, it must be greater than or equal to the item’s minimum bid amount
to be placed on the stack.
When another bid is made that is greater than the current high bidder’s maximum bid, that bid
will be pushed to the top of the stack and become the new highest bid.
If another bid is made that is greater than the current high bid but less than or equal to the
current high bidder’s maximum amount, the current high bidder’s bid will be raised to match but
the new bid will not be placed on the stack.
Your application should have a message box or label to indicate the status of the bid operation.
There is no limit on the number of bids.
Solution
// To import features as \'Panel, Button, Label, TextArea, TextField, Color\', etc.
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
// In this program, \"this.\" is used instead of \"this.getContentPane().\" in Auction.init() uses;
class Bidacution
{
public static void main (String[] args)
{ Frame gameapp = new Frame (\"AUCTION by Henry C. Joy\");
gameapp.setSize (750, 560); // larger than actual applet -- allow for edges
gameapp.addWindowListener (new WindowCloser());
Auction display = new Auction();
display.init();
gameapp.add (display);
gameapp.setVisible (true);
}
private static class WindowCloser extends java.awt.event.WindowAdapter
{ public void windowClosing (java.awt.event.WindowEvent e)
{ System.exit (0);
}}
}
// The MAIN method of the software (the init method): using 20 + classes.
public class Auction extends java.applet.Applet // every Applet is a Panel
{
public static final int UNIT = 5; // difference between 2 consec. bids
public static final int BREAK = 5; // separate first 5 from last 4
public static final String REPEAT = \"repeat game\";
// VIEW objects
private Panel boardPanel = new Panel();
p.
The following code, is a one player battleship game in JAVA. Im tryi.pdffonecomp
The following code, is a one player battleship game in JAVA. Im trying to Enhance the game to
be a two player game (were a player plays aggainst a computer opponent). With TWO boards
displayed side by side. The player and the computer must take turns selecting the coordinates on
their own boards. (the ships cannot be placed adjacent to each other).
BattleShipGame.java
package battleship;
import java.util.ArrayList;
import java.util.Scanner;
public class BattleshipGame {
private Ocean ocean;
private boolean[][] availableSpot;
private Scanner sc;
public BattleshipGame() {
// define a new ocean and a new 2D array to store available coordinates
ocean = new Ocean();
availableSpot = new boolean[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++){
availableSpot[i][j] = true;
}
}
}
/**
* prints the game menu and info
* //param select
*/
public void print(int select){
String info;
switch (select) {
case 1: info = \"Welcome to the World of Battleship!\";
break;
case 2: info = \"Enter coordinates to fire: \";
break;
case 3: info = \"Shots fired: \"+ocean.getShotsFired()+\", Ships sunk:
\"+ocean.getShipsSunk();
break;
case 4: info = \"Congratulations! You win!\";
break;
case 99: info = \"Invalid input. Please re-enter:\";
break;
case 100: info = \"--------------------------------------------\";
break;
case 101: info = \"\ ============================================\";
break;
default: info = \"Error selection\";
break;
}
System.out.println(info);
}
/**
* check if the input is valid
* //param input
* //return boolean
*/
public boolean checkValidInput(String input){
ArrayList numList = new ArrayList();
for (int i=0;i<10;i++){
numList.add(\"\"+i);
}
String[] coordinates = input.split(\" \");
//returns false if there are not 2 strings
if (coordinates.length!=2){
return false;
}
//returns false if any of the strings is not a single digit number
for (String str: coordinates){
if (numList.contains(str)==false){
return false;
}
}
//returns false if the coordinates have already been shot at
int row = Integer.parseInt(coordinates[0]);
int column = Integer.parseInt(coordinates[1]);
if (this.availableSpot[row][column]==false){
return false;
}
return true;
}
/**
* get the coordinates to shoot at from the String input
* //param input
* //return int[] coordinates
*/
public int[] getCoordinates(String input){
int[] coordinates = new int[2];
String[] strList = input.split(\" \");
int row = Integer.parseInt(strList[0]);
int column = Integer.parseInt(strList[1]);
coordinates[0] = row;
coordinates[1] = column;
return coordinates;
}
/**
* play the battleship game
*/
public void play(){
print(101);
print(1);
ocean.placeAllShipsRandomly();
boolean isGameOver = ocean.isGameOver();
sc = new Scanner(System.in);
//print the ocean and start the game
ocean.print();
print(3);
while (!isGameOver){
print(2);
String input = sc.nextLine();
//check if input is valid
while (!checkValidInput(input)){
print(99);
input = sc.nextLine();
}
//get coordinates and fire
int[] coord.
public interface Game Note interface in place of class { .pdfkavithaarp
public interface Game // Note *interface* in place of *class*
{
/// play the game and return the final score
/// where a higher score should be better,
/// and a negative score is allowed.
int play(); // Note semicolon in place of a body
// You can have multiple method headings declared
}
--------------------------------------------------------------------------------------------------------------
import java.util.*;
/// Starting point for Interface Lab.
public class PlayGames
{
private static Scanner in;
private static Random rand = new Random();
private static int gameCount = 0;
public static Game popRandom(Game[] g)
{
int n = gameCount;
int i = rand.nextInt(n);
Game ret = g[i];
g[i] = g[n-1];
gameCount--;
return ret;
}
public static void main(String[] args)
{
Game[] games = new Game[10]; // Note Game as a type
games[gameCount] = new AdditionGame(rand, 100);
gameCount++; // next index to put a Game at
// write at least 2 more different types of Game classes
// and add a new one of each type to games
// ...
in = new Scanner(System.in);
int totScore = 0;
do {
Game g = popRandom(games);
totScore += g.play(); // use numerical result from the game
} while (gameCount > 0 && agree(\"Want a game? \"));
System.out.println(\"Thanks for Playing!\");
System.out.println(\"Your total score is \" + totScore);
}
public static boolean agree(String prompt)
{
System.out.print(prompt);
String input = in.next();
if (input.equalsIgnoreCase(\"y\")) return true;
return false;
}
--------------------------------------------------------------------------------------------------------------------
--
import java.util.*;
public class AdditionGame implements Game // note implements!!
{
private Random rand;
private int n;
// Constructor for objects of class AdditionGame
public AdditionGame(Random r, int big)
{
rand = r;
n = big;
}
// play all games and keep score.
public int play() // exactly matches heading in Game interface
{
final int numGames = 3;
Scanner in = new Scanner(System.in);
int score = 0;
System.out.println(\"Welcome to the addition game! We\'ll now play \" + numGames
+ \" rounds.\");
for (int i = 0; i < numGames; i++) {
int x = rand.nextInt(n), y = rand.nextInt(n), ans = x+y;
System.out.print(String.format(\"Enter the sum: %d + %d = \", x, y));
int val = in.nextInt();
if (ans == val) {
System.out.println(\"Correct!\");
score++;
}
else
System.out.println(\"Wrong! Right answer is \" + ans);
}
System.out.println(\"Thanks for playing the addition game. Your score is \" + score +
\".\");
System.out.println();
return score;
}
}
--------------------------------------------------------------------------------------------------------------------
---
Create two classes that implement a Game interface:
------------------------------------
There is a Game interface defined, and also a PlayGames class that uses objects from classes that
implement that interface. The Game interface declares a single abstract method play that returns
an int, the score from playing the gam.
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdfinfomalad
Tic Tac Toe game with GUI written in java.
Solution
Answer:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TicTacToe extends JPanel
{
JButton buttons[] = new JButton[9];
int alternate = 0;//if this number is a even, then put a X. If it\'s odd, then put an O
public TicTacToe()
{
setLayout(new GridLayout(3,3));
initializebuttons();
}
public void initializebuttons()
{
for(int i = 0; i <= 8; i++)
{
buttons[i] = new JButton();
buttons[i].setText(\"\");
buttons[i].addActionListener(new buttonListener());
add(buttons[i]); //adds this button to JPanel (note: no need for JPanel.add(...)
//because this whole class is a JPanel already
}
}
public void resetButtons()
{
for(int i = 0; i <= 8; i++)
{
buttons[i].setText(\"\");
}
}
// when a button is clicked, it generates an ActionEvent. Thus, each button needs an
ActionListener. When it is clicked, it goes to this listener class that I have created and goes to the
actionPerformed method. There (and in this class), we decide what we want to do.
private class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton buttonClicked = (JButton)e.getSource(); //get the particular button that was clicked
if(alternate%2 == 0)
buttonClicked.setText(\"X\");
else
buttonClicked.setText(\"O\");
if(checkForWin() == true)
{
JOptionPane.showConfirmDialog(null, \"Game Over.\");
resetButtons();
}
alternate++;
}
public boolean checkForWin()
{
/** Reference: the button array is arranged like this as the board
* 0 | 1 | 2
* 3 | 4 | 5
* 6 | 7 | 8
*/
//horizontal win check
if( checkAdjacent(0,1) && checkAdjacent(1,2) ) //no need to put \" == true\" because the
default check is for true
return true;
else if( checkAdjacent(3,4) && checkAdjacent(4,5) )
return true;
else if ( checkAdjacent(6,7) && checkAdjacent(7,8))
return true;
//vertical win check
else if ( checkAdjacent(0,3) && checkAdjacent(3,6))
return true;
else if ( checkAdjacent(1,4) && checkAdjacent(4,7))
return true;
else if ( checkAdjacent(2,5) && checkAdjacent(5,8))
return true;
//diagonal win check
else if ( checkAdjacent(0,4) && checkAdjacent(4,8))
return true;
else if ( checkAdjacent(2,4) && checkAdjacent(4,6))
return true;
else
return false;
}
public boolean checkAdjacent(int a, int b)
{
if ( buttons[a].getText().equals(buttons[b].getText()) && !buttons[a].getText().equals(\"\") )
return true;
else
return false;
}
}
public static void main(String[] args)
{
JFrame window = new JFrame(\"Tic-Tac-Toe\");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(new TicTacToe());
window.setBounds(300,200,300,300);
window.setVisible(true);
}
}.
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxmary772
CodeZip/ButtonDemo.javaCodeZip/ButtonDemo.java// Demonstrate a push button and handle action events.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclassButtonDemoimplementsActionListener{
JLabel jlab;
JTextField jtf;
ButtonDemo(){
// Create a new JFrame container.
JFrame jfrm =newJFrame("A Button Example");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(newFlowLayout());
// Give the frame an initial size.
jfrm.setSize(220,90);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make two buttons.
JButton jbtnUp =newJButton("Up");
JButton jbtnDown =newJButton("Down");
// Create a text field.
jtf =newJTextField(10);
// Add action listeners.
jbtnUp.addActionListener(this);
jbtnDown.addActionListener(this);
// Add the buttons to the content pane.
jfrm.add(jbtnUp);
jfrm.add(jbtnDown);
jfrm.add(jtf);
// Create a label.
jlab =newJLabel("Press a button.");
// Add the label to the frame.
jfrm.add(jlab);
// Display the frame.
jfrm.setVisible(true);
}
// Handle button events.
publicvoid actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("Up")){
jlab.setText("You pressed Up.");
FileClock clock1=newFileClock(jtf);
Thread thread1=newThread(clock1);
thread1.start();
}
else
jlab.setText("You pressed down. ");
}
publicstaticvoid main(String args[]){
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(newRunnable(){
publicvoid run(){
newButtonDemo();
}
});
}
}
CodeZip/CBDemo.javaCodeZip/CBDemo.java// Demonstrate check boxes.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclassCBDemoimplementsItemListener{
JLabel jlabSelected;
JLabel jlabChanged;
JCheckBox jcbAlpha;
JCheckBox jcbBeta;
JCheckBox jcbGamma;
CBDemo(){
// Create a new JFrame container.
JFrame jfrm =newJFrame("Demonstrate Check Boxes");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(newFlowLayout());
// Give the frame an initial size.
jfrm.setSize(280,120);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create empty labels.
jlabSelected =newJLabel("");
jlabChanged =newJLabel("");
// Make check boxes.
jcbAlpha =newJCheckBox("Alpha");
jcbBeta =newJCheckBox("Beta");
jcbGamma =newJCheckBox("Gamma");
// Events generated by the check boxes
// are handled in common by the itemStateChanged()
// method implemented by CBDemo.
jcbAlpha.addItemListener(this);
jcbBeta.addItemListener(this);
jcbGamma.addItemListener(this);
// Add checkboxes and labels to the content pane.
jfrm.add(jcbAlpha);
jfrm.add(jcbBeta);
jfrm.add(jcbGamma);
jfrm.add(jlabChanged);
jfrm.add(jlabSelected);
// Display the frame.
jfrm.setVisible(true);
}
// This is the handler for the check boxes..
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxmccormicknadine86
CodeZip/ButtonDemo.javaCodeZip/ButtonDemo.java// Demonstrate a push button and handle action events.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclassButtonDemoimplementsActionListener{
JLabel jlab;
JTextField jtf;
ButtonDemo(){
// Create a new JFrame container.
JFrame jfrm =newJFrame("A Button Example");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(newFlowLayout());
// Give the frame an initial size.
jfrm.setSize(220,90);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make two buttons.
JButton jbtnUp =newJButton("Up");
JButton jbtnDown =newJButton("Down");
// Create a text field.
jtf =newJTextField(10);
// Add action listeners.
jbtnUp.addActionListener(this);
jbtnDown.addActionListener(this);
// Add the buttons to the content pane.
jfrm.add(jbtnUp);
jfrm.add(jbtnDown);
jfrm.add(jtf);
// Create a label.
jlab =newJLabel("Press a button.");
// Add the label to the frame.
jfrm.add(jlab);
// Display the frame.
jfrm.setVisible(true);
}
// Handle button events.
publicvoid actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("Up")){
jlab.setText("You pressed Up.");
FileClock clock1=newFileClock(jtf);
Thread thread1=newThread(clock1);
thread1.start();
}
else
jlab.setText("You pressed down. ");
}
publicstaticvoid main(String args[]){
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(newRunnable(){
publicvoid run(){
newButtonDemo();
}
});
}
}
CodeZip/CBDemo.javaCodeZip/CBDemo.java// Demonstrate check boxes.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclassCBDemoimplementsItemListener{
JLabel jlabSelected;
JLabel jlabChanged;
JCheckBox jcbAlpha;
JCheckBox jcbBeta;
JCheckBox jcbGamma;
CBDemo(){
// Create a new JFrame container.
JFrame jfrm =newJFrame("Demonstrate Check Boxes");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(newFlowLayout());
// Give the frame an initial size.
jfrm.setSize(280,120);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create empty labels.
jlabSelected =newJLabel("");
jlabChanged =newJLabel("");
// Make check boxes.
jcbAlpha =newJCheckBox("Alpha");
jcbBeta =newJCheckBox("Beta");
jcbGamma =newJCheckBox("Gamma");
// Events generated by the check boxes
// are handled in common by the itemStateChanged()
// method implemented by CBDemo.
jcbAlpha.addItemListener(this);
jcbBeta.addItemListener(this);
jcbGamma.addItemListener(this);
// Add checkboxes and labels to the content pane.
jfrm.add(jcbAlpha);
jfrm.add(jcbBeta);
jfrm.add(jcbGamma);
jfrm.add(jlabChanged);
jfrm.add(jlabSelected);
// Display the frame.
jfrm.setVisible(true);
}
// This is the handler for the check boxes. ...
1. VacuolesThe vacuole is an organelle in plant cells which stores.pdfaoneonlinestore1
1. Vacuoles
The vacuole is an organelle in plant cells which stores water and nutrients for the cell. It takes in
and release the water as per cell\'s requirement.
2. . In plasmolysed Elodea leaf the gap between the cell wall and the cell membrane is filled with
0.6M sucrose solution.
Solution
1. Vacuoles
The vacuole is an organelle in plant cells which stores water and nutrients for the cell. It takes in
and release the water as per cell\'s requirement.
2. . In plasmolysed Elodea leaf the gap between the cell wall and the cell membrane is filled with
0.6M sucrose solution..
1. B) - Two independent properties serve to specify the state.2. B.pdfaoneonlinestore1
1. B) - Two independent properties serve to specify the state.
2. B) - The locus of all points where the second law is satisfied.
3. B) - Is the p-T coordinates at which solid, liquid and vapour co-exist in equlibrium.
Solution
1. B) - Two independent properties serve to specify the state.
2. B) - The locus of all points where the second law is satisfied.
3. B) - Is the p-T coordinates at which solid, liquid and vapour co-exist in equlibrium..
(NH4)2SO4 is a soluble salt and is fully ionized in solution(NH4).pdfaoneonlinestore1
(NH4)2SO4 is a soluble salt and is fully ionized in solution:
(NH4)2SO4 => 2 NH4+ + SO42-
NH4+ is a weak acid and ionizes further: NH4+<=> NH3 + H+
The H+ formed can react with C2O42- to form the weak acid oxalic acid (H2C2O4):
C2O42- + 2 H+ <=> H2C2O4
Removal of C2O42- causes the equilibrium: ZnC2O4 <=> Zn2+ + C2O42-
to shift to the right according to Le Chatelier\'s principle and more ZnC2O4 dissolves.
Thus the solubility of ZnC2O4 increases in the presence of (NH4)2SO4.
Solution
(NH4)2SO4 is a soluble salt and is fully ionized in solution:
(NH4)2SO4 => 2 NH4+ + SO42-
NH4+ is a weak acid and ionizes further: NH4+<=> NH3 + H+
The H+ formed can react with C2O42- to form the weak acid oxalic acid (H2C2O4):
C2O42- + 2 H+ <=> H2C2O4
Removal of C2O42- causes the equilibrium: ZnC2O4 <=> Zn2+ + C2O42-
to shift to the right according to Le Chatelier\'s principle and more ZnC2O4 dissolves.
Thus the solubility of ZnC2O4 increases in the presence of (NH4)2SO4..
I have inserted spaces. Consider f(x) belonging to f(X) thi.pdfaoneonlinestore1
I have inserted spaces.
Consider f(x) belonging to f(X)
this means : x belongs to X
But X is a subset of Y
So, x belongs to Y
So, f(x) belongs to f(Y).
Hence all f(x) in f(X) belong to f(Y)
So, f(X) is a subset of f(Y)
Example: f(x) = sin(x) : R -> R
X = [0,2pi]
Y = [-2pi,2pi]
f(X) = [-1,1]
f(Y) = [-1,1]
So, f(X) = f(Y)
Solution
I have inserted spaces.
Consider f(x) belonging to f(X)
this means : x belongs to X
But X is a subset of Y
So, x belongs to Y
So, f(x) belongs to f(Y).
Hence all f(x) in f(X) belong to f(Y)
So, f(X) is a subset of f(Y)
Example: f(x) = sin(x) : R -> R
X = [0,2pi]
Y = [-2pi,2pi]
f(X) = [-1,1]
f(Y) = [-1,1]
So, f(X) = f(Y).
More Related Content
Similar to import java.awt.;import java.awt.event.;import javax.swing.;.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfudit652068
Working with Layout Managers. Notes: 1. In part 2, note that the Game class inherits from
JPanel. Therefore, the panel you are asked to add to the center of the content pane is the \"game\"
object. 2. In part 4, at the end of the function, call validate(). This is not mentioned in the book,
but it is mentioned in the framework comments.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JPanel
{
private JButton [][] squares;
private TilePuzzle game;
public Game( int newSide )
{
game = new TilePuzzle( newSide );
setUpGameGUI( );
}
public void setUpGame( int newSide )
{
game.setUpGame( newSide );
setUpGameGUI( );
}
public void setUpGameGUI( )
{
removeAll( ); // remove all components
setLayout( new GridLayout( game.getSide( ),
game.getSide( ) ) );
squares = new JButton[game.getSide( )][game.getSide( )];
ButtonHandler bh = new ButtonHandler( );
// for each button: generate button label,
// instantiate button, add to container,
// and register listener
for ( int i = 0; i < game.getSide( ); i++ )
{
for ( int j = 0; j < game.getSide( ); j++ )
{
squares[i][j] = new JButton( game.getTiles( )[i][j] );
add( squares[i][j] );
squares[i][j].addActionListener( bh );
}
}
setSize( 300, 300 );
setVisible( true );
}
private void update( int row, int col )
{
for ( int i = 0; i < game.getSide( ); i++ )
{
for ( int j = 0; j < game.getSide( ); j++ )
{
squares[i][j].setText( game.getTiles( )[i][j] );
}
}
if ( game.won( ) )
{
JOptionPane.showMessageDialog( Game.this,
\"Congratulations! You won!\ Setting up new game\" );
// int sideOfPuzzle = 3 + (int) ( 4 * Math.random( ) );
// setUpGameGUI( );
}
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed( ActionEvent ae )
{
for( int i = 0; i < game.getSide( ); i++ )
{
for( int j = 0; j < game.getSide( ); j++ )
{
if ( ae.getSource( ) == squares[i][j] )
{
if ( game.tryToPlay( i, j ) )
update( i, j );
return;
} // end if
} // end inner for loop
} // outer for loop
} // end actionPerformed method
} // end ButtonHandler class
} // end Game class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NestedLayoutPractice extends JFrame
{
private Container contents;
private Game game;
private BorderLayout bl;
private JLabel bottom;
// ***** Task 1: declare a JPanel named top
// also declare three JButton instance variables
// that will be added to the JPanel top
// these buttons will determine the grid size of the game:
// 3-by-3, 4-by-4, or 5-by-5
// Part 1 student code starts here:
// Part 1 student code ends here.
public NestedLayoutPractice()
{
super(\"Practicing layout managers\");
contents = getContentPane();
// ***** Task 2:
// instantiate the BorderLayout manager bl
// Part 2 student code starts here:
// set the layout manager of the content pane contents to bl:
game = new Game(3); // instantiating the GamePanel object
// add panel (game) to the center of the content pane
// Part 2 student code ends here.
bottom = new JLabel(.
I dont know what is wrong with this roulette program I cant seem.pdfarchanaemporium
I don\'t know what is wrong with this roulette program I can\'t seem to get it to run.
Game Class:
public class Game {
public static void main(String[] args) {
Table table = new Table();
BinBuilder bb = new BinBuilder();
Outcome black = new Outcome(\"Black\", 35);
Bet bet = new Bet(10, black);
table.placeBet(bet);
Bin bin = bb.wheel.get(8);
System.out.println(bin.toString());
System.out.println(table.bets.toString());
System.out.println(black.toString());
ListIterator i = table.bets.listIterator();
Iterator b = bin.outcomes.iterator();
while(i.hasNext()) {
System.out.println(i.next().outcome.name.toString());
while(b.hasNext()){
System.out.println(b.next().name.toString());
if(i.next().outcome.equals(b.next())){
System.out.println(\"Win!\");
}
else{
System.out.println(\"Win :/\");
}
}
}
}
}
Player Class
public class Player {
public Table table;
public Outcome black;
public Bet bet;
public Player(Table table) {
table = new Table();
black = new Outcome(\"Black\", 1);
}
void placeBets() {
Bet bet = new Bet(100, black);
table.placeBet(bet);
}
void win(Bet bet) {
System.out.println(\"You\'ve won: \" + bet.winAmount());
}
void lose(Bet bet) {
System.out.println(\"You lost!\" + bet.loseAmount() + \":/\");
}
}
Outcome class
public class Outcome implements Comparable {
public String name;
public int odds;
public Outcome(String name, int odds){
this.name = name;
this.odds = odds;
}
public int winAmount(int amount){
return amount*this.odds;
}
public boolean equals(Outcome other){
return (this.name.equals(other.name));
}
public String toString() {
Object[] values= { name, new Integer(odds) };
String msgTempl= \"{0} ({1}:1)\";
return MessageFormat.format( msgTempl, values );
}
@Override
public int compareTo(E arg0) {
if(this.equals(arg0)){
return 0;
}
return 1;
}
}
Table Class
public class Table {
public int limit = 1000;
public LinkedList bets;
public Table() {
bets = new LinkedList();
}
public boolean isValid(Bet bet) {
int sum = 0;
for(Bet bett: bets) {
sum += bett.amountBet;
}
return (sum>limit);
}
public void placeBet(Bet bet) {
bets.add(bet);
}
ListIterator iterator() {
return bets.listIterator();
}
}
Wheel Class
public class Wheel extends TreeSet {
Vector bins;
NonRandom rng;
Set all_outcomes;
Wheel(NonRandom rng){
this.rng = rng;
rng = new NonRandom();
all_outcomes = new TreeSet();
bins = new Vector(38);
for (int i=0; i<38; i++){
bins.add(i, new Bin());
}
}
Bin next(){
int rand = rng.next(38);
return bins.elementAt(rand);
}
Bin get(int bin){
return bins.elementAt(bin);
}
public Outcome getOutcome( String name ){
TreeSet result= new TreeSet();
for( Iterator i = all_outcomes.iterator(); i.hasNext(); ) {
Outcome oc= i.next();
if( oc.name.contains(name) ) {result.add( oc );}
}
return result.first();
}
public void addOutcome(int bin, Outcome outcome) {
all_outcomes.add(outcome);
this.bins.elementAt(bin).add(outcome);
}
}
Bet Class
public class Bet {
public int amountBet;
public Outcome outcome;
public Bet(int amount, Outcome outcome) {
this.outcome = o.
Here is the code for youimport java.util.Scanner; import java.u.pdfanithareadymade
Here is the code for you:
import java.util.Scanner;
import java.util.Random;
public class TicTacToeGame {
static char[] [] board = new char[3][3];
static Scanner input=new Scanner(System.in);
//Object of Stats class to maintain statistics
static Stats stat = new Stats();
/**
* Prints the TicTacToe board
* @param arr: The board so far
*/
public static void printBoard(char [][] arr){
System.out.println();
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
System.out.print(arr[i][j]);
if(j!=2)
//Print the | for readable output
System.out.print(\" \" + \"|\" + \" \");
}
System.out.println();
if(i!=2) {
System.out.print(\"_ _ _ \"); // Print _ for readability
System.out.println();;
}
}
}
/**
* Clear the TicTacToe board before starting a new game
* @param arr: The board so far
*/
public static void clearBoard(char [][] arr){
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
arr[i][j]=\' \';
}
}
}
/** Determines if the player with the specified token wins
*
* @param symbol: Specifies whether the player is X or O
* @return true if player has won, false otherwise
*/
public static boolean isWon(char symbol) {
for (int i = 0; i < 3; i++) //horizontal
if (board[i][0] == symbol
&& board[i][1] == symbol
&& board[i][2] == symbol) {
return true;
}
//TODO!!! Also check for vertical and the two diagonals
for (int i = 0; i < 3; i++) //vertical
if (board[0][i] == symbol
&& board[1][i] == symbol
&& board[2][i] == symbol) {
return true;
}
//Leading diagonal
if (board[0][0] == symbol
&& board[1][1] == symbol
&& board[2][2] == symbol) {
return true;
}
//Trailing diagonal
if (board[0][2] == symbol
&& board[1][1] == symbol
&& board[2][0] == symbol) {
return true;
}
return false;
}
/** Determines if the cell is occupied
*
* @param row: Row of the cell to be checked
* @param col: Column of the cell to be checked
* @return true if the cell is occupied, false otherwise
*/
public static boolean isOccupied(int row, int col){
if (board[row][col]!=\' \') return false;
else return true;
}
/** Determines who starts the game
*/
public static int whoStarts(){
//TODO: Randomly chooses between 0 and 1 and returns the choice
return (int)(Math.random() + 0.5 );
}
/** takes care of the human\'s move
* 1. Prompt for a cell, then column
* 2. Puts a symbol (X or O) on the board
* 3. Prints the updated board
* 4. If a human wins: prints, updates stats and returns true
* 5. If not a win yet, returns false */
public static boolean humanTurn(char symbol){
//Prompt for a cell. User must enter
//row and column with a space in between.
System.out.print(\"\ \ Enter your move: (row column): \" );
int row = input.nextInt();
int col = input.nextInt();
//TODO!!! Mark user move in the board, print
//the board and check if user has won!
board[row][col] = symbol;
printBoard(board);
if(isWon(symbol))
return true;
return false;
}
/** takes care of the computer\'s move
* 1. Generates numbers until finds an empty cell
* 2. Puts a symbol (X or O) on the board
* 3. Prints the updated board
* 4. If a comp .
i need a taking turn method for a player vs computer battleship game.pdfpetercoiffeur18
i need a taking turn method for a player vs computer battleship game in java. when a user slects
on players board then computer should be able to pick one on the computer board. this should
continue to repeat the order until the first one finds all the ship on their board first.
Solution
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*;
import java.io.*; import java.lang.Integer; import java.util.Vector; import java.net.*; public class
Battleship extends JFrame { private static JButton ok = new
JButton(\"OK\"),//closes stats menu done =new
JButton(\"Done\");//closes options menu private static JFrame statistics= new
JFrame(\"Statistics\"),//holds stats options=new
JFrame(\"Options\");//holds opts private static JLabel data,//used for stats menu
title;//used for options menu private static JPanel stats=new
JPanel(),//used for stats menu opts,//used for options menu
inputpanel;//for manually inputting ships private static Container
b,c,d;//board and input panel private JPanel input;//input bar private static
JMenuItem m,pvp,pvc,cvc;//menu items private static String[] cletters = {\"
\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\"}, //array of letters used for combo
boxes cnumbers = {\"
\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\"}, //array of numbers used for
combo boxes ships =
{\"Carrier\",\"Battleship\",\"Submarine\",\"Destroyer\", \"Patrol
Boat\"},//strings used for ship combo box direction =
{\"Horizontal\",\"Vertical\"},//directions level={\"Normal\",
\"Ridiculously Hard\"}, layout={\"Manual\",\"Automatic\"},
colors={\"Cyan\", \"Green\", \"Yellow\", \"Magenta\", \"Pink\", \"Red\",
\"White\"}, first={\"Player 1\", \"Player 2\",
\"Random\"};//used for options private JComboBox cshi = new JComboBox(ships),//ships
cdir = new JComboBox(direction);//directions private static
JComboBox aiLevel=new JComboBox(level), shipLayout=new
JComboBox(layout), shipColor=new JComboBox(colors),
playsFirst=new JComboBox(first);//used
//for options menu private JTextField mbar = new JTextField();//message bar
private static int enemy=1, i,j,//counters
length=5, you=0,
prevcolor=0,//index of previous color prevFirst=0,
prevLayout=0, prevLevel=0,//tracks changes in corresponding comboboxes
ready=0, sindex=0,//stores index of array
dindex=0;//direction private static Player players[]=new Player[2]; private static
JButton deploy=new JButton(\"DEPLOY\"); private static int
w=0,a=0,s=0,t=0,e=0;//counters to track the use of all ships private static String[][]
shiphit=new String[10][10]; private static String user,user2; private static Color[]
color={Color.cyan,Color.green,Color.yellow,Color.magenta,
Color.pink, Color.red, Color.white}; private static Object
selectedValue=\" \", gametype; private static
BattleshipClient me; private static boolean gameover=false; public Battleship()
{ setTitle(\"Battleship\");
setDefaultCloseOperation(EXIT_ON_CLOSE); setJMenuBar(createMenuBar());
setResizabl.
An introduction to making browser based games in JavaScript and HTML5.
This workshop was presented at an open day for the Academy of Interactive Entertainment in Sydney, Australia on November 17, 2012.
Java ProgrammingImplement an auction application with the followin.pdfatulkapoor33
Java Programming
Implement an auction application with the following features/functionality:
Inputs for an item and minimum bid amount.
Inputs for bidder name, bid amount and maximum bid. You will implement a class called Bid to
hold this information.
Label controls to show the current high bidder’s name, bid amount and maximum bid. For bid
amounts, you may assume all bids will be a whole dollar value just to simplify things a bit.
A list box to show all entries when the auction is over. You will use the pop() method to retrieve
each bid off the stack and display it. This feature is intended more for test/debug purposes.
You will implement a Stack class that will keep the highest bid at the top of the stack. It must
have the classic stack operations of push() to place an item on the stack, pop() to remove the top
item from the stack, and top() to view the top item on the stack but not remove it. You may use a
linked list of your own design, an array, or the built-in Java Array List or Linked List classes as
the underlying data structure. You may also add an item count property if you want.
The auction will work by the following rules:
When the initial bid is made, it must be greater than or equal to the item’s minimum bid amount
to be placed on the stack.
When another bid is made that is greater than the current high bidder’s maximum bid, that bid
will be pushed to the top of the stack and become the new highest bid.
If another bid is made that is greater than the current high bid but less than or equal to the
current high bidder’s maximum amount, the current high bidder’s bid will be raised to match but
the new bid will not be placed on the stack.
Your application should have a message box or label to indicate the status of the bid operation.
There is no limit on the number of bids.
Solution
// To import features as \'Panel, Button, Label, TextArea, TextField, Color\', etc.
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
// In this program, \"this.\" is used instead of \"this.getContentPane().\" in Auction.init() uses;
class Bidacution
{
public static void main (String[] args)
{ Frame gameapp = new Frame (\"AUCTION by Henry C. Joy\");
gameapp.setSize (750, 560); // larger than actual applet -- allow for edges
gameapp.addWindowListener (new WindowCloser());
Auction display = new Auction();
display.init();
gameapp.add (display);
gameapp.setVisible (true);
}
private static class WindowCloser extends java.awt.event.WindowAdapter
{ public void windowClosing (java.awt.event.WindowEvent e)
{ System.exit (0);
}}
}
// The MAIN method of the software (the init method): using 20 + classes.
public class Auction extends java.applet.Applet // every Applet is a Panel
{
public static final int UNIT = 5; // difference between 2 consec. bids
public static final int BREAK = 5; // separate first 5 from last 4
public static final String REPEAT = \"repeat game\";
// VIEW objects
private Panel boardPanel = new Panel();
p.
The following code, is a one player battleship game in JAVA. Im tryi.pdffonecomp
The following code, is a one player battleship game in JAVA. Im trying to Enhance the game to
be a two player game (were a player plays aggainst a computer opponent). With TWO boards
displayed side by side. The player and the computer must take turns selecting the coordinates on
their own boards. (the ships cannot be placed adjacent to each other).
BattleShipGame.java
package battleship;
import java.util.ArrayList;
import java.util.Scanner;
public class BattleshipGame {
private Ocean ocean;
private boolean[][] availableSpot;
private Scanner sc;
public BattleshipGame() {
// define a new ocean and a new 2D array to store available coordinates
ocean = new Ocean();
availableSpot = new boolean[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++){
availableSpot[i][j] = true;
}
}
}
/**
* prints the game menu and info
* //param select
*/
public void print(int select){
String info;
switch (select) {
case 1: info = \"Welcome to the World of Battleship!\";
break;
case 2: info = \"Enter coordinates to fire: \";
break;
case 3: info = \"Shots fired: \"+ocean.getShotsFired()+\", Ships sunk:
\"+ocean.getShipsSunk();
break;
case 4: info = \"Congratulations! You win!\";
break;
case 99: info = \"Invalid input. Please re-enter:\";
break;
case 100: info = \"--------------------------------------------\";
break;
case 101: info = \"\ ============================================\";
break;
default: info = \"Error selection\";
break;
}
System.out.println(info);
}
/**
* check if the input is valid
* //param input
* //return boolean
*/
public boolean checkValidInput(String input){
ArrayList numList = new ArrayList();
for (int i=0;i<10;i++){
numList.add(\"\"+i);
}
String[] coordinates = input.split(\" \");
//returns false if there are not 2 strings
if (coordinates.length!=2){
return false;
}
//returns false if any of the strings is not a single digit number
for (String str: coordinates){
if (numList.contains(str)==false){
return false;
}
}
//returns false if the coordinates have already been shot at
int row = Integer.parseInt(coordinates[0]);
int column = Integer.parseInt(coordinates[1]);
if (this.availableSpot[row][column]==false){
return false;
}
return true;
}
/**
* get the coordinates to shoot at from the String input
* //param input
* //return int[] coordinates
*/
public int[] getCoordinates(String input){
int[] coordinates = new int[2];
String[] strList = input.split(\" \");
int row = Integer.parseInt(strList[0]);
int column = Integer.parseInt(strList[1]);
coordinates[0] = row;
coordinates[1] = column;
return coordinates;
}
/**
* play the battleship game
*/
public void play(){
print(101);
print(1);
ocean.placeAllShipsRandomly();
boolean isGameOver = ocean.isGameOver();
sc = new Scanner(System.in);
//print the ocean and start the game
ocean.print();
print(3);
while (!isGameOver){
print(2);
String input = sc.nextLine();
//check if input is valid
while (!checkValidInput(input)){
print(99);
input = sc.nextLine();
}
//get coordinates and fire
int[] coord.
public interface Game Note interface in place of class { .pdfkavithaarp
public interface Game // Note *interface* in place of *class*
{
/// play the game and return the final score
/// where a higher score should be better,
/// and a negative score is allowed.
int play(); // Note semicolon in place of a body
// You can have multiple method headings declared
}
--------------------------------------------------------------------------------------------------------------
import java.util.*;
/// Starting point for Interface Lab.
public class PlayGames
{
private static Scanner in;
private static Random rand = new Random();
private static int gameCount = 0;
public static Game popRandom(Game[] g)
{
int n = gameCount;
int i = rand.nextInt(n);
Game ret = g[i];
g[i] = g[n-1];
gameCount--;
return ret;
}
public static void main(String[] args)
{
Game[] games = new Game[10]; // Note Game as a type
games[gameCount] = new AdditionGame(rand, 100);
gameCount++; // next index to put a Game at
// write at least 2 more different types of Game classes
// and add a new one of each type to games
// ...
in = new Scanner(System.in);
int totScore = 0;
do {
Game g = popRandom(games);
totScore += g.play(); // use numerical result from the game
} while (gameCount > 0 && agree(\"Want a game? \"));
System.out.println(\"Thanks for Playing!\");
System.out.println(\"Your total score is \" + totScore);
}
public static boolean agree(String prompt)
{
System.out.print(prompt);
String input = in.next();
if (input.equalsIgnoreCase(\"y\")) return true;
return false;
}
--------------------------------------------------------------------------------------------------------------------
--
import java.util.*;
public class AdditionGame implements Game // note implements!!
{
private Random rand;
private int n;
// Constructor for objects of class AdditionGame
public AdditionGame(Random r, int big)
{
rand = r;
n = big;
}
// play all games and keep score.
public int play() // exactly matches heading in Game interface
{
final int numGames = 3;
Scanner in = new Scanner(System.in);
int score = 0;
System.out.println(\"Welcome to the addition game! We\'ll now play \" + numGames
+ \" rounds.\");
for (int i = 0; i < numGames; i++) {
int x = rand.nextInt(n), y = rand.nextInt(n), ans = x+y;
System.out.print(String.format(\"Enter the sum: %d + %d = \", x, y));
int val = in.nextInt();
if (ans == val) {
System.out.println(\"Correct!\");
score++;
}
else
System.out.println(\"Wrong! Right answer is \" + ans);
}
System.out.println(\"Thanks for playing the addition game. Your score is \" + score +
\".\");
System.out.println();
return score;
}
}
--------------------------------------------------------------------------------------------------------------------
---
Create two classes that implement a Game interface:
------------------------------------
There is a Game interface defined, and also a PlayGames class that uses objects from classes that
implement that interface. The Game interface declares a single abstract method play that returns
an int, the score from playing the gam.
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdfinfomalad
Tic Tac Toe game with GUI written in java.
Solution
Answer:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TicTacToe extends JPanel
{
JButton buttons[] = new JButton[9];
int alternate = 0;//if this number is a even, then put a X. If it\'s odd, then put an O
public TicTacToe()
{
setLayout(new GridLayout(3,3));
initializebuttons();
}
public void initializebuttons()
{
for(int i = 0; i <= 8; i++)
{
buttons[i] = new JButton();
buttons[i].setText(\"\");
buttons[i].addActionListener(new buttonListener());
add(buttons[i]); //adds this button to JPanel (note: no need for JPanel.add(...)
//because this whole class is a JPanel already
}
}
public void resetButtons()
{
for(int i = 0; i <= 8; i++)
{
buttons[i].setText(\"\");
}
}
// when a button is clicked, it generates an ActionEvent. Thus, each button needs an
ActionListener. When it is clicked, it goes to this listener class that I have created and goes to the
actionPerformed method. There (and in this class), we decide what we want to do.
private class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton buttonClicked = (JButton)e.getSource(); //get the particular button that was clicked
if(alternate%2 == 0)
buttonClicked.setText(\"X\");
else
buttonClicked.setText(\"O\");
if(checkForWin() == true)
{
JOptionPane.showConfirmDialog(null, \"Game Over.\");
resetButtons();
}
alternate++;
}
public boolean checkForWin()
{
/** Reference: the button array is arranged like this as the board
* 0 | 1 | 2
* 3 | 4 | 5
* 6 | 7 | 8
*/
//horizontal win check
if( checkAdjacent(0,1) && checkAdjacent(1,2) ) //no need to put \" == true\" because the
default check is for true
return true;
else if( checkAdjacent(3,4) && checkAdjacent(4,5) )
return true;
else if ( checkAdjacent(6,7) && checkAdjacent(7,8))
return true;
//vertical win check
else if ( checkAdjacent(0,3) && checkAdjacent(3,6))
return true;
else if ( checkAdjacent(1,4) && checkAdjacent(4,7))
return true;
else if ( checkAdjacent(2,5) && checkAdjacent(5,8))
return true;
//diagonal win check
else if ( checkAdjacent(0,4) && checkAdjacent(4,8))
return true;
else if ( checkAdjacent(2,4) && checkAdjacent(4,6))
return true;
else
return false;
}
public boolean checkAdjacent(int a, int b)
{
if ( buttons[a].getText().equals(buttons[b].getText()) && !buttons[a].getText().equals(\"\") )
return true;
else
return false;
}
}
public static void main(String[] args)
{
JFrame window = new JFrame(\"Tic-Tac-Toe\");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(new TicTacToe());
window.setBounds(300,200,300,300);
window.setVisible(true);
}
}.
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxmary772
CodeZip/ButtonDemo.javaCodeZip/ButtonDemo.java// Demonstrate a push button and handle action events.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclassButtonDemoimplementsActionListener{
JLabel jlab;
JTextField jtf;
ButtonDemo(){
// Create a new JFrame container.
JFrame jfrm =newJFrame("A Button Example");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(newFlowLayout());
// Give the frame an initial size.
jfrm.setSize(220,90);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make two buttons.
JButton jbtnUp =newJButton("Up");
JButton jbtnDown =newJButton("Down");
// Create a text field.
jtf =newJTextField(10);
// Add action listeners.
jbtnUp.addActionListener(this);
jbtnDown.addActionListener(this);
// Add the buttons to the content pane.
jfrm.add(jbtnUp);
jfrm.add(jbtnDown);
jfrm.add(jtf);
// Create a label.
jlab =newJLabel("Press a button.");
// Add the label to the frame.
jfrm.add(jlab);
// Display the frame.
jfrm.setVisible(true);
}
// Handle button events.
publicvoid actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("Up")){
jlab.setText("You pressed Up.");
FileClock clock1=newFileClock(jtf);
Thread thread1=newThread(clock1);
thread1.start();
}
else
jlab.setText("You pressed down. ");
}
publicstaticvoid main(String args[]){
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(newRunnable(){
publicvoid run(){
newButtonDemo();
}
});
}
}
CodeZip/CBDemo.javaCodeZip/CBDemo.java// Demonstrate check boxes.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclassCBDemoimplementsItemListener{
JLabel jlabSelected;
JLabel jlabChanged;
JCheckBox jcbAlpha;
JCheckBox jcbBeta;
JCheckBox jcbGamma;
CBDemo(){
// Create a new JFrame container.
JFrame jfrm =newJFrame("Demonstrate Check Boxes");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(newFlowLayout());
// Give the frame an initial size.
jfrm.setSize(280,120);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create empty labels.
jlabSelected =newJLabel("");
jlabChanged =newJLabel("");
// Make check boxes.
jcbAlpha =newJCheckBox("Alpha");
jcbBeta =newJCheckBox("Beta");
jcbGamma =newJCheckBox("Gamma");
// Events generated by the check boxes
// are handled in common by the itemStateChanged()
// method implemented by CBDemo.
jcbAlpha.addItemListener(this);
jcbBeta.addItemListener(this);
jcbGamma.addItemListener(this);
// Add checkboxes and labels to the content pane.
jfrm.add(jcbAlpha);
jfrm.add(jcbBeta);
jfrm.add(jcbGamma);
jfrm.add(jlabChanged);
jfrm.add(jlabSelected);
// Display the frame.
jfrm.setVisible(true);
}
// This is the handler for the check boxes..
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxmccormicknadine86
CodeZip/ButtonDemo.javaCodeZip/ButtonDemo.java// Demonstrate a push button and handle action events.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclassButtonDemoimplementsActionListener{
JLabel jlab;
JTextField jtf;
ButtonDemo(){
// Create a new JFrame container.
JFrame jfrm =newJFrame("A Button Example");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(newFlowLayout());
// Give the frame an initial size.
jfrm.setSize(220,90);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make two buttons.
JButton jbtnUp =newJButton("Up");
JButton jbtnDown =newJButton("Down");
// Create a text field.
jtf =newJTextField(10);
// Add action listeners.
jbtnUp.addActionListener(this);
jbtnDown.addActionListener(this);
// Add the buttons to the content pane.
jfrm.add(jbtnUp);
jfrm.add(jbtnDown);
jfrm.add(jtf);
// Create a label.
jlab =newJLabel("Press a button.");
// Add the label to the frame.
jfrm.add(jlab);
// Display the frame.
jfrm.setVisible(true);
}
// Handle button events.
publicvoid actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("Up")){
jlab.setText("You pressed Up.");
FileClock clock1=newFileClock(jtf);
Thread thread1=newThread(clock1);
thread1.start();
}
else
jlab.setText("You pressed down. ");
}
publicstaticvoid main(String args[]){
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(newRunnable(){
publicvoid run(){
newButtonDemo();
}
});
}
}
CodeZip/CBDemo.javaCodeZip/CBDemo.java// Demonstrate check boxes.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclassCBDemoimplementsItemListener{
JLabel jlabSelected;
JLabel jlabChanged;
JCheckBox jcbAlpha;
JCheckBox jcbBeta;
JCheckBox jcbGamma;
CBDemo(){
// Create a new JFrame container.
JFrame jfrm =newJFrame("Demonstrate Check Boxes");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(newFlowLayout());
// Give the frame an initial size.
jfrm.setSize(280,120);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create empty labels.
jlabSelected =newJLabel("");
jlabChanged =newJLabel("");
// Make check boxes.
jcbAlpha =newJCheckBox("Alpha");
jcbBeta =newJCheckBox("Beta");
jcbGamma =newJCheckBox("Gamma");
// Events generated by the check boxes
// are handled in common by the itemStateChanged()
// method implemented by CBDemo.
jcbAlpha.addItemListener(this);
jcbBeta.addItemListener(this);
jcbGamma.addItemListener(this);
// Add checkboxes and labels to the content pane.
jfrm.add(jcbAlpha);
jfrm.add(jcbBeta);
jfrm.add(jcbGamma);
jfrm.add(jlabChanged);
jfrm.add(jlabSelected);
// Display the frame.
jfrm.setVisible(true);
}
// This is the handler for the check boxes. ...
Similar to import java.awt.;import java.awt.event.;import javax.swing.;.pdf (18)
1. VacuolesThe vacuole is an organelle in plant cells which stores.pdfaoneonlinestore1
1. Vacuoles
The vacuole is an organelle in plant cells which stores water and nutrients for the cell. It takes in
and release the water as per cell\'s requirement.
2. . In plasmolysed Elodea leaf the gap between the cell wall and the cell membrane is filled with
0.6M sucrose solution.
Solution
1. Vacuoles
The vacuole is an organelle in plant cells which stores water and nutrients for the cell. It takes in
and release the water as per cell\'s requirement.
2. . In plasmolysed Elodea leaf the gap between the cell wall and the cell membrane is filled with
0.6M sucrose solution..
1. B) - Two independent properties serve to specify the state.2. B.pdfaoneonlinestore1
1. B) - Two independent properties serve to specify the state.
2. B) - The locus of all points where the second law is satisfied.
3. B) - Is the p-T coordinates at which solid, liquid and vapour co-exist in equlibrium.
Solution
1. B) - Two independent properties serve to specify the state.
2. B) - The locus of all points where the second law is satisfied.
3. B) - Is the p-T coordinates at which solid, liquid and vapour co-exist in equlibrium..
(NH4)2SO4 is a soluble salt and is fully ionized in solution(NH4).pdfaoneonlinestore1
(NH4)2SO4 is a soluble salt and is fully ionized in solution:
(NH4)2SO4 => 2 NH4+ + SO42-
NH4+ is a weak acid and ionizes further: NH4+<=> NH3 + H+
The H+ formed can react with C2O42- to form the weak acid oxalic acid (H2C2O4):
C2O42- + 2 H+ <=> H2C2O4
Removal of C2O42- causes the equilibrium: ZnC2O4 <=> Zn2+ + C2O42-
to shift to the right according to Le Chatelier\'s principle and more ZnC2O4 dissolves.
Thus the solubility of ZnC2O4 increases in the presence of (NH4)2SO4.
Solution
(NH4)2SO4 is a soluble salt and is fully ionized in solution:
(NH4)2SO4 => 2 NH4+ + SO42-
NH4+ is a weak acid and ionizes further: NH4+<=> NH3 + H+
The H+ formed can react with C2O42- to form the weak acid oxalic acid (H2C2O4):
C2O42- + 2 H+ <=> H2C2O4
Removal of C2O42- causes the equilibrium: ZnC2O4 <=> Zn2+ + C2O42-
to shift to the right according to Le Chatelier\'s principle and more ZnC2O4 dissolves.
Thus the solubility of ZnC2O4 increases in the presence of (NH4)2SO4..
I have inserted spaces. Consider f(x) belonging to f(X) thi.pdfaoneonlinestore1
I have inserted spaces.
Consider f(x) belonging to f(X)
this means : x belongs to X
But X is a subset of Y
So, x belongs to Y
So, f(x) belongs to f(Y).
Hence all f(x) in f(X) belong to f(Y)
So, f(X) is a subset of f(Y)
Example: f(x) = sin(x) : R -> R
X = [0,2pi]
Y = [-2pi,2pi]
f(X) = [-1,1]
f(Y) = [-1,1]
So, f(X) = f(Y)
Solution
I have inserted spaces.
Consider f(x) belonging to f(X)
this means : x belongs to X
But X is a subset of Y
So, x belongs to Y
So, f(x) belongs to f(Y).
Hence all f(x) in f(X) belong to f(Y)
So, f(X) is a subset of f(Y)
Example: f(x) = sin(x) : R -> R
X = [0,2pi]
Y = [-2pi,2pi]
f(X) = [-1,1]
f(Y) = [-1,1]
So, f(X) = f(Y).
C program that prompts user to enter two floating point t.pdfaoneonlinestore1
/**
C program that prompts user to enter two floating point
type values and print the product of two values upt to 3
decimal places
*/
//program1.c
//header files
#include
#include
//main function
int main()
{
//declare two double type variables
double num1;
double num2;
//set a double variable,product=0
double product=0;
printf(\"Enter num1 and num2: \");
//prompt for num1 and num2 values from keyboard
scanf(\"%lf %lf\",&num1,&num2);
//calculate product
product=num1*num2;
//print product of two numbers and limit product to 3 decimal places
printf(\"The product of %lf and %lf is %5.3lf \ \",num1,num2,product);
getch();
return 0;
}
Sample output:
Enter num1 and num2: 2.25 3.25
The product of 2.250000 and 3.250000 is 7.313
------------------------------------------------------------------------------------
//2.
/**
C program that prompts user to enter integer values
until user enters 999 to stop reading. Then prit
number of even and odd to console.
*/
//program2.c
//header files
#include
#include
//main function
int main()
{
//set SENTINAL=999;
int SENTINAL=999;
//declare integer variable
int value;
//set even and odd=0
int even=0;
int odd=0;
printf(\"Enter a vlaue or 999 to stop reading input \");
scanf(\"%d\",&value);
//read until value is not 999
while(value!=SENTINAL)
{
//check if value is even
if(value%2==0)
//increment even by one
even++;
else
//otherwise increment odd by one
odd++;
printf(\"Enter a vlaue or 999 to stop reading input \");
//read a value
scanf(\"%d\",&value);
}
printf(\"Even numbers : %d\ \",even);
printf(\"Odd numbers : %d\ \",odd);
//pause program output on console
getch();
return 0;
}
Sample output:
Enter a vlaue or 999 to stop reading input 1
Enter a vlaue or 999 to stop reading input 2
Enter a vlaue or 999 to stop reading input 3
Enter a vlaue or 999 to stop reading input 4
Enter a vlaue or 999 to stop reading input 5
Enter a vlaue or 999 to stop reading input 6
Enter a vlaue or 999 to stop reading input 7
Enter a vlaue or 999 to stop reading input 8
Enter a vlaue or 999 to stop reading input 9
Enter a vlaue or 999 to stop reading input 10
Enter a vlaue or 999 to stop reading input 999
Even numbers : 5
Odd numbers : 5
------------------------------------------------------------------------------------------------------------
//3.
/**
C program that prompts length in inches and prints the length
in miles, yards, feet to console.
*/
//program3.c
//header files
#include
#include
//function prototype
void measure(int inch,int &m,int &y,int &f, int &i);
//main function
int main()
{
int miles,yards,feet,inches=0;
int len;
printf(\"Enter the length (inches): \");
//prompt for len
scanf(\"%d\",&len);
//calling measure method
measure(len,miles,yards,feet,inches);
//print len
printf(\"Total length : %d\ \", len);
//print miles,yards, feet and inches
printf(\"Miles : %d\ \", miles);
printf(\"Yards : %d\ \", yards);
printf(\"Feet : %d\ \", feet);
printf(\"Inches : %d\ \", inches);
//pause program output on console
getch();
return.
The carbonyl functional group in glucose is an al.pdfaoneonlinestore1
The carbonyl functional group in glucose is an aldehyde while the fructose contains
a ketone
Solution
The carbonyl functional group in glucose is an aldehyde while the fructose contains
a ketone.
Well to find the pH at the equivalance point. Acc.pdfaoneonlinestore1
Well to find the pH at the equivalance point. According to mychemistry book(
Chemistry: A Molecular Approach BY Nivaldo J. Tro,et. all.) . pH= pKa at the equivalnce point.
Solution
Well to find the pH at the equivalance point. According to mychemistry book(
Chemistry: A Molecular Approach BY Nivaldo J. Tro,et. all.) . pH= pKa at the equivalnce point..
The weakest base in the reaction is A the enolat.pdfaoneonlinestore1
The weakest base in the reaction is: A the enolate in the reaction is: C
Solution
The weakest base in the reaction is: A the enolate in the reaction is: C.
so take an aliquot of the upper layer and add a f.pdfaoneonlinestore1
so take an aliquot of the upper layer and add a few drops of water. if it\'s miscible,
it\'s water. if not, it\'s the ether.
Solution
so take an aliquot of the upper layer and add a few drops of water. if it\'s miscible,
it\'s water. if not, it\'s the ether..
moles of NH4Cl formed = 20.050 = 0.1 moles so we.pdfaoneonlinestore1
moles of NH4Cl formed = 2*0.050 = 0.1 moles so weight = 0.1 * 53.49 = 5.35 so
D is answer
Solution
moles of NH4Cl formed = 2*0.050 = 0.1 moles so weight = 0.1 * 53.49 = 5.35 so
D is answer.
Latency is a measure of time delay experienced in.pdfaoneonlinestore1
Latency is a measure of time delay experienced in a system, the precise definition
of which depends on the system and the time being measured.
Solution
Latency is a measure of time delay experienced in a system, the precise definition
of which depends on the system and the time being measured..
Entropy is the measure of disorder. Therefore, th.pdfaoneonlinestore1
Entropy is the measure of disorder. Therefore, the choice should be (D) because the
entropy of a system increases when two systems come in contact. Here, the two systems are two
liquids.
Solution
Entropy is the measure of disorder. Therefore, the choice should be (D) because the
entropy of a system increases when two systems come in contact. Here, the two systems are two
liquids..
Ø Napoleonic era brought some relief to the faltering ottoman empire.pdfaoneonlinestore1
Ø Napoleonic era brought some relief to the faltering ottoman empire .it distracted Russia from
further advances. Napoleon I himself invaded Egypt, but his army was trapped when the British
sank the French fleet. A peace interlude in 1803 allowed the army to return to France.
Ø To secure his own domination and to render the rest Europe virtually powerless, napoleon
established an alliance with Russia by concluding the treaty of titlist in 1807. Russia undertook
to aid napoleon in his war against Britain ,in turn the emperor of Russia would receive the
ottoman territories of Moldavia and Wallachia if the sultan refused to surrender these territories,
France and Russia were to attack the empire, and the ottoman in Europe were to be partitioned
between the two allies.
Ø The napoleon scheme threatened threated not only the sultan, but also Britain, Austria and
Prussia, which was almost powerless in the face of such a potent alliance. The alliance naturally
proved accommodating to the au strains , who hoped that a joint Franco –Russian attack which
would probably have utterly divested the ottoman empire, could be prevented by diplomacy, but
if diplomatic measures failed , the Austrian minister klemens wenzel, prince von Metternich
decided that he would support the partition of ottoman empire a solution disadvantages to
Austria. But not as dangerous as a complete Russian takeover of southeastern Europe.
Ø The Napoleonic era (1799–1815) brought some relief to the faltering Ottoman Empire. It
distracted Russia from further advances. Napoleon I himself invaded Egypt, but his army was
trapped there when the British sank the French fleet. A peace interlude in 1803 allowed the army
to return to France.
Solution
Ø Napoleonic era brought some relief to the faltering ottoman empire .it distracted Russia from
further advances. Napoleon I himself invaded Egypt, but his army was trapped when the British
sank the French fleet. A peace interlude in 1803 allowed the army to return to France.
Ø To secure his own domination and to render the rest Europe virtually powerless, napoleon
established an alliance with Russia by concluding the treaty of titlist in 1807. Russia undertook
to aid napoleon in his war against Britain ,in turn the emperor of Russia would receive the
ottoman territories of Moldavia and Wallachia if the sultan refused to surrender these territories,
France and Russia were to attack the empire, and the ottoman in Europe were to be partitioned
between the two allies.
Ø The napoleon scheme threatened threated not only the sultan, but also Britain, Austria and
Prussia, which was almost powerless in the face of such a potent alliance. The alliance naturally
proved accommodating to the au strains , who hoped that a joint Franco –Russian attack which
would probably have utterly divested the ottoman empire, could be prevented by diplomacy, but
if diplomatic measures failed , the Austrian minister klemens wenzel, prince von Metternich
decided that he would.
YES=Cathode rays have mass. .yes=Matter contains positive and nega.pdfaoneonlinestore1
YES=Cathode rays have mass.
.yes=Matter contains positive and negative charge.
YES=.Particles of the cathode rays are fundamental to all matter.
.yes= An atom is divisible.
Solution
YES=Cathode rays have mass.
.yes=Matter contains positive and negative charge.
YES=.Particles of the cathode rays are fundamental to all matter.
.yes= An atom is divisible..
TWEEN ENGINE1.Tween engine is universal.2.Reusability of tween .pdfaoneonlinestore1
TWEEN ENGINE:
1.Tween engine is universal.
2.Reusability of tween engine is possible to animate our projects in java .
3.It is generic(collective) and tells us to acess the features.
4.It supports all the interpolation functions.
5.Designed especially for the games.
6.By default they are pooled hence they can be used for android game development.
7.Single line is enough to create and start a normal interpolation.
8.yoyo style option is present to repeat the tweens and timelines.
Solution
TWEEN ENGINE:
1.Tween engine is universal.
2.Reusability of tween engine is possible to animate our projects in java .
3.It is generic(collective) and tells us to acess the features.
4.It supports all the interpolation functions.
5.Designed especially for the games.
6.By default they are pooled hence they can be used for android game development.
7.Single line is enough to create and start a normal interpolation.
8.yoyo style option is present to repeat the tweens and timelines..
To identify the identity of Variable Interest Entity , first of all .pdfaoneonlinestore1
To identify the identity of Variable Interest Entity , first of all we will check the snature, extent
and scope of the entity.
We will check the following
Solution
To identify the identity of Variable Interest Entity , first of all we will check the snature, extent
and scope of the entity.
We will check the following.
technology is the application of scientific knowledge. technology is.pdfaoneonlinestore1
technology is the application of scientific knowledge. technology is neutral by itself. Its effects
on environment depends on the people who handle it. technology had its ability to mitigate many
problems of world. it can reproduce the lost species and balance the ecosystem. it can fasten the
growth of trees and decrease the carnbon dioxide levels in the world. it can stop the spread of
epidemics that can eliminate a particular species from world. it can detect meteors and comets
and save world from destruction.
as i said its effects depend on people who handle it. Most of the people so called technocrats use
it for momentary monetarygains. this had led the world to the brisk of chaos. they focus on
technology producing gadgets that make people happy for short term and failing to understand
the long term effects
Solution
technology is the application of scientific knowledge. technology is neutral by itself. Its effects
on environment depends on the people who handle it. technology had its ability to mitigate many
problems of world. it can reproduce the lost species and balance the ecosystem. it can fasten the
growth of trees and decrease the carnbon dioxide levels in the world. it can stop the spread of
epidemics that can eliminate a particular species from world. it can detect meteors and comets
and save world from destruction.
as i said its effects depend on people who handle it. Most of the people so called technocrats use
it for momentary monetarygains. this had led the world to the brisk of chaos. they focus on
technology producing gadgets that make people happy for short term and failing to understand
the long term effects.
b)The cations on the left side act as oxidants. C.pdfaoneonlinestore1
b)The cations on the left side act as oxidants. Cations on the left are easily
oxidisable and hence are reducing agents
Solution
b)The cations on the left side act as oxidants. Cations on the left are easily
oxidisable and hence are reducing agents.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
1. import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class Checkers extends JPanel {
public static void main(String[] args) {
JFrame window = new JFrame("Checkers");
Checkers content = new Checkers();
window.setContentPane(content);
window.pack();
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screensize.width - window.getWidth())/2,
(screensize.height - window.getHeight())/2 );
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setResizable(false);
window.setVisible(true);
}
private JButton newGameButton; // Button for starting a new game.
private JButton resignButton; // Button that a player can use to end
// the game by resigning.
private JLabel message; // Label for displaying messages to the user.
public Checkers() {
setLayout(null); // I will do the layout myself.
setPreferredSize( new Dimension(350,250) );
setBackground(new Color(0,150,0)); // Dark green background.
/* Create the components and add them to the applet. */
2. Board board = new Board(); // Note: The constructor for the
// board also creates the buttons
// and label.
add(board);
add(newGameButton);
add(resignButton);
add(message);
/* Set the position and size of each component by calling
its setBounds() method. */
board.setBounds(20,20,164,164); // Note: size MUST be 164-by-164 !
newGameButton.setBounds(210, 60, 120, 30);
resignButton.setBounds(210, 120, 120, 30);
message.setBounds(0, 200, 350, 30);
} // end constructor
private static class CheckersMove {
int fromRow, fromCol; // Position of piece to be moved.
int toRow, toCol; // Square it is to move to.
CheckersMove(int r1, int c1, int r2, int c2) {
// Constructor. Just set the values of the instance variables.
fromRow = r1;
fromCol = c1;
toRow = r2;
toCol = c2;
}
boolean isJump() {
// Test whether this move is a jump. It is assumed that
// the move is legal. In a jump, the piece moves two
// rows. (In a regular move, it only moves one row.)
return (fromRow - toRow == 2 || fromRow - toRow == -2);
}
} // end class CheckersMove.
3. private class Board extends JPanel implements ActionListener, MouseListener {
CheckersData board; // The data for the checkers board is kept here.
// This board is also responsible for generating
// lists of legal moves.
boolean gameInProgress; // Is a game currently in progress?
/* The next three variables are valid only when the game is in progress. */
int currentPlayer; // Whose turn is it now? The possible values
// are CheckersData.RED and CheckersData.BLACK.
int selectedRow, selectedCol; // If the current player has selected a piece to
// move, these give the row and column
// containing that piece. If no piece is
// yet selected, then selectedRow is -1.
CheckersMove[] legalMoves; // An array containing the legal moves for the
// current player.
Board() {
setBackground(Color.BLACK);
addMouseListener(this);
resignButton = new JButton("Resign");
resignButton.addActionListener(this);
newGameButton = new JButton("New Game");
newGameButton.addActionListener(this);
message = new JLabel("",JLabel.CENTER);
message.setFont(new Font("Serif", Font.BOLD, 14));
message.setForeground(Color.green);
board = new CheckersData();
doNewGame();
}
4. /**
* Respond to user's click on one of the two buttons.
*/
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src == newGameButton)
doNewGame();
else if (src == resignButton)
doResign();
}
/**
* Start a new game
*/
void doNewGame() {
if (gameInProgress == true) {
// This should not be possible, but it doesn't hurt to check.
message.setText("Finish the current game first!");
return;
}
board.setUpGame(); // Set up the pieces.
currentPlayer = CheckersData.RED; // RED moves first.
legalMoves = board.getLegalMoves(CheckersData.RED); // Get RED's legal moves.
selectedRow = -1; // RED has not yet selected a piece to move.
message.setText("Red: Make your move.");
gameInProgress = true;
newGameButton.setEnabled(false);
resignButton.setEnabled(true);
repaint();
}
/**
* Current player resigns. Game ends. Opponent wins.
5. */
void doResign() {
if (gameInProgress == false) { // Should be impossible.
message.setText("There is no game in progress!");
return;
}
if (currentPlayer == CheckersData.RED)
gameOver("RED resigns. BLACK wins.");
else
gameOver("BLACK resigns. RED wins.");
}
void gameOver(String str) {
message.setText(str);
newGameButton.setEnabled(true);
resignButton.setEnabled(false);
gameInProgress = false;
}
void doClickSquare(int row, int col) {
for (int i = 0; i < legalMoves.length; i++)
if (legalMoves[i].fromRow == row && legalMoves[i].fromCol == col) {
selectedRow = row;
selectedCol = col;
if (currentPlayer == CheckersData.RED)
message.setText("RED: Make your move.");
else
message.setText("BLACK: Make your move.");
repaint();
return;
}
6. /* If no piece has been selected to be moved, the user must first
select a piece. Show an error message and return. */
if (selectedRow < 0) {
message.setText("Click the piece you want to move.");
return;
}
/* If the user clicked on a square where the selected piece can be
legally moved, then make the move and return. */
for (int i = 0; i < legalMoves.length; i++)
if (legalMoves[i].fromRow == selectedRow && legalMoves[i].fromCol == selectedCol
&& legalMoves[i].toRow == row && legalMoves[i].toCol == col) {
doMakeMove(legalMoves[i]);
return;
}
message.setText("Click the square you want to move to.");
} // end doClickSquare()
void doMakeMove(CheckersMove move) {
board.makeMove(move);
if (move.isJump()) {
legalMoves = board.getLegalJumpsFrom(currentPlayer,move.toRow,move.toCol);
if (legalMoves != null) {
if (currentPlayer == CheckersData.RED)
message.setText("RED: You must continue jumping.");
else
7. message.setText("BLACK: You must continue jumping.");
selectedRow = move.toRow; // Since only one piece can be moved, select it.
selectedCol = move.toCol;
repaint();
return;
}
}
if (currentPlayer == CheckersData.RED) {
currentPlayer = CheckersData.BLACK;
legalMoves = board.getLegalMoves(currentPlayer);
if (legalMoves == null)
gameOver("BLACK has no moves. RED wins.");
else if (legalMoves[0].isJump())
message.setText("BLACK: Make your move. You must jump.");
else
message.setText("BLACK: Make your move.");
}
else {
currentPlayer = CheckersData.RED;
legalMoves = board.getLegalMoves(currentPlayer);
if (legalMoves == null)
gameOver("RED has no moves. BLACK wins.");
else if (legalMoves[0].isJump())
message.setText("RED: Make your move. You must jump.");
else
message.setText("RED: Make your move.");
}
selectedRow = -1;
if (legalMoves != null) {
boolean sameStartSquare = true;
8. for (int i = 1; i < legalMoves.length; i++)
if (legalMoves[i].fromRow != legalMoves[0].fromRow
|| legalMoves[i].fromCol != legalMoves[0].fromCol) {
sameStartSquare = false;
break;
}
if (sameStartSquare) {
selectedRow = legalMoves[0].fromRow;
selectedCol = legalMoves[0].fromCol;
}
}
/* Make sure the board is redrawn in its new state. */
repaint();
} // end doMakeMove();
public void paintComponent(Graphics g) {
/* Draw a two-pixel black border around the edges of the canvas. */
g.setColor(Color.black);
g.drawRect(0,0,getSize().width-1,getSize().height-1);
g.drawRect(1,1,getSize().width-3,getSize().height-3);
/* Draw the squares of the checkerboard and the checkers. */
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if ( row % 2 == col % 2 )
g.setColor(Color.LIGHT_GRAY);
else
g.setColor(Color.GRAY);
g.fillRect(2 + col*20, 2 + row*20, 20, 20);
switch (board.pieceAt(row,col)) {
9. case CheckersData.RED:
g.setColor(Color.RED);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
break;
case CheckersData.BLACK:
g.setColor(Color.BLACK);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
break;
case CheckersData.RED_KING:
g.setColor(Color.RED);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
g.setColor(Color.WHITE);
g.drawString("K", 7 + col*20, 16 + row*20);
break;
case CheckersData.BLACK_KING:
g.setColor(Color.BLACK);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
g.setColor(Color.WHITE);
g.drawString("K", 7 + col*20, 16 + row*20);
break;
}
}
}
g.setColor(Color.cyan);
for (int i = 0; i < legalMoves.length; i++) {
g.drawRect(2 + legalMoves[i].fromCol*20, 2 + legalMoves[i].fromRow*20, 19, 19);
g.drawRect(3 + legalMoves[i].fromCol*20, 3 + legalMoves[i].fromRow*20, 17, 17);
}
/* If a piece is selected for moving (i.e. if selectedRow >= 0), then
draw a 2-pixel white border around that piece and draw green borders
around each square that that piece can be moved to. */
if (selectedRow >= 0) {
g.setColor(Color.white);
g.drawRect(2 + selectedCol*20, 2 + selectedRow*20, 19, 19);
g.drawRect(3 + selectedCol*20, 3 + selectedRow*20, 17, 17);
g.setColor(Color.green);
10. for (int i = 0; i < legalMoves.length; i++) {
if (legalMoves[i].fromCol == selectedCol && legalMoves[i].fromRow ==
selectedRow) {
g.drawRect(2 + legalMoves[i].toCol*20, 2 + legalMoves[i].toRow*20, 19, 19);
g.drawRect(3 + legalMoves[i].toCol*20, 3 + legalMoves[i].toRow*20, 17, 17);
}
}
}
}
} // end paintComponent()
public void mousePressed(MouseEvent evt) {
if (gameInProgress == false)
message.setText("Click "New Game" to start a new game.");
else {
int col = (evt.getX() - 2) / 20;
int row = (evt.getY() - 2) / 20;
if (col >= 0 && col < 8 && row >= 0 && row < 8)
doClickSquare(row,col);
}
}
public void mouseReleased(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
} // end class Board
private static class CheckersData {
/* The following constants represent the possible contents of a square
11. on the board. The constants RED and BLACK also represent players
in the game. */
static final int
EMPTY = 0,
RED = 1,
RED_KING = 2,
BLACK = 3,
BLACK_KING = 4;
int[][] board; // board[r][c] is the contents of row r, column c.
/**
* Constructor. Create the board and set it up for a new game.
*/
CheckersData() {
board = new int[8][8];
setUpGame();
}
void setUpGame() {
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if ( row % 2 == col % 2 ) {
if (row < 3)
board[row][col] = BLACK;
else if (row > 4)
board[row][col] = RED;
else
board[row][col] = EMPTY;
}
else {
board[row][col] = EMPTY;
}
}
12. }
} // end setUpGame()
int pieceAt(int row, int col) {
return board[row][col];
}
void makeMove(CheckersMove move) {
makeMove(move.fromRow, move.fromCol, move.toRow, move.toCol);
}
void makeMove(int fromRow, int fromCol, int toRow, int toCol) {
board[toRow][toCol] = board[fromRow][fromCol];
board[fromRow][fromCol] = EMPTY;
if (fromRow - toRow == 2 || fromRow - toRow == -2) {
// The move is a jump. Remove the jumped piece from the board.
int jumpRow = (fromRow + toRow) / 2; // Row of the jumped piece.
int jumpCol = (fromCol + toCol) / 2; // Column of the jumped piece.
board[jumpRow][jumpCol] = EMPTY;
}
if (toRow == 0 && board[toRow][toCol] == RED)
board[toRow][toCol] = RED_KING;
if (toRow == 7 && board[toRow][toCol] == BLACK)
board[toRow][toCol] = BLACK_KING;
}
CheckersMove[] getLegalMoves(int player) {
if (player != RED && player != BLACK)
return null;
int playerKing; // The constant representing a King belonging to player.
if (player == RED)
13. playerKing = RED_KING;
else
playerKing = BLACK_KING;
ArrayList moves = new ArrayList(); // Moves will be stored in this list.
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (board[row][col] == player || board[row][col] == playerKing) {
if (canJump(player, row, col, row+1, col+1, row+2, col+2))
moves.add(new CheckersMove(row, col, row+2, col+2));
if (canJump(player, row, col, row-1, col+1, row-2, col+2))
moves.add(new CheckersMove(row, col, row-2, col+2));
if (canJump(player, row, col, row+1, col-1, row+2, col-2))
moves.add(new CheckersMove(row, col, row+2, col-2));
if (canJump(player, row, col, row-1, col-1, row-2, col-2))
moves.add(new CheckersMove(row, col, row-2, col-2));
}
}
}
if (moves.size() == 0) {
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (board[row][col] == player || board[row][col] == playerKing) {
if (canMove(player,row,col,row+1,col+1))
moves.add(new CheckersMove(row,col,row+1,col+1));
if (canMove(player,row,col,row-1,col+1))
moves.add(new CheckersMove(row,col,row-1,col+1));
if (canMove(player,row,col,row+1,col-1))
moves.add(new CheckersMove(row,col,row+1,col-1));
if (canMove(player,row,col,row-1,col-1))
moves.add(new CheckersMove(row,col,row-1,col-1));
}
14. }
}
}
if (moves.size() == 0)
return null;
else {
CheckersMove[] moveArray = new CheckersMove[moves.size()];
for (int i = 0; i < moves.size(); i++)
moveArray[i] = moves.get(i);
return moveArray;
}
} // end getLegalMoves
CheckersMove[] getLegalJumpsFrom(int player, int row, int col) {
if (player != RED && player != BLACK)
return null;
int playerKing; // The constant representing a King belonging to player.
if (player == RED)
playerKing = RED_KING;
else
playerKing = BLACK_KING;
ArrayList moves = new ArrayList(); // The legal jumps will be stored in this list.
if (board[row][col] == player || board[row][col] == playerKing) {
if (canJump(player, row, col, row+1, col+1, row+2, col+2))
moves.add(new CheckersMove(row, col, row+2, col+2));
if (canJump(player, row, col, row-1, col+1, row-2, col+2))
moves.add(new CheckersMove(row, col, row-2, col+2));
if (canJump(player, row, col, row+1, col-1, row+2, col-2))
moves.add(new CheckersMove(row, col, row+2, col-2));
if (canJump(player, row, col, row-1, col-1, row-2, col-2))
moves.add(new CheckersMove(row, col, row-2, col-2));
}
15. if (moves.size() == 0)
return null;
else {
CheckersMove[] moveArray = new CheckersMove[moves.size()];
for (int i = 0; i < moves.size(); i++)
moveArray[i] = moves.get(i);
return moveArray;
}
} // end getLegalMovesFrom()
private boolean canJump(int player, int r1, int c1, int r2, int c2, int r3, int c3) {
if (r3 < 0 || r3 >= 8 || c3 < 0 || c3 >= 8)
return false; // (r3,c3) is off the board.
if (board[r3][c3] != EMPTY)
return false; // (r3,c3) already contains a piece.
if (player == RED) {
if (board[r1][c1] == RED && r3 > r1)
return false; // Regular red piece can only move up.
if (board[r2][c2] != BLACK && board[r2][c2] != BLACK_KING)
return false; // There is no black piece to jump.
return true; // The jump is legal.
}
else {
if (board[r1][c1] == BLACK && r3 < r1)
return false; // Regular black piece can only move downn.
if (board[r2][c2] != RED && board[r2][c2] != RED_KING)
return false; // There is no red piece to jump.
return true; // The jump is legal.
}
} // end canJump()
16. private boolean canMove(int player, int r1, int c1, int r2, int c2) {
if (r2 < 0 || r2 >= 8 || c2 < 0 || c2 >= 8)
return false; // (r2,c2) is off the board.
if (board[r2][c2] != EMPTY)
return false; // (r2,c2) already contains a piece.
if (player == RED) {
if (board[r1][c1] == RED && r2 > r1)
return false; // Regular red piece can only move down.
return true; // The move is legal.
}
else {
if (board[r1][c1] == BLACK && r2 < r1)
return false; // Regular black piece can only move up.
return true; // The move is legal.
}
} // end canMove()
} // end class CheckersData
} // end class Checkers
Solution
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class Checkers extends JPanel {
17. public static void main(String[] args) {
JFrame window = new JFrame("Checkers");
Checkers content = new Checkers();
window.setContentPane(content);
window.pack();
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screensize.width - window.getWidth())/2,
(screensize.height - window.getHeight())/2 );
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setResizable(false);
window.setVisible(true);
}
private JButton newGameButton; // Button for starting a new game.
private JButton resignButton; // Button that a player can use to end
// the game by resigning.
private JLabel message; // Label for displaying messages to the user.
public Checkers() {
setLayout(null); // I will do the layout myself.
setPreferredSize( new Dimension(350,250) );
setBackground(new Color(0,150,0)); // Dark green background.
/* Create the components and add them to the applet. */
Board board = new Board(); // Note: The constructor for the
// board also creates the buttons
// and label.
add(board);
add(newGameButton);
add(resignButton);
add(message);
18. /* Set the position and size of each component by calling
its setBounds() method. */
board.setBounds(20,20,164,164); // Note: size MUST be 164-by-164 !
newGameButton.setBounds(210, 60, 120, 30);
resignButton.setBounds(210, 120, 120, 30);
message.setBounds(0, 200, 350, 30);
} // end constructor
private static class CheckersMove {
int fromRow, fromCol; // Position of piece to be moved.
int toRow, toCol; // Square it is to move to.
CheckersMove(int r1, int c1, int r2, int c2) {
// Constructor. Just set the values of the instance variables.
fromRow = r1;
fromCol = c1;
toRow = r2;
toCol = c2;
}
boolean isJump() {
// Test whether this move is a jump. It is assumed that
// the move is legal. In a jump, the piece moves two
// rows. (In a regular move, it only moves one row.)
return (fromRow - toRow == 2 || fromRow - toRow == -2);
}
} // end class CheckersMove.
private class Board extends JPanel implements ActionListener, MouseListener {
CheckersData board; // The data for the checkers board is kept here.
// This board is also responsible for generating
// lists of legal moves.
19. boolean gameInProgress; // Is a game currently in progress?
/* The next three variables are valid only when the game is in progress. */
int currentPlayer; // Whose turn is it now? The possible values
// are CheckersData.RED and CheckersData.BLACK.
int selectedRow, selectedCol; // If the current player has selected a piece to
// move, these give the row and column
// containing that piece. If no piece is
// yet selected, then selectedRow is -1.
CheckersMove[] legalMoves; // An array containing the legal moves for the
// current player.
Board() {
setBackground(Color.BLACK);
addMouseListener(this);
resignButton = new JButton("Resign");
resignButton.addActionListener(this);
newGameButton = new JButton("New Game");
newGameButton.addActionListener(this);
message = new JLabel("",JLabel.CENTER);
message.setFont(new Font("Serif", Font.BOLD, 14));
message.setForeground(Color.green);
board = new CheckersData();
doNewGame();
}
/**
* Respond to user's click on one of the two buttons.
*/
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src == newGameButton)
20. doNewGame();
else if (src == resignButton)
doResign();
}
/**
* Start a new game
*/
void doNewGame() {
if (gameInProgress == true) {
// This should not be possible, but it doesn't hurt to check.
message.setText("Finish the current game first!");
return;
}
board.setUpGame(); // Set up the pieces.
currentPlayer = CheckersData.RED; // RED moves first.
legalMoves = board.getLegalMoves(CheckersData.RED); // Get RED's legal moves.
selectedRow = -1; // RED has not yet selected a piece to move.
message.setText("Red: Make your move.");
gameInProgress = true;
newGameButton.setEnabled(false);
resignButton.setEnabled(true);
repaint();
}
/**
* Current player resigns. Game ends. Opponent wins.
*/
void doResign() {
if (gameInProgress == false) { // Should be impossible.
message.setText("There is no game in progress!");
return;
}
if (currentPlayer == CheckersData.RED)
21. gameOver("RED resigns. BLACK wins.");
else
gameOver("BLACK resigns. RED wins.");
}
void gameOver(String str) {
message.setText(str);
newGameButton.setEnabled(true);
resignButton.setEnabled(false);
gameInProgress = false;
}
void doClickSquare(int row, int col) {
for (int i = 0; i < legalMoves.length; i++)
if (legalMoves[i].fromRow == row && legalMoves[i].fromCol == col) {
selectedRow = row;
selectedCol = col;
if (currentPlayer == CheckersData.RED)
message.setText("RED: Make your move.");
else
message.setText("BLACK: Make your move.");
repaint();
return;
}
/* If no piece has been selected to be moved, the user must first
select a piece. Show an error message and return. */
if (selectedRow < 0) {
message.setText("Click the piece you want to move.");
return;
22. }
/* If the user clicked on a square where the selected piece can be
legally moved, then make the move and return. */
for (int i = 0; i < legalMoves.length; i++)
if (legalMoves[i].fromRow == selectedRow && legalMoves[i].fromCol == selectedCol
&& legalMoves[i].toRow == row && legalMoves[i].toCol == col) {
doMakeMove(legalMoves[i]);
return;
}
message.setText("Click the square you want to move to.");
} // end doClickSquare()
void doMakeMove(CheckersMove move) {
board.makeMove(move);
if (move.isJump()) {
legalMoves = board.getLegalJumpsFrom(currentPlayer,move.toRow,move.toCol);
if (legalMoves != null) {
if (currentPlayer == CheckersData.RED)
message.setText("RED: You must continue jumping.");
else
message.setText("BLACK: You must continue jumping.");
selectedRow = move.toRow; // Since only one piece can be moved, select it.
selectedCol = move.toCol;
repaint();
return;
}
}
23. if (currentPlayer == CheckersData.RED) {
currentPlayer = CheckersData.BLACK;
legalMoves = board.getLegalMoves(currentPlayer);
if (legalMoves == null)
gameOver("BLACK has no moves. RED wins.");
else if (legalMoves[0].isJump())
message.setText("BLACK: Make your move. You must jump.");
else
message.setText("BLACK: Make your move.");
}
else {
currentPlayer = CheckersData.RED;
legalMoves = board.getLegalMoves(currentPlayer);
if (legalMoves == null)
gameOver("RED has no moves. BLACK wins.");
else if (legalMoves[0].isJump())
message.setText("RED: Make your move. You must jump.");
else
message.setText("RED: Make your move.");
}
selectedRow = -1;
if (legalMoves != null) {
boolean sameStartSquare = true;
for (int i = 1; i < legalMoves.length; i++)
if (legalMoves[i].fromRow != legalMoves[0].fromRow
|| legalMoves[i].fromCol != legalMoves[0].fromCol) {
sameStartSquare = false;
break;
}
if (sameStartSquare) {
24. selectedRow = legalMoves[0].fromRow;
selectedCol = legalMoves[0].fromCol;
}
}
/* Make sure the board is redrawn in its new state. */
repaint();
} // end doMakeMove();
public void paintComponent(Graphics g) {
/* Draw a two-pixel black border around the edges of the canvas. */
g.setColor(Color.black);
g.drawRect(0,0,getSize().width-1,getSize().height-1);
g.drawRect(1,1,getSize().width-3,getSize().height-3);
/* Draw the squares of the checkerboard and the checkers. */
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if ( row % 2 == col % 2 )
g.setColor(Color.LIGHT_GRAY);
else
g.setColor(Color.GRAY);
g.fillRect(2 + col*20, 2 + row*20, 20, 20);
switch (board.pieceAt(row,col)) {
case CheckersData.RED:
g.setColor(Color.RED);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
break;
case CheckersData.BLACK:
g.setColor(Color.BLACK);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
25. break;
case CheckersData.RED_KING:
g.setColor(Color.RED);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
g.setColor(Color.WHITE);
g.drawString("K", 7 + col*20, 16 + row*20);
break;
case CheckersData.BLACK_KING:
g.setColor(Color.BLACK);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
g.setColor(Color.WHITE);
g.drawString("K", 7 + col*20, 16 + row*20);
break;
}
}
}
g.setColor(Color.cyan);
for (int i = 0; i < legalMoves.length; i++) {
g.drawRect(2 + legalMoves[i].fromCol*20, 2 + legalMoves[i].fromRow*20, 19, 19);
g.drawRect(3 + legalMoves[i].fromCol*20, 3 + legalMoves[i].fromRow*20, 17, 17);
}
/* If a piece is selected for moving (i.e. if selectedRow >= 0), then
draw a 2-pixel white border around that piece and draw green borders
around each square that that piece can be moved to. */
if (selectedRow >= 0) {
g.setColor(Color.white);
g.drawRect(2 + selectedCol*20, 2 + selectedRow*20, 19, 19);
g.drawRect(3 + selectedCol*20, 3 + selectedRow*20, 17, 17);
g.setColor(Color.green);
for (int i = 0; i < legalMoves.length; i++) {
if (legalMoves[i].fromCol == selectedCol && legalMoves[i].fromRow ==
selectedRow) {
g.drawRect(2 + legalMoves[i].toCol*20, 2 + legalMoves[i].toRow*20, 19, 19);
g.drawRect(3 + legalMoves[i].toCol*20, 3 + legalMoves[i].toRow*20, 17, 17);
}
}
26. }
}
} // end paintComponent()
public void mousePressed(MouseEvent evt) {
if (gameInProgress == false)
message.setText("Click "New Game" to start a new game.");
else {
int col = (evt.getX() - 2) / 20;
int row = (evt.getY() - 2) / 20;
if (col >= 0 && col < 8 && row >= 0 && row < 8)
doClickSquare(row,col);
}
}
public void mouseReleased(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
} // end class Board
private static class CheckersData {
/* The following constants represent the possible contents of a square
on the board. The constants RED and BLACK also represent players
in the game. */
static final int
EMPTY = 0,
RED = 1,
RED_KING = 2,
BLACK = 3,
27. BLACK_KING = 4;
int[][] board; // board[r][c] is the contents of row r, column c.
/**
* Constructor. Create the board and set it up for a new game.
*/
CheckersData() {
board = new int[8][8];
setUpGame();
}
void setUpGame() {
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if ( row % 2 == col % 2 ) {
if (row < 3)
board[row][col] = BLACK;
else if (row > 4)
board[row][col] = RED;
else
board[row][col] = EMPTY;
}
else {
board[row][col] = EMPTY;
}
}
}
} // end setUpGame()
int pieceAt(int row, int col) {
return board[row][col];
28. }
void makeMove(CheckersMove move) {
makeMove(move.fromRow, move.fromCol, move.toRow, move.toCol);
}
void makeMove(int fromRow, int fromCol, int toRow, int toCol) {
board[toRow][toCol] = board[fromRow][fromCol];
board[fromRow][fromCol] = EMPTY;
if (fromRow - toRow == 2 || fromRow - toRow == -2) {
// The move is a jump. Remove the jumped piece from the board.
int jumpRow = (fromRow + toRow) / 2; // Row of the jumped piece.
int jumpCol = (fromCol + toCol) / 2; // Column of the jumped piece.
board[jumpRow][jumpCol] = EMPTY;
}
if (toRow == 0 && board[toRow][toCol] == RED)
board[toRow][toCol] = RED_KING;
if (toRow == 7 && board[toRow][toCol] == BLACK)
board[toRow][toCol] = BLACK_KING;
}
CheckersMove[] getLegalMoves(int player) {
if (player != RED && player != BLACK)
return null;
int playerKing; // The constant representing a King belonging to player.
if (player == RED)
playerKing = RED_KING;
else
playerKing = BLACK_KING;
ArrayList moves = new ArrayList(); // Moves will be stored in this list.
29. for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (board[row][col] == player || board[row][col] == playerKing) {
if (canJump(player, row, col, row+1, col+1, row+2, col+2))
moves.add(new CheckersMove(row, col, row+2, col+2));
if (canJump(player, row, col, row-1, col+1, row-2, col+2))
moves.add(new CheckersMove(row, col, row-2, col+2));
if (canJump(player, row, col, row+1, col-1, row+2, col-2))
moves.add(new CheckersMove(row, col, row+2, col-2));
if (canJump(player, row, col, row-1, col-1, row-2, col-2))
moves.add(new CheckersMove(row, col, row-2, col-2));
}
}
}
if (moves.size() == 0) {
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (board[row][col] == player || board[row][col] == playerKing) {
if (canMove(player,row,col,row+1,col+1))
moves.add(new CheckersMove(row,col,row+1,col+1));
if (canMove(player,row,col,row-1,col+1))
moves.add(new CheckersMove(row,col,row-1,col+1));
if (canMove(player,row,col,row+1,col-1))
moves.add(new CheckersMove(row,col,row+1,col-1));
if (canMove(player,row,col,row-1,col-1))
moves.add(new CheckersMove(row,col,row-1,col-1));
}
}
}
}
if (moves.size() == 0)
return null;
30. else {
CheckersMove[] moveArray = new CheckersMove[moves.size()];
for (int i = 0; i < moves.size(); i++)
moveArray[i] = moves.get(i);
return moveArray;
}
} // end getLegalMoves
CheckersMove[] getLegalJumpsFrom(int player, int row, int col) {
if (player != RED && player != BLACK)
return null;
int playerKing; // The constant representing a King belonging to player.
if (player == RED)
playerKing = RED_KING;
else
playerKing = BLACK_KING;
ArrayList moves = new ArrayList(); // The legal jumps will be stored in this list.
if (board[row][col] == player || board[row][col] == playerKing) {
if (canJump(player, row, col, row+1, col+1, row+2, col+2))
moves.add(new CheckersMove(row, col, row+2, col+2));
if (canJump(player, row, col, row-1, col+1, row-2, col+2))
moves.add(new CheckersMove(row, col, row-2, col+2));
if (canJump(player, row, col, row+1, col-1, row+2, col-2))
moves.add(new CheckersMove(row, col, row+2, col-2));
if (canJump(player, row, col, row-1, col-1, row-2, col-2))
moves.add(new CheckersMove(row, col, row-2, col-2));
}
if (moves.size() == 0)
return null;
else {
CheckersMove[] moveArray = new CheckersMove[moves.size()];
for (int i = 0; i < moves.size(); i++)
moveArray[i] = moves.get(i);
return moveArray;
31. }
} // end getLegalMovesFrom()
private boolean canJump(int player, int r1, int c1, int r2, int c2, int r3, int c3) {
if (r3 < 0 || r3 >= 8 || c3 < 0 || c3 >= 8)
return false; // (r3,c3) is off the board.
if (board[r3][c3] != EMPTY)
return false; // (r3,c3) already contains a piece.
if (player == RED) {
if (board[r1][c1] == RED && r3 > r1)
return false; // Regular red piece can only move up.
if (board[r2][c2] != BLACK && board[r2][c2] != BLACK_KING)
return false; // There is no black piece to jump.
return true; // The jump is legal.
}
else {
if (board[r1][c1] == BLACK && r3 < r1)
return false; // Regular black piece can only move downn.
if (board[r2][c2] != RED && board[r2][c2] != RED_KING)
return false; // There is no red piece to jump.
return true; // The jump is legal.
}
} // end canJump()
private boolean canMove(int player, int r1, int c1, int r2, int c2) {
if (r2 < 0 || r2 >= 8 || c2 < 0 || c2 >= 8)
return false; // (r2,c2) is off the board.
if (board[r2][c2] != EMPTY)
32. return false; // (r2,c2) already contains a piece.
if (player == RED) {
if (board[r1][c1] == RED && r2 > r1)
return false; // Regular red piece can only move down.
return true; // The move is legal.
}
else {
if (board[r1][c1] == BLACK && r2 < r1)
return false; // Regular black piece can only move up.
return true; // The move is legal.
}
} // end canMove()
} // end class CheckersData
} // end class Checkers