Hello I am new in Java and I have stuck. I am trying to make chess game, I made everything except check and checkmate method, and if you have any suggestions I will be happy to read them. Here is my work till now:
This is the board class where we play the game:
public class Board {
public static final int COLOR_WHITE = 1;
public static final int COLOR_BLACK = 2;
public static PlayingPiece[][] board;
private boolean isFirstMove;
private int color;
public Board() {
this.setBoard(new PlayingPiece[8][8]);
this.isFirstMove = true;
this.initializePieces();
}
// Initialize the chess pieces
public void initializePieces() {
for (int i = 0; i < 8; i++) {
board[1][i] = new Pawn(1, i, COLOR_WHITE);
}
for (int i = 0; i < 8; i++) {
board[6][i] = new Pawn(6, i, COLOR_BLACK);
}
board[0][0] = new Rook(0, 0, COLOR_WHITE);
board[0][7] = new Rook(0, 7, COLOR_WHITE);
board[7][0] = new Rook(7, 0, COLOR_BLACK);
board[7][7] = new Rook(7, 7, COLOR_BLACK);
board[0][1] = new Knight(0, 1, COLOR_WHITE);
board[0][6] = new Knight(0, 6, COLOR_WHITE);
board[7][1] = new Knight(7, 1, COLOR_BLACK);
board[7][6] = new Knight(7, 6, COLOR_BLACK);
board[0][2] = new Officer(0, 2, COLOR_WHITE);
board[0][5] = new Officer(0, 5, COLOR_WHITE);
board[7][2] = new Officer(7, 2, COLOR_BLACK);
board[7][5] = new Officer(7, 5, COLOR_BLACK);
board[0][3] = new Queen(3, 0, COLOR_WHITE);
board[0][4] = new King(4, 0, COLOR_WHITE);
board[7][3] = new Queen(7, 3, COLOR_BLACK);
board[7][4] = new King(7, 4, COLOR_BLACK);
this.printBoard();
}
public boolean play(int color, int fromX, int fromY, int toX, int toY) {
boolean isTrue = false;
// Check if this is the first turn and only white can move
if (isFirstMove && color == COLOR_WHITE) {
isTrue = true;
} else if (isFirstMove && color == COLOR_BLACK) {
return false;
}
// check if player plays 2 times in a raw and if you move the piece from
// current possition
if (color == this.color || (toX == fromX && toY == fromY)) {
return false;
}
isTrue = true;
if (isTrue == true) {
this.isFirstMove = false;
// Check if player plays with his own color
if (((board[fromX][fromY]).getColor() != color)) {
return false;
}
// Check the isLegal movement of every chess piece
if ((board[fromX][fromY]).move(toX, toY)) {
board[toX][toY] = board[fromX][fromY];
board[fromX][fromY] = null;
}
this.printBoard();
}
return isTrue;
}
public PlayingPiece[][] getBoard() {
return board;
}
public void setBoard(PlayingPiece[][] board) {
Board.board = board;
}
This is the Pieces class with all kind of pieces:
package com.chess.www;
public class PlayingPiece {
public static final int COLOR_WHITE = 1;
public static final int COLOR_BLACK = 2;
public static final char BLACK_PAWN = '\u265F';
public static final char BLACK_ROOK = '\u265C';
public static final char BLACK_KNIGHT = '\u265E';
public static final char BLACK_BISHOP = '\u265D';
public static final char BLACK_QUEEN = '\u265B';
public static final char BLACK_KING = '\u265A';
public static final char WHITE_PAWN = '\u2659';
public static final char WHITE_ROOK = '\u2656';
public static final char WHITE_KNIGHT = '\u2658';
public static final char WHITE_BISHOP = '\u2657';
public static final char WHITE_QUEEN = '\u2655';
public static final char WHITE_KING = '\u2654';
public static final char NO_PIECE = ' ';
private int x, y;
private boolean isAlive;
private int color;
private char symbol;
protected PlayingPiece (int newX, int newY, int newColor) {
this.setX(newX);
this.setY(newY);
this.color = newColor;
this.isAlive = true;
}
protected PlayingPiece(int newX, int newY) {
this.setX(newX);
this.setY(newY);
}
protected PlayingPiece() {
}
public int getX() {
return x;
}
public void setY(int y) {
this.y = y;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
protected boolean moveIsLegal (int newX, int newY) {
boolean isLegal = false;
if ((0 <= newX && newX <= 7) && (0 <= newY && newY <= 7)){
isLegal = true;
}
return isLegal;
}
public boolean move (int newX, int newY) {
if (moveIsLegal(newX, newY)) {
setX(newX);
setY(newY);
return true;
}
return false;
}
public int getColor() {
return color;
}
public boolean isAlive() {
return isAlive;
}
public void setAlive(boolean isAlive) {
this.isAlive = isAlive;
}
public char getSymbol() {
return symbol;
}
public void setSymbol(char symbol) {
this.symbol = symbol;
}
}
And here is the King class:
package com.chess.www;
public class King extends PlayingPiece {
public King(int newX, int newY, int color) {
super(newX, newY, color);
if (color == COLOR_BLACK) {
this.setSymbol(BLACK_KING);
} else {
this.setSymbol(WHITE_KING);
}
}
#Override
protected boolean moveIsLegal(int newX, int newY) {
int newPositionX = newX - getX();
int newPositionY = newY - getY();
int checkX = this.getX();
int checkY = this.getY();
if (super.moveIsLegal(newX, newY)) {
if ((Math.abs(newPositionX) == 1) && (newY == getY())) {
while (checkX != newX) {
if (this.isValidTraceX(checkX, newY, newX)) {
return true;
}
if (checkX > newX) {
checkX--;
} else if (this.getX() < newX) {
checkX++;
}
}
} else if ((newX == getX()) && (Math.abs(newPositionY) == 1)) {
while (checkY != newY) {
if (this.isValidTraceY(newX, checkY, newY)) {
return true;
}
if (checkY > newY) {
checkY--;
} else if (this.getY() < newY) {
checkY++;
}
}
} else if ((Math.abs(newPositionY) == 1) == (Math.abs(newPositionX) == 1)) {
while (checkX != newX && checkY != newY) {
if (this.isValidTrace(checkX, checkY, newX, newY)) {
return true;
}
if (checkX > newX) {
checkX--;
} else if (this.getX() < newX) {
checkX++;
}
if (checkY > newY) {
checkY--;
} else if (this.getY() < newY) {
checkY++;
}
}
}
}
return false;
}
public boolean isValidTraceX(int newX, int newY, int lastX) {
boolean isValid = true;
if ((Board.board[newX][newY]) != null) {
isValid = false;
}
if (((Board.board[lastX][newY]) != null)) {
if (Board.board[lastX][newY].getColor() == this.getColor()) {
isValid = false;
} else {
isValid = true;
}
}
return isValid;
}
public boolean isValidTraceY(int newX, int newY, int lastY) {
boolean isValid = true;
if ((Board.board[newX][newY]) != null) {
isValid = false;
}
if (((Board.board[newX][lastY]) != null)) {
if (Board.board[newX][lastY].getColor() == this.getColor()) {
isValid = false;
} else {
isValid = true;
}
}
return isValid;
}
public boolean isValidTrace(int newX, int newY, int lastX, int lastY) {
boolean isValid = true;
if ((Board.board[newX][newY]) != null) {
isValid = false;
}
if (((Board.board[lastX][lastY]) != null)) {
if (Board.board[lastX][lastY].getColor() == this.getColor()) {
isValid = false;
} else {
isValid = true;
}
}
return isValid;
}
}
I want to implement the method for check in board class do you have any suggestions?
The way I would implement would be just a method in the King class called something like, isChecked.
boolean isChecked() {
/* Check straight lines */
for (directions) { // up, down, left and right
for (square in direction) { // square by square from the king and out in the current direction
if (square contains opponent rook or queen)
return true;
else if (square contains friendly piece)
continue;
/* Check diagonals */
for (directions) { // left-up, left-down, right-up and right-down
for (square in direction) { // square by square from the king and out in the current direction
if (square contains opponent bishop or queen)
return true;
else if (square contains friendly piece)
continue;
/* Check pawns */
if (squares where pawns would threaten the king contains pawns)
return true;
/* Check king, this is to find if a square is legal to move to only */
if (squares where a king would threaten the king contains king)
return true;
/* Check knights */
if (squares where knights would threaten the king contains knights)
return true;
Sorry, I haven't really got time to write the entire code now, but the pseudo code should be enough to understand the concept. If you need I could fix it later today.
The principle is just, check every possible way a king can be checked.
If a king is checked and all possible moves are also checked, it is a checkmate.
Hope it helps :)
import java.util.Arrays;
public class KingsChecker {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
String[][] chess = new String[n][n];
print(chess,n);
}
public static void print (String[][] chess,int n) {
for(int i = 0; i< chess.length; i++) {
double random = Math.random()*n; //to generate a random number.
for(int j = 0; j < chess[i].length; j++) {
int column = (int)random;
int[] count = new int[n];
chess[i][j]= "+";
count[column]++;
if (count[column]<=1){
chess[i][column]="k";
System.out.print(chess[i][j]);
}
}
System.out.println();
}
}
}
Related
Im supposed to create a Snake game using a Queue in Java.
I'm supposed to only use the three classes down below, however I do not know how I should modify my move() function in order to move the snake, since it is a Queue and I cannot access the tail of the snake.
I came up with the following:
Snake.java
import java.util.Random;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Snake extends JFrame implements Runnable, KeyListener {
int length=40, width = 30;
int time;
int factor=10;
Specialqueue q;
int direction = 6;
Thread t;
int[][] food;
private boolean started;
public Snake() {
super("Snake");
setSize(length*factor+30, width*factor+60);
setVisible(true);
addKeyListener(this);
started = false;
time = 0;
}
public void paint(Graphics g){
if (g == null) return;
g.clearRect(0,0,getWidth(),getHeight());
if (!gestartet){
g.drawString("start the game by pressing 5",10,50);
g.drawString("Controll the snake with W,A,S,D",10,80);
return;
}
g.setColor(Color.blue);
for (int k = 0; k < length; k++)
for (int j = 0; j < breite; j++)
if (food[k][j]==1)
g.fillOval(k*10,20+j*10,10,10);
}
public void run() {
time = 0;
while (started){
try {Thread.sleep(300);}
catch (Exception e){};
move();
time++;
Graphics g = this.getGraphics();
}
}
public void stop() {
started=false;
t = null;
}
public void initFood() {
food = new int[length][breite];
for (int k = 0; k < length; k++) {
for (int j = 0; j < breite; j++) {
if (Math.random() < 0.01) futter[k][j] = 1;
else food[k][j] = 0;
}
}
}
public void initSnake(){
q = new Specialqueue();
direction = 6;
q.append(new Point(20,20));
q.append(new Point(19,20));
q.append(new Point(18,20));
q.append(new Point(17,20));
Graphics g = this.getGraphics();
repaint();
g.setColor(Color.red);
g.fillOval(20*10,20+20*10,10,10);
g.fillOval(19*10,20+20*10,10,10);
g.fillOval(18*10,20+20*10,10,10);
g.fillOval(17*10,20+20*10,10,10);
g.setColor(Color.black);
}
public void move()
{
Graphics g = this.getGraphics();
Point p = (Point)q.tail();
Point newPoint = null;
int size = 4;
if (direction == 6) {
for(int i=0;i<3;i++) {
q.remove();
}
for(int q=0;q<3;q++) {
newPoint = new Point(p.x+1, p.y);
}
if (newPoint.x >= length) {stoppe(); return;}
}
else if (direction == 4) {
newPoint = new Point(p.x-1, p.y);
if (newPoint.x < 0) {stoppe(); return;}
}
else if (direction == 8)
{
newPoint = new Point(p.x, p.y-1);
if (newPoint.y < 0) {stoppe(); return;}
}
else if (direction == 2)
{
newPoint = new Point(p.x, p.y+1);
if (newPoint.y >= width) {stoppe(); return;}
}
q.append(newPoint);
p = (Point)q.tail();
g.setColor(Color.red);
g.fillOval(p.x*10,20+p.y*10,10,10);
if(food[newPoint.x][newPoint.y] == 0){
p = (Point)q.first();
g.setColor(Color.white);
g.fillOval(p.x*10,20+p.y*10,10,10);
q.remove();
}
else {
food[newPoint.x][newPoint.y]=0;
}
}
public void keyPressed(KeyEvent ke)
{
char c = ke.getKeyChar();
if (c=='5' && started) {started = false; t = null; repaint(); return; }
if (c=='5' && !started){
gestartet=true;
initSnake();
initFutter();
t = new Thread(this);
try {Thread.sleep(150);} catch (Exception e){};
t.start();
return;
}
if ((c =='6' || c=='d') && direction != 4) direction = 6;
else if ((c =='2' || c=='s') && direction != 8) direction = 2;
else if ((c =='4' || c=='a') && direction != 6) direction = 4;
else if ((c =='8' || c=='w') && direction != 2) direction = 8;
}
}
SpecialQueue.java
public class Specialqueue <ContentType> {
Queue<ContentType> s;
public Specialqueue()
{
s = new Queue<ContentType>();
}
public ContentType tail(){
if (s.isEmpty()) return null;
return s.front();
}
public boolean isEmpty(){
return s.isEmpty();
}
public void append(ContentType pContent)
{
s.enqueue(pContent);
}
public void remove()
{
if(!s.isEmpty()) {
s.dequeue();
}
}
public ContentType first(){
if (this.isEmpty())
{
return null;
}
else{
return s.front();
}
}
}
**Queue.java**
public class Queue {
protected class QueueNode {
protected ContentType content = null;
protected QueueNode nextNode = null;
public QueueNode(ContentType pContent) {
content = pContent;
nextNode = null;
}
public void setNext(QueueNode pNext) {
nextNode = pNext;
}
public QueueNode getNext() {
return nextNode;
}
public ContentType getContent() {
return content;
}
}
protected QueueNode head;
protected QueueNode tail;
public Queue() {
head = null;
tail = null;
}
public boolean isEmpty() {
return head == null;
}
public void enqueue(ContentType pContent) {
if (pContent != null) {
QueueNode newNode = new QueueNode(pContent);
if (this.isEmpty()) {
head = newNode;
tail = newNode;
} else {
tail.setNext(newNode);
tail = newNode;
}
}
}
public void dequeue() {
if (!this.isEmpty()) {
head = head.getNext();
if (this.isEmpty()) {
head = null;
tail = null;
}
}
}
public ContentType front() {
if (this.isEmpty()) {
return null;
} else {
return head.getContent();
}
}
}
I need help with a program I have to finish by this Saturday, it is really important, I actually have this code in spanish though. I am looking for a way to make a simple IA, here are my classes:
public class Game {
private HumanPlayer[] players;
public Game() {
this.players = new HumanPlayer[]{
new HumanPlayer(1),
new HumanPlayer(2)
};
}
public void start() {
int i = 0;
int j = 1;
int len = players.length;
HumanPlayer player = null;
this.players[i].colocaBarcos();
this.players[j].colocaBarcos2();
while(players[0].getVidasRestantes() > 0 &&
players[1].getVidasRestantes() > 0) {
players[i++ % len].dispararA(players[j++ % len]);
player = (players[0].getVidasRestantes() < players[1].getVidasRestantes()) ?
players[1] :
players[0];
}
System.out.printf("Enhorabuena Player %d, ganaste!",player.getId());
}
}
public class AguaField implements IGameField {
private boolean fieldGolpeado = false;
#Override
public char getIcon() {
return fieldGolpeado ? 'M' : '~';
}
#Override
public Resultado dispararA() {
fieldGolpeado = true;
return Resultado.NO_GOLPE;
}
}
public class Barco {
private final String nombre;
private final int tamaño;
private int vidas;
public Barco(String nombre, int tamaño) {
this.nombre = nombre;
this.tamaño = tamaño;
this.vidas = tamaño;
}
public void golpear() {
if(vidas > 0) {
System.out.printf("%nBuen golpe! El %s fue golpeado", nombre);
vidas--;
}
else {
System.out.println("El barco fue destruido");
}
}
public Resultado getEstado() {
if(vidas == 0) {
return Resultado.DESTRUIDO;
}
else if(vidas < tamaño) {
return Resultado.PARCIAL_GOLPE;
}
else {
return Resultado.NO_GOLPE;
}
}
public String getNombre() {
return nombre;
}
public int getTamaño() {
return tamaño;
}
}
public class BarcoField implements IGameField {
private final Barco ship;
public BarcoField(Barco ship) {
this.ship = ship;
}
#Override
public char getIcon() {
char icon;
Resultado barcoEstado = ship.getEstado();
switch (barcoEstado) {
case PARCIAL_GOLPE: icon = 'O';
break;
case DESTRUIDO: icon = 'O';
break;
case NO_GOLPE: icon = 'X';
break;
default: icon = ' ';
break;
}
return icon;
}
#Override
public Resultado dispararA() {
ship.golpear();
return ship.getEstado();
}
}
public class BarcoTamaño {
private BarcoTamaño() {
}
public static final int CARRIER = 6;
public static final int BATTLESHIP = 4;
public static final int CRUISER = 2;
public static final int DESTROYER = 1;
}
public class HumanPlayer implements IPlayer {
private int totalVidas = 17;
private int id;
private Tablero tablero;
private Tablero tablero2;
private Scanner scanner;
public HumanPlayer(int id) {
this.id = id;
this.tablero = new Tablero();
this.scanner = new Scanner(System.in);
}
public int getId() {
return id;
}
public Tablero getTablero() {
return tablero;
}
#Override
public void colocaBarcos() {
System.out.printf("%n======== Player %d - Coloca tus barcos ========%n", id);
tablero.colocaBarcosTablero();
}
public void colocaBarcos2() {
System.out.printf("%n======== Player %d - Coloca tus barcos ========%n", id);
tablero.colocaBarcosTablero2();
}
#Override
public void dispararA(IPlayer opponent) {
System.out.printf("%n Bien player %d - Introduce las coordenadas de tu ataque: ", id);
boolean esPuntoValido = false;
while(!esPuntoValido) {
try {
Point point = new Point(scanner.nextInt(), scanner.nextInt());
int x = (int)point.getX() - 1;
int y = (int)point.getY() - 1;
Resultado resultado = ((HumanPlayer)opponent)
.getTablero()
.getField(x, y)
.dispararA();
if(resultado == Resultado.PARCIAL_GOLPE || resultado == Resultado.DESTRUIDO) {
totalVidas--;
}
esPuntoValido = true;
}
catch(IllegalArgumentException e) {
System.out.printf(e.getMessage());
}
}
}
#Override
public int getVidasRestantes() {
return totalVidas;
}
}
public interface IGameField {
char getIcon();
Resultado dispararA();
}
public interface IPlayer {
void colocaBarcos();
void dispararA(IPlayer opponent);
int getVidasRestantes();
}
public enum Resultado {
NO_GOLPE,
PARCIAL_GOLPE,
DESTRUIDO
}
public class Tablero {
private static final char AGUA = '~';
private static final int TABLERO_SIZE = 10;
private static final char[] TABLERO_LETRAS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
private static final String HORIZONTAL = "H";
private static final String VERTICAL = "V";
private static final String HORIZONTAL2 = "h";
private static final String VERTICAL2 = "v";
private Scanner scanner;
private IGameField[][] tablero;
private static final Barco[] barcos;
static {
barcos = new Barco[]{
new Barco("Carrier", BarcoTamaño.CARRIER),
new Barco("Battleship1", BarcoTamaño.BATTLESHIP),
new Barco("Battleship2", BarcoTamaño.BATTLESHIP),
new Barco("Cruiser1", BarcoTamaño.CRUISER),
new Barco("Cruiser2", BarcoTamaño.CRUISER),
new Barco("Cruiser3", BarcoTamaño.CRUISER),
new Barco("Destroyer", BarcoTamaño.DESTROYER),
new Barco("Destroyer", BarcoTamaño.DESTROYER),
new Barco("Destroyer", BarcoTamaño.DESTROYER),
new Barco("Destroyer", BarcoTamaño.DESTROYER)
};
}
public void escogerBarco(){
System.out.println("Que barco quieres introducir? ");
String barcoEscogido = scanner.nextLine();
if (barcoEscogido == "Carrier"){
new Barco("Carrier", BarcoTamaño.CARRIER);
}
}
public Tablero() {
this.scanner = new Scanner(System.in);
this.tablero = new IGameField[TABLERO_SIZE][TABLERO_SIZE];
for(int i = 0; i < TABLERO_SIZE; i++) {
for(int j = 0; j < TABLERO_SIZE; j++) {
tablero[i][j] = new AguaField();
}
}
}
public void colocaBarcosTablero() {
for(Barco ship : barcos) {
boolean horizontal = preguntaDireccionValida();
Point puntoInicio = preguntaPuntoInicio(ship, horizontal);
colocaBarcoValido(ship, puntoInicio, horizontal);
printTablero();
}
}
public void colocaBarcosTablero2() {
for(Barco ship2 : barcos) {
boolean horizontal2 = preguntaDireccionValida2();
Point puntoInicio2 = preguntaPuntoInicio2(ship2, horizontal2);
colocaBarcoValido(ship2, puntoInicio2, horizontal2);
printTablero();
}
}
public IGameField getField(int x, int y) {
if(!dentroTablero(x, y)) {
throw new IllegalArgumentException("Fuera del trablero - intenta de nuevo: ");
}
return tablero[y][x];
}
public void printTablero() {
System.out.print("\t");
for(int i = 0; i < TABLERO_SIZE; i++) {
System.out.print(TABLERO_LETRAS[i] + "\t");
}
System.out.println();
for(int i = 0; i < TABLERO_SIZE; i++) {
System.out.print((i+1) + "\t");
for(int j = 0; j < TABLERO_SIZE; j++) {
System.out.print(tablero[i][j].getIcon() + "\t");
}
System.out.println();
}
}
private boolean preguntaDireccionValida() {
System.out.printf("%nQuieres introducir el barco horizontalmente (H) o verticalmente (V)?");
String direccion;
do {
direccion = scanner.nextLine().trim();
}while (!HORIZONTAL.equals(direccion) && !VERTICAL.equals(direccion));
return HORIZONTAL.equals(direccion);
}
private boolean preguntaDireccionValida2() {
System.out.printf("%nQuieres introducir el barco horizontalmente (H) o verticalmente (V)?");
String direccion = "HV";
Random aleatorio = new Random();
do {
direccion.charAt(aleatorio.nextInt(direccion.length()));
}while (!HORIZONTAL2.equals(direccion) && !VERTICAL2.equals(direccion));
return HORIZONTAL.equals(direccion);
}
private Point preguntaPuntoInicio(Barco ship, boolean horizontal) {
Point from;
do{
System.out.printf("%nIntroduce la posicion de %s (tamaño %d): ", ship.getNombre(), ship.getTamaño());
from = new Point(scanner.nextInt(), scanner.nextInt());
}while(!esPuntoInicioValido(from, ship.getTamaño(), horizontal));
return from;
}
private Point preguntaPuntoInicio2(Barco ship, boolean horizontal) {
Random random2 = new Random();
Point from2;
do{
from2 = new Point(random2.nextInt(10), random2.nextInt(10));
}while(!esPuntoInicioValido(from2, ship.getTamaño(), horizontal));
return from2;
}
private boolean esPuntoInicioValido(Point from, int longitud, boolean horizontal) {
int xDiff = 0;
int yDiff = 0;
if(horizontal) {
xDiff = 1;
}
else {
yDiff = 1;
}
int x = (int)from.getX() - 1;
int y = (int)from.getY() - 1;
if(!dentroTablero(x, y) || (!dentroTablero(x + longitud,y) && horizontal) || (!dentroTablero(x, y + longitud) && !horizontal)){
return false;
}
for(int i = 0; i < longitud; i++) {
if(tablero[(int)from.getY() + i *yDiff - 1]
[(int)from.getX() + i *xDiff - 1].getIcon() != AGUA){
return false;
}
}
return true;
}
private boolean dentroTablero(int x, int y){
return x <= TABLERO_SIZE && x >= 0 && y <= TABLERO_SIZE && y >= 0;}
private void colocaBarcoValido(Barco ship, Point puntoInicio, boolean horizontal) {
int xDiff = 0;
int yDiff = 0;
if(horizontal) {
xDiff = 1;
}
else {
yDiff = 1;
}
for(int i = 0; i < ship.getTamaño() ; i++) {
tablero[(int)puntoInicio.getY() + i*yDiff - 1]
[(int)puntoInicio.getX()+ i*xDiff - 1] = new BarcoField(ship);
}
}
}
The thing is that I got stuck and I don't know how to continue. Sorry for my bad English and if I placed this wrong, it is my first time using stackoverflow!
Hello I'm fairly new to programming and this is my first time posting here so any help would be appreciated so:
my problem is that I"m trying to create some kind of 2D shooter game in java but I don't know if my simple game loop is good because when i shoot a missile it shoots a one every 20 ms and it's too fast and shoots a ton of missiles at once so is there any way to adjust it ? Like to keep some delay between every missile and the other??
and please tell me if i have problems or bad programming in my code !!
this is my game panel where most of the game happens and where my loop and adding missiles method in
public class GamePanel extends JPanel implements KeyListener {
Measurments mesure = new Measurments();
int panel_width = mesure.getUniversalWidth();
int panel_height = mesure.getUniversalHeight();
Timer timer;
Random rand = new Random();
ArrayList<Enemy> enemies = new ArrayList<>();
ArrayList<Missile> missiles = new ArrayList<>();
Player player = new Player(0, 0);
boolean up = false;
boolean down = false;
boolean right = false;
boolean left = false;
boolean isShooting = false;
boolean isRunning = true;
public boolean gameRunning() {
return isRunning;
}
int count = 5;
int missilesCount = 6;
public GamePanel() {
timer = new Timer(20, new ActionListener() {
public void actionPerformed(ActionEvent e) {
StartGame();
repaint();
}
});
setSize(panel_width, panel_height);
addKeyListener(this);
timer.start();
for (int i = 0; i < count; i++) {
addEnemy(new Enemy(rand.nextInt(750), rand.nextInt(500)));
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
player.paint(g2d);
for (int i = 0; i < enemies.size(); i++) {
Enemy temp = enemies.get(i);
temp.paint(g2d);
}
for (int i = 0; i < missiles.size(); i++) {
Missile mis = missiles.get(i);
mis.paint(g2d);
mis.behave();
}
}
public void StartGame() {
if (isRunning) {
runGame();
setBackground(Color.YELLOW);
} else {
setBackground(Color.BLACK);
}
}
public void runGame() {
update();
};
public void update() {
player.checkBorders();
checkColls();
if (up) {
player.updateUp();
}
if (down) {
player.updateDown();
}
if (right) {
player.updateRight();
}
if (left) {
player.updateLeft();
}
if (isShooting) {
for (int i = 0; i < 5; i++) {
missiles.add(new Missile(player.getX() + 16, player.getY() + 16));
}
}
for (int i = 0; i < missiles.size(); i++) {
Missile temp = missiles.get(i);
if (temp.getX() == panel_width) {
RemoveMissile(temp);
}
}
}
public void addEnemy(Enemy e) {
enemies.add(e);
}
public void removeEnemy(Enemy e) {
enemies.remove(e);
}
public void addMissile(Missile e) {
missiles.add(e);
}
public void RemoveMissile(Missile e) {
missiles.add(e);
}
public void checkColls() {
for (int i = 0; i < enemies.size(); i++) {
Enemy tempEnm = enemies.get(i);
for (int e = 0; e < missiles.size(); e++) {
Missile tempMis = missiles.get(e);
if (tempMis.missileRect().intersects(tempEnm.enemyRect())) {
enemies.remove(tempEnm);
missiles.remove(tempMis);
}
}
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == e.VK_UP) {
up = true;
}
if (key == e.VK_DOWN) {
down = true;
}
if (key == e.VK_RIGHT) {
right = true;
}
if (key == e.VK_LEFT) {
left = true;
}
if (key == e.VK_ENTER) {
isRunning = true;
}
if (key == e.VK_SPACE) {
isShooting = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == e.VK_UP) {
up = false;
}
if (key == e.VK_DOWN) {
down = false;
}
if (key == e.VK_RIGHT) {
right = false;
}
if (key == e.VK_LEFT) {
left = false;
}
if (key == e.VK_SPACE) {
isShooting = false;
}
}
public void keyTyped(KeyEvent e) {
}
}
Thanks in advance !!
private long fired = 0L;
public void update() {
...
// firing missiles: only if the missile count is less than the max., and the elapsed
// time is more than a limit (100 ms)
if ( isShooting && missiles.size() < missilesCount &&
( System.currentTimeMilis() - this.fired ) > 100 ) {
missiles.add( new Missile( player.getX() + 16, player.getY() + 16 ) );
// time of last firing
this.fired = System.currentTimeMilis();
}
...
}
public void RemoveMissile(Missile e) {
// as Guest is asked in another answer, this method should remove, not add...
missiles.remove(e);
}
So I've been working on this chess app for about a week now (a few hours a day)-- and I seem to have hit a snag. All of the pieces move as they should, with collision and all-- I have promotion and castling working, and I can successfully check for being in check.
However, I can't seem to check if a move legally gets out of check. My current approach is to move the piece-- check if the person is still in check, and if not then the move is legal.
It seems that when I do this, however, it doesn't correctly calculate the check after the faux-move.
Any help would be great.
public abstract class Piece {
private Type type = Type.BLANK;
private int locX, locY, preX, preY;
private Player player;
private boolean moved = false;
Piece(Type type, int locX, int locY, Player player) {
this.locX = locX;
this.locY = locY;
this.player = player;
this.type = type;
}
public void movePiece(int x, int y) {
if (player.isTurn()) {
if (isLegalMove(x, y)) {
if (checkCollision(x, y)) {
if (clearsCheck(x, y)) {
preX = locX;
preY = locY;
setLoc(x, y);
specialPreMove(x, y);
moved = true;
Chess.chessBoard.bitBoard[preX][preY] = null;
if (Chess.chessBoard.bitBoard[x][y] != null) {
Chess.chessBoard.bitBoard[x][y].getPlayer().pieces.remove(Chess.chessBoard.bitBoard[x][y]);
}
Chess.chessBoard.bitBoard[x][y] = this;
specialPostMove(x, y);
Chess.chessBoard.getGui().repaint();
Chess.changeTurns();
}
}
}
}
}
protected void specialPreMove(int x, int y) {}
protected void specialPostMove(int x, int y) {}
protected abstract boolean checkCollision(int x, int y);
protected abstract boolean isLegalMove(int x, int y);
private boolean clearsCheck(int x, int y) {
boolean checkCk = false;
preX = locX;
preY = locY;
setLoc(x, y);
Piece locPiece = null;
Chess.chessBoard.bitBoard[preX][preY] = null;
if (Chess.chessBoard.bitBoard[x][y] != null) {
locPiece = Chess.chessBoard.bitBoard[x][y];
Chess.chessBoard.bitBoard[x][y].getPlayer().pieces.remove(Chess.chessBoard.bitBoard[x][y]);
System.out.println("Piece there: " + locPiece);
}
Chess.chessBoard.bitBoard[x][y] = this;
System.out.println(Chess.chessBoard.bitBoard[x][y]);
Chess.chessBoard.getGui().repaint();
Chess.checkCheck();
checkCk = !player.inCheck();
setLoc(preX, preY);
Chess.chessBoard.bitBoard[preX][preY] = this;
if (locPiece != null) {
Chess.chessBoard.bitBoard[x][y] = locPiece;
Chess.chessBoard.bitBoard[x][y].getPlayer().pieces.add(Chess.chessBoard.bitBoard[x][y]);
} else {
Chess.chessBoard.bitBoard[x][y] = null;
}
System.out.println(checkCk);
return checkCk;
}
public ArrayList<Move> getLegalMoves() {
ArrayList<Move> moves = new ArrayList<Move>();
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (isLegalMove(row, col) && checkCollision(row, col)) {
moves.add(new Move(row, col));
}
}
}
return moves;
}
is the piece class, and then the check method
public static void checkCheck() {
for (Move m : player1.getLegalMoves()) {
if (m.getX() == player2.getKing().getLocX()
&& m.getY() == player2.getKing().getLocY()) {
player2.setCheck(true);
System.out.println("IN CHECK PLAYER 2");
break;
}
}
for (Move m : player2.getLegalMoves()) {
if (m.getX() == player1.getKing().getLocX()
&& m.getY() == player1.getKing().getLocY()) {
player1.setCheck(true);
System.out.println("IN CHECK PLAYER 1");
break;
}
}
}
and then here is some other stuff that is useful
public class Player {
private Color color;
private Direction direction;
private boolean turn;
private boolean check = false;
public ArrayList<Piece> pieces = new ArrayList<>();
public Player(Color color, Direction direction) {
this.color = color;
this.turn = false;
this.direction = direction;
}
public ArrayList<Move> getLegalMoves() {
ArrayList<Move> moves = new ArrayList<>();
for (Piece p : pieces) {
for (Move m : p.getLegalMoves()) {
moves.add(m);
}
}
return moves;
}
public Piece getKing() {
for (Piece p : pieces) {
if (p.getType() == Type.KING) {
return p;
}
}
return null;
}
Looks like once you set a player in check you're not setting his status later on to unchecked.
public static void checkCheck() {
boolean isInCheck = false;
for (Move m : player1.getLegalMoves()) {
if (m.getX() == player2.getKing().getLocX()
&& m.getY() == player2.getKing().getLocY()) {
isInCheck = true;
System.out.println("IN CHECK PLAYER 2");
break;
}
}
player2.setCheck(isInCheck);
isInCheck = false;
for (Move m : player2.getLegalMoves()) {
if (m.getX() == player1.getKing().getLocX()
&& m.getY() == player1.getKing().getLocY()) {
isInCheck = true;
System.out.println("IN CHECK PLAYER 1");
break;
}
}
player1.setCheck(isInCheck);
}
This question already has answers here:
How to change JFrame icon [duplicate]
(8 answers)
Closed 6 years ago.
How do I add an icon to this snake game and where do I put it, also how do I increase speed of the game after so many points? The code below is the class in which I believe these two pieces of code should go.
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class SnakeGame extends JFrame {
private static final long FRAME_TIME = 1000L / 50L;
private static final int MIN_SNAKE_LENGTH = 5;
private static final int MAX_DIRECTIONS = 3;
private BoardPanel board;
private SidePanel side;
private Random random;
private Clock logicTimer;
private boolean isNewGame;
private boolean isGameOver;
private boolean isPaused;
private LinkedList<Point> snake;
private LinkedList<Direction> directions;
private int score;
private int foodsEaten;
private int nextFoodScore;
private SnakeGame() {
super("Snake");
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
this.board = new BoardPanel(this);
this.side = new SidePanel(this);
add(board, BorderLayout.CENTER);
add(side, BorderLayout.EAST);
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_W:
case KeyEvent.VK_UP:
if(!isPaused && !isGameOver) {
if(directions.size() < MAX_DIRECTIONS) {
Direction last = directions.peekLast();
if(last != Direction.South && last != Direction.North) {
directions.addLast(Direction.North);
}
}
}
break;
case KeyEvent.VK_S:
case KeyEvent.VK_DOWN:
if(!isPaused && !isGameOver) {
if(directions.size() < MAX_DIRECTIONS) {
Direction last = directions.peekLast();
if(last != Direction.North && last != Direction.South) {
directions.addLast(Direction.South);
}
}
}
break;
case KeyEvent.VK_A:
case KeyEvent.VK_LEFT:
if(!isPaused && !isGameOver) {
if(directions.size() < MAX_DIRECTIONS) {
Direction last = directions.peekLast();
if(last != Direction.East && last != Direction.West) {
directions.addLast(Direction.West);
}
}
}
break;
case KeyEvent.VK_D:
case KeyEvent.VK_RIGHT:
if(!isPaused && !isGameOver) {
if(directions.size() < MAX_DIRECTIONS) {
Direction last = directions.peekLast();
if(last != Direction.West && last != Direction.East) {
directions.addLast(Direction.East);
}
}
}
break;
case KeyEvent.VK_P:
if(!isGameOver) {
isPaused = !isPaused;
logicTimer.setPaused(isPaused);
}
break;
case KeyEvent.VK_ENTER:
if(isNewGame || isGameOver) {
resetGame();
}
break;
}
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void startGame() {
this.random = new Random();
this.snake = new LinkedList<>();
this.directions = new LinkedList<>();
this.logicTimer = new Clock(10.0f);
//////////////////////////////////////////////////////////////////////////////////////////////////
this.isNewGame = true;
logicTimer.setPaused(true);
while(true) {
long start = System.nanoTime();
logicTimer.update();
if(logicTimer.hasElapsedCycle()) {
updateGame();
}
board.repaint();
side.repaint();
long delta = (System.nanoTime() - start) / 1000000L;
if(delta < FRAME_TIME) {
try {
Thread.sleep(FRAME_TIME - delta);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
private void updateGame() {
TileType collision = updateSnake();
if(collision == TileType.Food) {
foodsEaten++;
score += nextFoodScore;
spawnFood();
} else if(collision == TileType.SnakeBody) {
isGameOver = true;
logicTimer.setPaused(true);
} else if(nextFoodScore > 10) {
}
}
private TileType updateSnake() {
Direction direction = directions.peekFirst();
Point head = new Point(snake.peekFirst());
switch(direction) {
case North:
head.y--;
break;
case South:
head.y++;
break;
case West:
head.x--;
break;
case East:
head.x++;
break;
}
if(head.x < 0 || head.x >= BoardPanel.COL_COUNT || head.y < 0 || head.y >= BoardPanel.ROW_COUNT) {
return TileType.SnakeBody;
}
TileType old = board.getTile(head.x, head.y);
if(old != TileType.Food && snake.size() > MIN_SNAKE_LENGTH) {
Point tail = snake.removeLast();
board.setTile(tail, null);
old = board.getTile(head.x, head.y);
}
if(old != TileType.SnakeBody) {
board.setTile(snake.peekFirst(), TileType.SnakeBody);
snake.push(head);
board.setTile(head, TileType.SnakeHead);
if(directions.size() > 1) {
directions.poll();
}
}
return old;
}
private void resetGame() {
this.score = 0;
this.foodsEaten = 0;
this.isNewGame = false;
this.isGameOver = false;
Point head = new Point(BoardPanel.COL_COUNT / 2, BoardPanel.ROW_COUNT / 2);
snake.clear();
snake.add(head);
board.clearBoard();
board.setTile(head, TileType.SnakeHead);
directions.clear();
directions.add(Direction.North);
logicTimer.reset();
spawnFood();
}
public boolean isNewGame() {
return isNewGame;
}
public boolean isGameOver() {
return isGameOver;
}
public boolean isPaused() {
return isPaused;
}
private void spawnFood() {
this.nextFoodScore = 10;
int index = random.nextInt(BoardPanel.COL_COUNT * BoardPanel.ROW_COUNT - snake.size());
int freeFound = -1;
for(int x = 0; x < BoardPanel.COL_COUNT; x++) {
for(int y = 0; y < BoardPanel.ROW_COUNT; y++) {
TileType type = board.getTile(x, y);
if(type == null || type == TileType.Food) {
if(++freeFound == index) {
board.setTile(x, y, TileType.Food);
break;
}
}
}
}
}
public int getScore() {
return score;
}
public int getFoodsEaten() {
return foodsEaten;
}
public int getNextFoodScore() {
return nextFoodScore;
}
public Direction getDirection() {
return directions.peek();
}
public static void main(String[] args) {
SnakeGame snake = new SnakeGame();
snake.startGame();
}
}
Create a new ImageIcon object like this:
ImageIcon img = new ImageIcon(pathToFileOnDisk);
Then set it to your JFrame with setIconImage():
myFrame.setIconImage(img.getImage());
Also checkout setIconImages() which takes a List instead.
How to change JFrame icon
It 's not my answer !!!!