java game development restricted number randomly objects - java

Im creating a game. I need to create objects randomly but i want them to come in a certain number. Here is my main class code for randomly created object
private void randomTiles() {
int randomXtile = new Random().nextInt(9500) + 20;
int randomYtile = new Random().nextInt(12) + 0;
Tile t = new Tile(randomXtile, randomYtile, 3);
tilearray.add(t);
}
private void updateTiles() {
randomTiles();
for (int i = 0; i < tilearray.size(); i++) {
Tile t = (Tile) tilearray.get(i);
t.update();
}
}
private void paintTiles(Graphics g) {
for (int i = 0; i < tilearray.size(); i++) {
Tile t = (Tile) tilearray.get(i);
g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY(), this);
}
}
tile constructor is
public Tile(int x, int y, int typeInt) {
tileX = x * 40;
tileY = y * 40;
type = typeInt;
r = new Rectangle();
if (type == 5) {
tileImage = StartingClass.tiledirt;
} else if (type == 8) {
tileImage = StartingClass.tilegrassTop;
} else if (type == 4) {
tileImage = StartingClass.tilegrassLeft;
} else if (type == 6) {
tileImage = StartingClass.tilegrassRight;
} else if (type == 2) {
tileImage = StartingClass.tilegrassBot;
} else if (type == 3) {
tileImage = StartingClass.ice;
hp = 2;
} else {
type = 0;
}
}
and somewhere in my game object should come at certain coordinates. Can you help me about this ?

Related

How do I make resizing images while displaying my screen not be inefficient in processing.core (PApplet)

I am new to coding and don't really know what I am doing. I know that there my code is pretty inefficient and I could probably fix it later (i.e. collision and movement), but I have what I think is an efficient map setup. It only renders what is either around the camera or is around the player based on the camera type (freeRoam vs placerCentered). This works and runs fine until I start to resize pictures when I zoom in and out my map. I think that every time I draw a resized image my computer resizes it and then draws it for every instance of it rather than resizing it once and drawing it. Would I have to make images for every instance of zooming in or out or is there an optimized resizing tool that I am missing?
Google Drive link with images if anyone is interested: https://drive.google.com/drive/folders/1s5_9YPX7_6QWaxZPexN7pWk8zgmaT0w5?usp=sharing
(All images are 20 x 20 I think besides warrior1 and stoneTile1 which are both 32 x 32)
import processing.core.*;
import processing.event.MouseEvent;
import java.util.*;
public class Dungeon1 extends PApplet implements MyLibrary {
static gameState currentState;
static cameraState currentCameraState = cameraState.playerCentered;
enum gameState {
Over, Running
}
enum cameraState {
freeRoam, playerCentered
}
int cameraScaling = 20;
PImage testBoots;
PImage clown;
PImage testSquare;
PImage stoneTile1;
PImage resizedTile;
PImage warrior1;
float enemyX = 10;
float enemyY = 10;
float redSquare;
int currentXPos = 10;
int currentYPos = 10;
int tileType;
int mapWidth = 500;
int mapHeight = 500;
int[][] squareType = new int[mapHeight][mapWidth];
boolean movingUp, movingDown, movingLeft, movingRight;
int squareX;
int squareY;
boolean canMoveUp, canMoveDown, canMoveLeft, canMoveRight = true;
int cameraX = currentXPos;
int cameraY = currentYPos;
int lastCameraX;
int lastCameraY;
boolean centerCamera = false;
int pastMouseXPosition;
int pastMouseYPosition;
int squareWidth;
int squareHeight;
boolean mouseDragging = true, freeRoam, playerCentered;
public static void main(String[] args) {
PApplet.main("Dungeon1");
}
public void settings() {
fullScreen();
}
public void setup() {
playerStartPos();
createMap();
currentState = gameState.Running;
testBoots = loadImage("Images/TestBoots.png");
clown = loadImage("Images/clown.png");
testSquare = loadImage("Images/testSquare.png");
stoneTile1 = loadImage("Images/stoneTile1.png");
resizedTile = loadImage("Images/resizedTile.png");
warrior1 = loadImage("Images/warrior1.png");
}
public void draw() {
background(0, 0, 0);
drawMap();
isMoving();
}
public void keyPressed() {
if (key == 'w') {
movingUp = true;
}
if (key == 's') {
movingDown = true;
}
if (key == 'a') {
movingLeft = true;
}
if (key == 'd') {
movingRight = true;
}
if (key == 'k') {
Test = true;
}
if (key == 'c') {
currentCameraState = cameraState.playerCentered;
centerCamera = true;
}
if (key == 'v') {
currentCameraState = cameraState.freeRoam;
}
if (key == 'b') {
currentCameraState = cameraState.playerCentered;
}
}
public void keyReleased() {
if (key == 'w') {
movingUp = false;
}
if (key == 's') {
movingDown = false;
}
if (key == 'a') {
movingLeft = false;
}
if (key == 'd') {
movingRight = false;
}
if (key == 'k') {
Test = false;
}
}
public void mouseDragged(MouseEvent e) {
if (pastMouseXPosition < mouseX) {
lastCameraX--;
}
if (pastMouseXPosition > mouseX) {
lastCameraX++;
}
if (pastMouseYPosition < mouseY) {
lastCameraY--;
}
if (pastMouseYPosition > mouseY) {
lastCameraY++;
}
pastMouseXPosition = mouseX;
pastMouseYPosition = mouseY;
}
public void mousePressed() {
currentCameraState = cameraState.freeRoam;
mouseDragging = true;
pastMouseXPosition = mouseX;
pastMouseYPosition = mouseY;
}
public void mouseReleased() {
mouseDragging = false;
}
public void mouseWheel(MouseEvent e) {
if (e.getAmount() < 0) {
cameraScaling--;
} else {
cameraScaling++;
}
}
public void isMoving() {
if (movingUp) {
if (canMoveUp) {
currentYPos--;
cameraY--;
}
if (squareType[currentXPos][currentYPos] == 2) {
currentYPos++;
canMoveUp = false;
cameraY++;
}
}
if (movingDown) {
if (canMoveDown) {
currentYPos++;
cameraY++;
}
if (squareType[currentXPos][currentYPos] == 2) {
currentYPos--;
canMoveDown = false;
cameraY--;
}
}
if (movingRight) {
if (canMoveRight) {
currentXPos++;
cameraX++;
}
if (squareType[currentXPos][currentYPos] == 2) {
currentXPos--;
canMoveRight = false;
cameraX--;
}
}
if (movingLeft) {
if (canMoveLeft) {
currentXPos--;
cameraX--;
}
if (squareType[currentXPos][currentYPos] == 2) {
currentXPos++;
canMoveLeft = false;
cameraX++;
}
}
if (squareType[currentXPos][currentYPos] != 2) {
drawPlayer();
canMoveUp = true;
canMoveLeft = true;
canMoveDown = true;
canMoveRight = true;
}
}
public void playerStartPos() {
currentXPos = 96/2;
currentYPos = 54/2;
}
public void drawPlayer() {
if (currentCameraState == cameraState.playerCentered) {
image(testSquare, (currentXPos * cameraScaling - cameraX * cameraScaling), (currentYPos * cameraScaling - cameraY * cameraScaling), cameraScaling, cameraScaling);
} else if (currentCameraState == cameraState.freeRoam) {
image(testSquare, (currentXPos * cameraScaling - lastCameraX * cameraScaling), (currentYPos * cameraScaling - lastCameraY * cameraScaling), cameraScaling, cameraScaling);
}
}
public void createMap() {
//First creates the plane to navigate
for (int r = 0; r < mapHeight; r++) {
for (int c = 0; c < mapWidth; c++) {
redSquare = generator.nextInt(100);
if (redSquare > 90) {
tileType = 2;
} else {
tileType = 0;
}
squareType[r][c] = tileType;
}
}
}
public void drawMap() {
//TODO: Either figure out how to make actual scaled images not run poorly or make a bunch of images that only are displayed a scaled resolution
if (cameraScaling < 15) {
cameraScaling = 15;
}
if (cameraScaling > 50) {
cameraScaling = 50;
}
if (centerCamera) {
cameraX = currentXPos - 47*20/ cameraScaling;
cameraY = currentYPos - 23*20/ cameraScaling;
}
squareWidth = 20+ cameraScaling;
squareHeight = 20+ cameraScaling;
centerCamera = false;
if (currentCameraState == cameraState.freeRoam) {
cameraX = lastCameraX;
cameraY = lastCameraY;
for (int r = lastCameraX; r < lastCameraX + 96*20/ cameraScaling + 2 ; r++) {
for (int c = lastCameraY; c < lastCameraY + 54*20/ cameraScaling + 2; c++) {
squareX = r * cameraScaling - lastCameraX * cameraScaling;
squareY = c * cameraScaling - lastCameraY * cameraScaling;
if (r > 0 && c > 0 && r < mapWidth && c < mapHeight) {
if (squareType[r][c] == 0) {
image(resizedTile, squareX, squareY, cameraScaling, cameraScaling);
} else {
colorTiles(r, c);
rect(squareX, squareY, cameraScaling, cameraScaling);
}
}
}
}
} else if (currentCameraState == cameraState.playerCentered) {
lastCameraX = cameraX;
lastCameraY = cameraY;
for (int r = cameraX; r < cameraX + 96*20/ cameraScaling + 2; r++) {
for (int c = cameraY; c < cameraY + 54*20/ cameraScaling + 2; c++) {
squareX = r * cameraScaling - cameraX * cameraScaling;
squareY = c * cameraScaling - cameraY * cameraScaling;
if (r > 0 && c > 0 && r < mapWidth && c < mapHeight) {
if (squareType[r][c] == 0) {
image(resizedTile, squareX, squareY, cameraScaling, cameraScaling);
} else {
colorTiles(r, c);
rect(squareX, squareY, cameraScaling, cameraScaling);
}
}
}
}
}
}
public void colorTiles(int r, int c) {
if (squareType[r][c] == 2) {
fill(255, 0, 0);
}
}
}```

Rotating game in JPanel

I created a very simple shooting game utilizing JPanel as shown in the code below. I also wanted to experiment with rotating the game and trying it out. I have one issue, where the game I was able to successfully rotate the game but the dimension seems to cut out, and I have to set each position of the enemy and myself to the rotated position.
I was wondering if there was a way to rotate the result as a whole, instead of simply rotating the shape so that the position of the ship and the missiles would also rotate all at once.
Edited code: added three lives to the player and tried implementing heart image with BufferedImage.
public class game extends JFrame{
public game(){
}
public static void main(String[] args){
new game();
}
public class MyJPanel extends JPanel implements ActionListener, MouseListener,
MouseMotionListener,KeyListener
{
//variables for player
int my_x;
int player_width,player_height;
private int lives = 3;
int heart_width, heart_height;
//variables for player's missiles
int my_missile_x, my_missile_y;
int missile_flag;
public static final int MY_Y = 600;
//variables for enemies' missiles
int e_missile_flag[];
int e_missile_x[];
int e_missile_y[];
int e_missile_move[];
Image image,image2;
Timer timer;
private BufferedImage heart;
public MyJPanel(){
missile_flag = 0;
/*** initialize enemies' info ***/
ImageIcon icon2 = new ImageIcon("enemy.jpg");
image2 = icon2.getImage();
enemy_width = image2.getWidth(this);
enemy_height = image2.getHeight(this);
try {
heart = ImageIO.read(getClass().getResource("heart.jpg"));
}catch(IOException e) {
}
heart_width = heart.getWidth(this);
heart_height = heart.getHeight(this);
n = 14; //number of enemies
enemy_x = new int[n];
enemy_y = new int[n];
enemy_move = new int[n];
enemy_alive = new int[n];
int distance = 40;
e_missile_flag = new int[n];
e_missile_x = new int[n];
e_missile_y = new int[n];
e_missile_move = new int[n];
// place enemies in 7x2
for (int i = 0; i < 7; i++) {
enemy_x[i] = (enemy_width + distance) * i + 50;
enemy_y[i] = 50;
}
for (int i = 7; i < n; i++) {
enemy_x[i] = (enemy_width + distance) * (i - 5) + 50;
enemy_y[i] = 100;
}
for (int i = 0; i < n; i++) {
enemy_alive[i] = 1; //all alive
enemy_move[i] = -10; //moves to left
}
for (int i = 0; i < n; i++) {
e_missile_flag[i] = 0;
e_missile_x[i] = 0;
e_missile_y[i] = 0;
e_missile_move[i] = 7 + n%3;
}
/*** setup system ***/
setBackground(Color.black);
setFocusable(true);
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
timer = new Timer(50, this);
timer.start();
}
private void updateEnemiesPosition(){
//update enemies' position
Dimension dim = getSize();
for (int i = 0; i < n; i++) {
enemy_x[i] += enemy_move[i];
if ((enemy_x[i] < 0) || (enemy_x[i] > (dim.width - enemy_width))) {
enemy_move[i] = -enemy_move[i];
}
}
}
private void updateMyPosition() {
if(my_x < 0) {
my_x = 800;
}
if(my_x > 800) {
my_x = 0;
}
}
private void activateMyMissile(){
//shoot a missile
if(missile_flag == 0){
my_missile_x = my_x + player_width / 2;
my_missile_y = MY_Y; //MY_Y=400
missile_flag = 1;
}
}
private void updateMyMissile(){
//update missile position if alive
if (missile_flag == 1) {
my_missile_y -= 15;
if (0 > my_missile_y) {
missile_flag = 0;
}
}
}
private void activateEnemiesMissile(){
//activate enemies' missile if enemy is alive and its missile is not alive
for(int i = 0; i < n; i++){
if (enemy_alive[i] == 1 && e_missile_flag[i] == 0) {
e_missile_x[i] = enemy_x[i] + enemy_width/2;
e_missile_y[i] = enemy_y[i];
e_missile_flag[i] = 1;
}
}
}
private void updateEnemiesMissile(){
//update enemies' missile position if alive
Dimension dim = getSize();
for(int i = 0; i < n; i++){
if (e_missile_flag[i] == 1) {
e_missile_y[i] += e_missile_move[i];
if (e_missile_y[i] > dim.height) {
e_missile_flag[i] = 0;
}
}
}
}
private void checkHitToEnemy(){
for(int i = 0; i < n; i++){
if(missile_flag == 1 && enemy_alive[i] == 1){
if(
my_missile_x > enemy_x[i] &&
my_missile_x < (enemy_x[i] + enemy_width) &&
my_missile_y > enemy_y[i] &&
my_missile_y < (enemy_y[i] + enemy_height)
){
//hit
missile_flag = 0;
enemy_alive[i] = 0;
}
}
}
}
private boolean checkClear(){
int cnt = 0;
for(int i = 0; i < n; i++){
if(enemy_alive[i] == 0) cnt++;
}
return (n == cnt);
}
if(lives>0) {
int x = 0;
int y = getHeight()- heart.getHeight();
for(int index = 0; index < lives; index++) {
g.drawImage(heart, x, y, this);
x += heart.getWidth();
}
}
g2d.dispose();
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == timer) {
updateEnemiesPosition();
updateMyPosition();
updateMyMissile();
updateEnemiesMissile();
activateEnemiesMissile();
if(checkHitToPlayer()){
System.out.println("===== Game Over =====");
System.exit(0);
}
checkHitToEnemy();
if(checkClear()){
System.out.println("===== Game Clear =====");
System.exit(0);
}
repaint();
}
}
public void mouseClicked(MouseEvent me)
{ }
public void mousePressed(MouseEvent me)
{
activateMyMissile();
}
public void mouseReleased(MouseEvent me)
{ }
public void mouseExited(MouseEvent me)
{ }
public void mouseEntered(MouseEvent me)
{ }
public void mouseMoved(MouseEvent me)
{ }
public void mouseDragged(MouseEvent me)
{ }
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
}
}
The original size of the component is going to be less then 800x500 (I say less then, because the actual size will be 800x500 - the frame decorations - this is why you should be setting the size of the window directly).
When you rotate it 90 degrees, it becomes (less then) 500x800. So, no, there's no "easy" way to resolve this, without making the game square.
I added...
g2d.setColor(Color.DARK_GRAY);
g2d.fillRect(0, 0, getWidth(), getHeight());
after the rotation, which highlights the issue.
To do this, you should override getPreferredSize of the JPanel and the call pack on the frame. This will ensure that that game canvas is sized to it's preferred size and the window decorations are then packed around it.
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Lec12 extends JFrame {
public Lec12() {
setTitle("Game Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
MyJPanel myJPanel = new MyJPanel();
Container c = getContentPane();
c.add(myJPanel);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Lec12();
}
public class MyJPanel extends JPanel implements ActionListener, MouseListener,
MouseMotionListener, KeyListener {
//variables for player
int my_x;
int player_width, player_height;
//variables for enemies
int enemy_width, enemy_height;
int n;
int enemy_x[];
int enemy_y[];
int enemy_move[];
int enemy_alive[];
//variables for player's missiles
int my_missile_x, my_missile_y;
int missile_flag;
public static final int MY_Y = 400;
//variables for enemies' missiles
int e_missile_flag[];
int e_missile_x[];
int e_missile_y[];
int e_missile_move[];
Image image, image2;
Timer timer;
public MyJPanel() {
/**
* * initialize player's info **
*/
my_x = 250;
ImageIcon icon = new ImageIcon("player.jpg");
image = icon.getImage();
player_width = image.getWidth(this);
player_height = image.getHeight(this);
missile_flag = 0;
/**
* * initialize enemies' info **
*/
ImageIcon icon2 = new ImageIcon("enemy.jpg");
image2 = icon2.getImage();
enemy_width = image2.getWidth(this);
enemy_height = image2.getHeight(this);
n = 14; //number of enemies
enemy_x = new int[n];
enemy_y = new int[n];
enemy_move = new int[n];
enemy_alive = new int[n];
int distance = 40;
e_missile_flag = new int[n];
e_missile_x = new int[n];
e_missile_y = new int[n];
e_missile_move = new int[n];
// place enemies in 7x2
for (int i = 0; i < 7; i++) {
enemy_x[i] = (enemy_width + distance) * i + 50;
enemy_y[i] = 50;
}
for (int i = 7; i < n; i++) {
enemy_x[i] = (enemy_width + distance) * (i - 5) + 50;
enemy_y[i] = 100;
}
for (int i = 0; i < n; i++) {
enemy_alive[i] = 1; //all alive
enemy_move[i] = -10; //moves to left
}
for (int i = 0; i < n; i++) {
e_missile_flag[i] = 0;
e_missile_x[i] = 0;
e_missile_y[i] = 0;
e_missile_move[i] = 7 + n % 3;
}
/**
* * setup system **
*/
setBackground(Color.black);
setFocusable(true);
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
timer = new Timer(50, this);
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 800);
}
private void updateEnemiesPosition() {
//update enemies' position
Dimension dim = getSize();
for (int i = 0; i < n; i++) {
enemy_x[i] += enemy_move[i];
if ((enemy_x[i] < 0) || (enemy_x[i] > (dim.width - enemy_width))) {
enemy_move[i] = -enemy_move[i];
}
}
}
private void updateMyPosition() {
if (my_x < 0) {
my_x = 800;
}
if (my_x > 800) {
my_x = 0;
}
}
private void activateMyMissile() {
//shoot a missile
if (missile_flag == 0) {
my_missile_x = my_x + player_width / 2;
my_missile_y = MY_Y; //MY_Y=400
missile_flag = 1;
}
}
private void updateMyMissile() {
//update missile position if alive
if (missile_flag == 1) {
my_missile_y -= 15;
if (0 > my_missile_y) {
missile_flag = 0;
}
}
}
private void activateEnemiesMissile() {
//activate enemies' missile if enemy is alive and its missile is not alive
for (int i = 0; i < n; i++) {
if (enemy_alive[i] == 1 && e_missile_flag[i] == 0) {
e_missile_x[i] = enemy_x[i] + enemy_width / 2;
e_missile_y[i] = enemy_y[i];
e_missile_flag[i] = 1;
}
}
}
private void updateEnemiesMissile() {
//update enemies' missile position if alive
Dimension dim = getSize();
for (int i = 0; i < n; i++) {
if (e_missile_flag[i] == 1) {
e_missile_y[i] += e_missile_move[i];
if (e_missile_y[i] > dim.height) {
e_missile_flag[i] = 0;
}
}
}
}
private void checkHitToEnemy() {
for (int i = 0; i < n; i++) {
if (missile_flag == 1 && enemy_alive[i] == 1) {
if (my_missile_x > enemy_x[i]
&& my_missile_x < (enemy_x[i] + enemy_width)
&& my_missile_y > enemy_y[i]
&& my_missile_y < (enemy_y[i] + enemy_height)) {
//hit
missile_flag = 0;
enemy_alive[i] = 0;
}
}
}
}
private boolean checkHitToPlayer() {
for (int i = 0; i < n; i++) {
if (e_missile_flag[i] == 1) {
if (e_missile_x[i] > my_x
&& e_missile_x[i] < (my_x + player_width)
&& e_missile_y[i] > MY_Y
&& e_missile_y[i] < (MY_Y + player_height)) {
e_missile_flag[i] = 0;
return true;
}
}
}
return false;
}
private boolean checkClear() {
int cnt = 0;
for (int i = 0; i < n; i++) {
if (enemy_alive[i] == 0) {
cnt++;
}
}
return (n == cnt);
}
public void paintComponent(Graphics g) {
super.paintComponent(g); //reset graphics
Graphics2D g2d = (Graphics2D) g.create();
System.out.println(getWidth() + "x" + getHeight());
int w2 = getWidth() / 2;
int h2 = getHeight() / 2;
g2d.rotate(-Math.PI / 2, w2, h2);
g2d.setColor(Color.DARK_GRAY);
g2d.fillRect(0, 0, getWidth(), getHeight());
//draw player
g2d.setColor(Color.BLUE);
g2d.fillRect(my_x, 400, 10, 10);
// g.drawImage(image, my_x, 400, this);
//draw enemies
for (int i = 0; i < n; i++) {
if (enemy_alive[i] == 1) {
g2d.setColor(Color.RED);
g2d.fillRect(enemy_x[i], enemy_y[i], 10, 10);
// g.drawImage(image2, enemy_x[i], enemy_y[i], this);
}
}
//draw players missiles
if (missile_flag == 1) {
g2d.setColor(Color.white);
g2d.fillRect(my_missile_x, my_missile_y, 2, 5);
}
//draw enemies' missiles
for (int i = 0; i < n; i++) {
if (e_missile_flag[i] == 1) {
g2d.setColor(Color.white);
g2d.fillRect(e_missile_x[i], e_missile_y[i], 2, 5);
}
}
g2d.dispose();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == timer) {
updateEnemiesPosition();
updateMyPosition();
updateMyMissile();
updateEnemiesMissile();
activateEnemiesMissile();
if (checkHitToPlayer()) {
System.out.println("===== Game Over =====");
System.exit(0);
}
checkHitToEnemy();
if (checkClear()) {
System.out.println("===== Game Clear =====");
System.exit(0);
}
repaint();
}
}
public void mouseClicked(MouseEvent me) {
}
public void mousePressed(MouseEvent me) {
activateMyMissile();
}
public void mouseReleased(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseMoved(MouseEvent me) {
}
public void mouseDragged(MouseEvent me) {
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
switch (key) {
case KeyEvent.VK_S:
my_x = my_x + 10;
break;
case KeyEvent.VK_W:
my_x = my_x - 10;
break;
case KeyEvent.VK_DOWN:
my_x = my_x + 10;
break;
case KeyEvent.VK_UP:
my_x = my_x - 10;
break;
case KeyEvent.VK_X:
if (missile_flag == 0) {
my_missile_x = my_x + player_width / 2;
my_missile_y = MY_Y;// MY_Y=400
missile_flag = 1;
}
break;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
}
Also, beware, transformations of this nature are accumulative. You should, instead, take a snapshot of the Graphics context and dispose of it once you're done (see the above for an example).
Also, have look at How to Use Key Bindings as it will help resolve the focus issues related to KeyListener

Keyboard Input Movement on Applet

I'm creating a very basic game using applet and I'm not sure how to write the code for the computer to register the arrows as movement (up, down, left, right).
How can I get the yellow Pacman looking character to move based on keyboard inputs?
This is my code:
import java.applet.*;
import java.awt.*;
public class GameShopRoofCashOut extends Applet
{
public void paint(Graphics g)
{
// Setup the board
int rows = 20;
int columns = 20;
int cellSize = 30;
int board [ ][ ] = new int [rows][columns];
int dirt = 12;
int lightstone = 13;
int darkstone = 17;
int slotx = 12;
int sloty = 0;
int linex = 30;
int liney = 390;
int layer = 0;
// Store objects in the board
board[11][4] = 7;
board[11][5] = 7;
board[10][14] = 8;
board[11][14] = 9;
board[0][19] = 10;
while (sloty<20)
{
while (slotx<20)
{
for (int r=0; r< board.length; r++)
{
for (int c=0; c< board[r].length; c++)
{
//store objects in the board
board[dirt][sloty] = 1;
board[lightstone][sloty] = 2;
board[darkstone][sloty]= 3;
if (lightstone<17)
{
lightstone++;
}
if (darkstone<19)
{
darkstone++;
}
// Draw the board
if (board [r][c] == 1)
{
g.setColor(Color.blue);
g.fillRect(c*cellSize,r*cellSize,cellSize,cellSize);
layer++;
}
if (board [r][c] == 2)
{
g.setColor(Color.lightGray);
g.fillRect(c*cellSize,r*cellSize,cellSize,cellSize);
layer++;
}
if (board [r][c] == 3)
{
g.setColor(Color.darkGray);
g.fillRect(c*cellSize,r*cellSize,cellSize,cellSize);
layer++;
}
if (board [r][c] == 7)
{
g.setColor(Color.magenta);
g.fillRect(c*cellSize,r*cellSize,cellSize,cellSize);
layer++;
}
if (board[r][c] == 8)
{
int x = c*cellSize;
int y = r*cellSize;
Polygon p = new Polygon();
p.addPoint(x+cellSize/2,y);
p.addPoint(x+cellSize, y+cellSize);
p.addPoint(x, y+cellSize);
p.addPoint(x+cellSize/2,y);
g.setColor(Color.orange);
g.fillPolygon(p);
}
if (board[r][c] == 9)
{
g.setColor(Color.orange);
g.fillRect(c*cellSize,r*cellSize,cellSize,cellSize);
}
if (board [r][c] == 10)
{
g.setColor(Color.yellow);
g.fillArc(c*cellSize,r*cellSize,cellSize,cellSize,30,300);
}
}
}
slotx++;
}
lightstone = 13;
darkstone = 17;
slotx=12;
sloty++;
}
g.setColor(Color.black);
g.drawString("Shop",420,295);
g.drawString("Cash Out",120,320);
while (linex<600)
{
g.setColor(Color.black);
g.drawLine(linex,360,linex,600);
g.drawLine(0,liney,600,liney);
linex+=30;
liney+=30;
}
}
}

Java: Super class won't override function

I have been working on a game for a while and I would like to have a different class for each type of Creature that there is. Right now, all of the different creatures' AI is run in a long switch and I would like a superclass to ovveride that function with that AI for that creature. I have this set up but it won't override.
Am I forgetting something?
Bunny.java:
package creature;
import org.newdawn.slick.opengl.Texture;
import creature.Creature;
import creature.CreatureType;
import data.Tile;
public class Bunny extends Creature{
public Bunny(CreatureType type, float x, float y, float speed1) {
super(type, x, y, speed1);
}
public void AI(int type) {
System.out.println("test");
}
}
Creature.java:
public Creature(CreatureType type, float x, float y, float speed1) {
this.texture = drawImg(type.textureName);
this.textureHamster = drawImg("creatures/HamsterFace");
this.healthBackground = drawImg("health_background");
this.healthForeground = drawImg("health_foreground");
this.healthBorder = drawImg("health_border");
this.startTile = startTile;
this.x = x;
this.y = y;
this.intX = (int) x;
this.intY = (int) y;
this.width = texture.getImageWidth();
this.height = texture.getImageHeight();
this.speed1 = speed1;
this.speed = speed;
this.intspeed = speed;
this.grid = grid;
this.health = type.health;
this.inithealth = type.health;
this.hiddenHealth = health;
this.startHealth = health;
this.dir = false;
this.dchosen = false;
this.setx = 0;
this.hurt = 0;
this.panick = 0;
this.deathWish = 0;
this.pdir = -1;
this.myX = x;
this.myY = HEIGHT / 2;
this.right = false;
this.left = false;
this.fade = 0;
this.fir = true;
this.aiType = type.aiType;
this.yOffset = 0;
}
.....
public void AI(int type) {
if(panic > 0)
panic--;
hurt();
speed = speed1;
switch(type) {
case 1:
if(panic > 0) {
if(pickRandom(150, 300) < 10) {
direction = !direction;
}
if(direction) {
if(!right) {
x += speed;
} else {
if(falling < 2)
gravity = 8;
}
} else {
if(!left) {
x -= speed;
} else {
if(falling < 2)
gravity = 8;
}
}
} else {
if(getRange(WIDTH / 2, myX) > 200) {
directionCoolDown++;
if(directionCoolDown > pickRandom(150, 3000)) {
direction = !direction;
directionCoolDown = 0;
}
if(direction) {
if(!right) {
x += speed / 3.2;
} else {
if(falling < 2)
gravity = 8;
}
} else {
if(!left) {
x -= speed / 3.2;
} else {
if(falling < 2)
gravity = 8;
}
}
} else {
if(myX < WIDTH / 2) {
direction = true;
} else {
direction = false;
}
}
}
break;
case 2:
yOffset = -25;
if(!angry) {
pdir = 0;
if(getRange(Player.getX(), myX) < 300) {
hamsterFace = true;
} else {
hamsterFace = false;
}
if(!hamsterFace) {
directionCoolDown++;
if(directionCoolDown > pickRandom(150, 3000)) {
direction = !direction;
directionCoolDown = 0;
}
if(direction) {
if(!right) {
x += speed / 3.2;
} else {
if(falling < 2)
gravity = 8;
}
} else {
if(!left) {
x -= speed / 3.2;
} else {
if(falling < 2)
gravity = 8;
}
}
}
} else {
pdir++;
hamsterFace = false;
if(myX < Player.getX()) {
direction = true;
} else {
direction = false;
}
if(direction) {
if(!right) {
x += speed / 1;
} else {
if(falling < 2)
gravity = 8;
}
} else {
if(!left) {
x -= speed / 1;
} else {
if(falling < 2)
gravity = 8;
}
}
if(getRange(myX, Player.getX()) < 5 && getRange(myY, Player.getY()) < 5) {
hurtPlayer(-2);
direction = !direction;
if(direction) {
if(!right) {
x += speed * 10;
} else {
if(falling < 2)
gravity = 8;
}
} else {
if(!left) {
x -= speed * 10;
} else {
if(falling < 2)
gravity = 8;
}
}
}
}
if(panic > 1) {
angry = true;
} else {
if(pdir > pickRandom(1000,2000)) {
angry = false;
}
}
break;
}
}
.....
(Both classes are in the same package)
EDIT: I fixed the typo....
you have in the Bunny class:
public void AI() {
System.out.println("test");
}
in the Creature class:
public void AI(int type) {
if(panic > 0)
....
so
void AI(int type) and void AI() are NOT the same method (check the signature and how they take different parameters!)
therefore the Bunny class is not overriding anything from the parent class
--
edit:
now that your classes have a method void AI(int type) then we can say that
Bunny override the Creature AI method and everytime you call bunny.AI(f) your bunny method will be called!

My sorting algorithms are only going through once

I am writing a program that sorts 2 arrays of the same values by using two different algorithms. It loops through the arrays once each time a button is clicked. My problem is that it only sorts the first time you click the button. Every other time nothing happens. I put a count incrementer to see if the code was running and it was. I'm stumped. Any help will be appreciated.
I fixed the selection sort.
public class TwoSortsPanel extends JPanel
{
private int width = 10, gap = 3, x = 200, y = 50;
private int[] ranArr1 = new int[15], ranArr2 = new int[15];
private Color blue = Color.blue, red = Color.red, pink = Color.pink, gray = Color.gray;
public static int count = 0, indexSel = 0;
{
for(int i = 0; i < ranArr1.length-1; i++)
{
ranArr1[i] = (int) (Math.random() * 15);
ranArr2[i] = ranArr1[i];
}
}
public TwoSortsPanel()
{
printArray(ranArr1);
setBackground(pink);
setPreferredSize (new Dimension (400,300));
JButton sort = new JButton ("Sort");
sort.addActionListener(new ButtonListener());
add (sort);
}
public static void printArray(int[] c)
{
System.out.println(Arrays.toString(c));
}
public void paintComponent (Graphics page)
{
super.paintComponent(page);
page.drawString("" + count, 10, 12);
if (insertion() == false || selection() == false)
{
int yPlus = 50;
for(int i = 0; i < ranArr1.length; i++)
{
page.setColor(blue);
page.fillRect(x, yPlus, ranArr1[i]*10, width);
yPlus += width + gap;
}
yPlus = 50;
for(int i = 0; i < ranArr2.length; i++)
{
page.setColor(red);
page.fillRect(x, yPlus, -ranArr2[i]*10, width);
yPlus += width + gap;
}
}
else
{
int yPlus = 50;
for(int i = 0; i < ranArr1.length; i++)
{
page.setColor(gray);
page.fillRect(x, yPlus, ranArr1[i]*10, width);
yPlus += width + gap;
}
yPlus = 50;
for(int i = 0; i < ranArr2.length; i++)
{
page.setColor(gray);
page.fillRect(x, yPlus, -ranArr2[i]*10, width);
yPlus += width + gap;
}
}
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
displaySelection(ranArr1);
displayInsertion(ranArr2);
count++;
printArray(ranArr1);
repaint();
}
}
public static void displaySelection(int[] a)
{
int temp;
int min = indexSel;
for (int scan = indexSel+1; scan < a.length ; scan++)
if (a[scan] < a[min])
min = scan;
temp = a[min];
a[min] = a[indexSel];
a[indexSel] = temp;
count++;
indexSel++;
}
public static void displayInsertion(int[] b)
{
int index = 1;
int key = b[index];
int position = index;
while (position > 0 && b[position-1] > key )
{
b[position] = b[position-1];
position--;
}
b[position] = key;
}
public boolean selection()
{
for (int i = 0; i < ranArr1.length-1; i++)
{
if(ranArr1[i] > ranArr1[i+1])
{
return false;
}
}
return true;
}
public boolean insertion()
{
for (int i = 0; i < ranArr2.length-1; i++)
{
if(ranArr2[i] > ranArr2[i+1])
{
return false;
}
}
return true;
}
}
Sorry. I didn't want the post to look too busy and I guess it lost meaning.

Categories

Resources