I'm in the process of making a game which has 3 sections to the JFrame, the game map, a "player view" : just an animation of the player moving and will hopefully include different enemy designs later and finally a inventory section I haven't started on yet.
What would be the best way in terms of class and method layouts to have all these 3 sections of my JPanel able to communicate with one another and dynamically change based on the current situation (having the player view show an enemy when their tile collides with another or have it not update if the player doesnt move (s)).
I don't mind re-writing the entire game just this is my first game and would like some assistance on structure.
And I'm not sure exactly how paintComponent works or repaint() method. Or how draw(Graphics g) is called
to make the graphics???
Code for context and testing:
TextGamePanel.java :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Random;
public class TextGamePanel extends JPanel implements ActionListener{
private static final int HEIGHT = 30, WIDTH = 30, MAPVISIBILITY = 8;
private static final int SCREEN_WIDTH = 1080;
private static final int SCREEN_HEIGHT = 1080;
private static final int UNIT_SIZE = 36;
private static final int DELAY = 10;
private String[][] mapBlank = new String[HEIGHT][WIDTH];
private ArrayList<Enemies> enemyList = new ArrayList<Enemies>();
private Random random = new Random();
private Players player;
private int turnCounter = 0;
Timer timer;
boolean active = false , movementMade = false;
TextGamePanel(){
this.setPreferredSize(new Dimension(1920, 1080));
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
}
public void startGame(){
newPlayer();
active = true;
timer = new Timer(DELAY, this);
timer.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
draw(g);
}
public void makeMap(){
for(int row = 0; row < mapBlank.length; row++){
for(int col = 0; col < mapBlank[row].length; col++){
mapBlank[row][col] = "";
}
}
for(Enemies enemy : enemyList){
mapBlank[enemy.getXPos()][enemy.getYPos()] = " *";
}
mapBlank[player.getXPos()][player.getYPos()] = " ^";
}
public void draw(Graphics g){
makeMap();
// These loops generate the
g.setColor(new Color(69, 69, 69));
g.fillRect(1080, 0, 840, 360);
g.setFont(new Font("Times Roman", Font.BOLD, 36));
g.setColor(new Color(74, 74, 74));
for(int x = 0; x < 20; x++){
g.drawString(randomString(50), 1020, UNIT_SIZE + x*UNIT_SIZE/2);
}
for(int i = 0; i < 2; i++){
for(int x = 0; x < 13; x++){
g.setColor(new Color(0+x*10, 0+x*10, 0+x*10));
g.setFont(new Font("Times Roman", Font.BOLD, 10+x*2));
g.drawString(randomString(200), 1020, 268 + x * 8);
}
}
//makes the map background grey
g.setColor(new Color(69, 69, 69));
g.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
//Makes light for context of player view range
g.setColor(new Color(227, 201, 109, 50));
g.fillOval((int)(((player.getXPos()) * UNIT_SIZE) - MAPVISIBILITY/2 * UNIT_SIZE), (int)(((player.getYPos()) * UNIT_SIZE) - MAPVISIBILITY/2 *UNIT_SIZE), (int)((MAPVISIBILITY +1) * UNIT_SIZE), (int)((MAPVISIBILITY +1) * UNIT_SIZE));
g.setColor(new Color(227, 180, 109, 50));
g.fillOval((int)(((player.getXPos()) * UNIT_SIZE) - (MAPVISIBILITY/2 - 1) * UNIT_SIZE), (int)(((player.getYPos()) * UNIT_SIZE) - (MAPVISIBILITY/2 - 1) *UNIT_SIZE), (int)((MAPVISIBILITY -1) * UNIT_SIZE), (int)((MAPVISIBILITY -1) * UNIT_SIZE));
g.setColor(new Color(240, 110, 67, 50));
g.fillOval((int)(((player.getXPos()) * UNIT_SIZE) - (MAPVISIBILITY/2 - 2.5) * UNIT_SIZE), (int)(((player.getYPos()) * UNIT_SIZE) - (MAPVISIBILITY/2 - 2.5) *UNIT_SIZE), (int)((MAPVISIBILITY -4) * UNIT_SIZE), (int)((MAPVISIBILITY -4) * UNIT_SIZE));
g.setColor(new Color(255, 255, 255));
g.setFont(new Font("Times Roman", Font.BOLD, 36));
//draws the grid
for(int i = 0; i < SCREEN_HEIGHT/UNIT_SIZE; i++){
g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);
}
for(int i = 0; i < SCREEN_WIDTH/UNIT_SIZE; i++){
g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE);
}
//draws only yourself and enemy around you given MAPVISIBILITY/2 = view range
int xIndex = -1, yIndex = -1;
for(int row = player.getXPos() - MAPVISIBILITY/2; row < player.getXPos() + 1 + MAPVISIBILITY/2; row++){
xIndex ++;
for(int col = player.getYPos() - MAPVISIBILITY/2; col < player.getYPos() + 1 + MAPVISIBILITY/2; col++){
yIndex++;
try{
g.drawString(mapBlank[row][col], row * UNIT_SIZE, (col + 1) * UNIT_SIZE);
}catch(Exception e){
}
}
}
// inventory section (yet to be made)
g.setColor(Color.blue);
g.fillRect(1080, 360, 840, 720);
}
public void movementPhase(){
turnCounter ++;
updateEnemyMovement();
if(turnCounter == 2){
turnCounter = 0;
newEnemy();
}
}
#Override
public void actionPerformed(ActionEvent e){
if(active){
}
}
public class MyKeyAdapter extends KeyAdapter{
#Override
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_Q: // Move diagonal left up.
if(player.getXPos() > 0 && player.getYPos() > 0){
player.setXPos(player.getXPos() - 1);
player.setYPos(player.getYPos() - 1);
movementMade = true;
}
break;
case KeyEvent.VK_E: // Move diagonal right up.
if(player.getXPos() < HEIGHT - 1 && player.getYPos() > 0){
player.setXPos(player.getXPos() + 1);
player.setYPos(player.getYPos() - 1);
movementMade = true;
}
break;
case KeyEvent.VK_Z: // Move diagonal left down.
if(player.getXPos() > 0 && player.getYPos() < WIDTH - 1){
player.setXPos(player.getXPos() - 1);
player.setYPos(player.getYPos() + 1);
movementMade = true;
}
break;
case KeyEvent.VK_C: // Move diagonal right down.
if(player.getYPos() < WIDTH - 1 && player.getXPos() < HEIGHT - 1){
player.setXPos(player.getXPos() + 1);
player.setYPos(player.getYPos() + 1);
movementMade = true;
}
break;
case KeyEvent.VK_W: // Move up.
if(player.getYPos() > 0){
player.setYPos(player.getYPos() - 1);
movementMade = true;
}
break;
case KeyEvent.VK_X: // Move down.
if(player.getYPos() < WIDTH - 1){
player.setYPos(player.getYPos() + 1);
movementMade = true;
}
break;
case KeyEvent.VK_A: // Move left.
if(player.getXPos() > 0){
player.setXPos(player.getXPos() - 1);
movementMade = true;
}
break;
case KeyEvent.VK_D: // Move right.
if(player.getXPos() < HEIGHT - 1){
player.setXPos(player.getXPos() + 1);
movementMade = true;
}
break;
case KeyEvent.VK_S: // Dont Move.
movementMade = true;
break;
}
if(movementMade){
movementPhase();
movementMade = false;
}
repaint();
}
}
public void updateEnemyMovement(){
Iterator i = (Iterator) enemyList.iterator();
Enemies enemy = new Enemies();
while(i.hasNext()){
enemy = (Enemies) i.next();
enemy.move(player.getXPos(), player.getYPos());
if(enemy.getXPos() == player.getXPos() && enemy.getYPos() == player.getYPos()){
i.remove();
}
}
}
public void newPlayer(){
player = new Players(random.nextInt((int)SCREEN_WIDTH/UNIT_SIZE), random.nextInt((int)SCREEN_HEIGHT/UNIT_SIZE));
}
public void newEnemy(){
enemyList.add(new Enemies(random.nextInt(HEIGHT), random.nextInt(WIDTH)));
}
public String randomString(int n) {
int leftLimit = 49; //'0'
int rightLimit = 122; //'z'
int targetStringLength = n;
Random random = new Random();
StringBuilder buffer = new StringBuilder(targetStringLength);
for (int i = 0; i < targetStringLength; i++) {
int randomLimitedInt = leftLimit + (int)
(random.nextFloat() * (rightLimit - leftLimit + 1));
buffer.append((char) randomLimitedInt);
}
String generatedString = buffer.toString();
return(generatedString);
}
}
`
Players.java :
public class Players{
private int x, y;
public Players(){
}
public Players(int x, int y){
this.x = x;
this.y = y;
}
/** Positional Methods */
public int getXPos(){
return x;
}
public int getYPos(){
return y;
}
public void setXPos(int x){
this.x = x;
}
public void setYPos(int y){
this.y = y;
}
}
`
Enemies.java :
public class Enemies {
private int x, y;
public Enemies(){
}
public Enemies(int x, int y){
this.x = x;
this.y = y;
}
/** Positional Methods */
public int getXPos(){
return x;
}
public int getYPos(){
return y;
}
public void setXPos(int x){
this.x = x;
}
public void setYPos(int y){
this.y = y;
}
/** Enemy Movement Method */
public void move(int playerX, int playerY){
if(getXPos() == playerX && getYPos() == playerY){ // x = playerX & y = playery
}/** Diagonal right down */
else if(getXPos() < playerX && getYPos() < playerY){ // x < playerX & y < playerY
setXPos(getXPos() + 1); // x + 1
setYPos(getYPos() + 1); // y + 1
}/** Diagonal right up */
else if(getXPos() > playerX && getYPos() < playerY){ // x > playerX & y < playerY
setXPos(getXPos() - 1); // x - 1
setYPos(getYPos() + 1); // y + 1
}/** Diagonal left down */
else if(getXPos() < playerX && getYPos() > playerY){ // x < playerX & y > playerY
setXPos(getXPos() + 1); // x + 1
setYPos(getYPos() - 1); // y - 1
}/** Diagonal right up */
else if(getXPos() > playerX && getYPos() > playerY){ // x > playerX & y > playerY
setXPos(getXPos() - 1); // x - 1
setYPos(getYPos() - 1); // y - 1
}/** Down */
else if(getXPos() < playerX && getYPos() == playerY){ // x < playerX & y = playerY
setXPos(getXPos() + 1); // x + 1
}/** Up */
else if(getXPos() > playerX && getYPos() == playerY){ // x > playerX & y = playerY
setXPos(getXPos() - 1); // x - 1
}/** Right */
else if(getXPos() == playerX && getYPos() < playerY){ // x = playerX & y < playerY
setYPos(getYPos() + 1); // y + 1
}/** Left */
else if(getXPos() == playerX && getYPos() > playerY){ // x = playerX & y > playerY
setYPos(getYPos() - 1); // y - 1
}
}
}
`
TextGameFrame.java :
import javax.swing.*;
public class TextGameFrame extends JFrame{
TextGameFrame(){
this.add(new TextGamePanel());
this.setTitle("Text Game");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
`
TextGameMain.java :
public class TextGameMain{
public static void main(String[] args){
new TextGameFrame();
}
}
`
Related
For my class I need to create a one player pong game. We need to use what we've learned so its simple code and the problem is, while the "while loop" is running, my Keydown thread doesn't seem to work. My teacher isn't helpful at all so that's why i'm here. Please help by only using methods and such that are used in my program.
I've tried moving the ball code into a run thread but i can never seem to actually get that thread running.
public class PongGame extends Applet {
int startup = 0;
int x = 400;
int y = 500;
int x2 = (int) (Math.random() * (600 + 1));
int y2 = (int) (Math.random() * (600 + 1));
int xVelocity = 1;
int yVelocity = 1;
int x2Velocity = 1;
int y2Velocity = 1;
int curry = 700;
int currx = 600;
int counter = 2;
#Override
public void init() {
setSize(1440, 900);
setBackground(Color.black);
setFont(new Font("Helvetica", Font.BOLD, 36));
}
#Override
public boolean keyDown(Event evt, int key) {
startup = startup + 1;
repaint();
if (key == Event.RIGHT) {
currx += 10;
}
if (key == Event.LEFT) {
currx -= 10;
}
if (currx == 1400) {
currx = 10;
}
if (currx == 20) {
currx = 1399;
}
repaint();
return false;
}
public void run(Graphics g) {
startup = 0;
while (counter > 0) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
}
x += xVelocity;
y += yVelocity;
g.setColor(Color.blue);
g.fillRect(currx, curry, 300, 25);
g.setColor(Color.red);
g.fillOval(x, y, 30, 30);
for (int j = 0; j < 20000000; j++);
g.setColor(Color.black);
g.fillOval(x, y, 30, 30);
//Bounce the ball off the wall or paddle
if (x >= 1400 || x <= 0) {
xVelocity = -xVelocity;
}
if (y >= 800 || y <= 0) {
yVelocity = -yVelocity;
}
if (((y == 675)) && ((currx <= x) && (currx + 300) >= x)) {
yVelocity = -yVelocity;
y = y - 10;
repaint();
}
}
}
public void paint(Graphics g) {
if (startup == 0) {
g.setColor(Color.white);
g.drawString("Welcome To PONG", 0, 100);
g.drawString("Created by Caden Anton", 0, 200);
g.drawString("copyright May 3rd, 2019 ©", 0, 300);
g.drawString("Press any key to continue", 0, 400);
}
if (startup == 1) {
g.setColor(Color.white);
g.drawString("RULES:", 0, 100);
g.drawString("Press the arrwow keys to move the paddle", 0, 200);
g.drawString("Your objective is to keep the ball from touching the ground", 0, 300);
g.drawString("Once the ball hits the ground you lose the game", 0, 400);
}
if (startup >= 2) {
//Input Run thread start here.
}
}
}
I need to do a Minesweeper game. I have most of the methods down, but I cannot figure out a way to draw the number of mines around a given tile. I have a method that returns the number of mines around that tile, but no such method to actually display that number inside the tile in the game.
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Insets;
import java.net.URL;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class MyPanel extends JPanel {
private static final long serialVersionUID = 3426940946811133635L;
private static final int GRID_X = 25;
private static final int GRID_Y = 25;
private static final int INNER_CELL_SIZE = 29;
private static final int TOTAL_COLUMNS = 9;
private static final int TOTAL_ROWS = 10; //Last row has only one cell
public int x = -1;
public int y = -1;
public int mouseDownGridX = 0;
public int mouseDownGridY = 0;
private ImageIcon icon;
private static char minefield[][];
public Color[][] colorArray = new Color[TOTAL_COLUMNS][TOTAL_ROWS];
public MyPanel() { //This is the constructor... this code runs first to initialize
if (INNER_CELL_SIZE + (new Random()).nextInt(1) < 1) { //Use of "random" to prevent unwanted Eclipse warning
throw new RuntimeException("INNER_CELL_SIZE must be positive!");
}
if (TOTAL_COLUMNS + (new Random()).nextInt(1) < 2) { //Use of "random" to prevent unwanted Eclipse warning
throw new RuntimeException("TOTAL_COLUMNS must be at least 2!");
}
if (TOTAL_ROWS + (new Random()).nextInt(1) < 3) { //Use of "random" to prevent unwanted Eclipse warning
throw new RuntimeException("TOTAL_ROWS must be at least 3!");
}
for (int x = 0; x < TOTAL_COLUMNS; x++) { //Top row
colorArray[x][0] = Color.LIGHT_GRAY;
}
for (int y = 0; y < TOTAL_ROWS; y++) { //Left column
colorArray[0][y] = Color.LIGHT_GRAY;
}
for (int x = 1; x < TOTAL_COLUMNS; x++) { //The rest of the grid
for (int y = 1; y < TOTAL_ROWS; y++) {
colorArray[x][y] = Color.LIGHT_GRAY;
}
}
minefield = new char [TOTAL_COLUMNS][TOTAL_ROWS];
}
Random rando = new Random();
public static int mines = 10;
public int flags = 10;
public static int flagged = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Compute interior coordinates
Insets myInsets = getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
int x2 = getWidth() - myInsets.right - 1;
int y2 = getHeight() - myInsets.bottom - 1;
int width = x2 - x1;
int height = y2 - y1;
//Paint the background
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x1, y1, width + 1, height + 1);
//Draw the grid minus the bottom row (which has only one cell)
//By default, the grid will be 10x10 (see above: TOTAL_COLUMNS and TOTAL_ROWS)
g.setColor(Color.BLACK);
for (int y = 0; y <= TOTAL_ROWS - 1; y++) {
g.drawLine(x1 + GRID_X, y1 + GRID_Y + (y * (INNER_CELL_SIZE + 1)), x1 + GRID_X + ((INNER_CELL_SIZE + 1) * TOTAL_COLUMNS), y1 + GRID_Y + (y * (INNER_CELL_SIZE + 1)));
}
for (int x = 0; x <= TOTAL_COLUMNS; x++) {
g.drawLine(x1 + GRID_X + (x * (INNER_CELL_SIZE + 1)), y1 + GRID_Y, x1 + GRID_X + (x * (INNER_CELL_SIZE + 1)), y1 + GRID_Y + ((INNER_CELL_SIZE + 1) * (TOTAL_ROWS - 1)));
}
//Paint cell colors
for (int x = 0; x < TOTAL_COLUMNS; x++) {
for (int y = 0; y < TOTAL_ROWS; y++) {
if ((x == 0) || (y != TOTAL_ROWS - 1)) {
Color c = colorArray[x][y];
g.setColor(c);
g.fillRect(x1 + GRID_X + (x * (INNER_CELL_SIZE + 1)) + 1, y1 + GRID_Y + (y * (INNER_CELL_SIZE + 1)) + 1, INNER_CELL_SIZE, INNER_CELL_SIZE);
}
}
}
}
// Places the mines in the field
public void placeMines() {
int minesPlaced = 1;
while (minesPlaced <= mines) {
int x = rando.nextInt(TOTAL_COLUMNS);
int y = rando.nextInt(TOTAL_ROWS-1);
if (minefield[x][y] != '*') {
minefield[x][y] = '*';
minesPlaced++;
}
}
for (int i=0; i<9; i++) {
for (int j=0; j<9; j++) {
bombCheck(i, j);
if (bombCheck(i, j) == 1) {
System.out.println(i + "," + j); // for debugging purposes
}
}
}repaint();
}
//checks a tile, white if there were no mines
public void check (int x, int y) {
colorArray[x][y] = Color.WHITE ;
repaint();
}
// Checks whether this place in the field has a bomb (1) or not (0).
public int bombCheck(int x, int y) {
if (!(x == -1 || y == -1)) {
if (minefield[x][y] == '*') {
return 1;
}
else {
minefield[x][y] = 'c';
return 0;
}
}
else{
return 0;
}
}
// Checks for mines on the 8 other tiles around the target location and returns the number of mines there are.
public int minesAround(int x, int y) {
int mines = 0;
mines += bombCheck(x-1, y-1);
mines += bombCheck(x-1, y);
mines += bombCheck(x-1, y+1);
mines += bombCheck(x, y-1);
mines += bombCheck(x, y+1);
mines += bombCheck(x+1, y-1);
mines += bombCheck(x+1, y);
mines += bombCheck(x+1, y+1);
if (mines > 0) {
return mines;
}
else{
return 0;
}
}
//What I've come up with so far for drawing the number in the tile. Does not work.
public void draw (Graphics g, int n, int x, int y) {
super.paintComponent(g);
g.drawString("" + n + "", x, y);
}
//Recursive method
public void checkAround(int x, int y) {
int minx, miny, maxx, maxy;
check(x,y);
minx = (x <= 0 ? 0 : x - 1);
miny = (y <= 0 ? 0 : y - 1);
maxx = (x >= TOTAL_COLUMNS - 1 ? TOTAL_COLUMNS - 1 : x + 1);
maxy = (y >= TOTAL_ROWS - 2 ? TOTAL_ROWS - 2 : y + 1);
for (int i = minx; i < maxx; i ++) {
for (int j = miny; j <= maxy; j ++) {
if (bombCheck(i,j) == 0 && colorArray[i][j] != Color.WHITE) {
check(i,j);
if (minesAround(i,j) == 0) {
checkAround(i,j);
}
if (minesAround(i,j) == 1) {
draw(getGraphics(),1,i,j); // Does not work.
repaint();
}
}
}
}
}
//Flag
public int checkflag(int x, int y){
int status = 0;
if (!(x == -1 || y == -1)) {
if (colorArray[x][y] == Color.RED) {
status += 1;
}else {
status += 0;
}
}
return status;
}
//Resets field
public void reset() {
for (int i = 0; i < TOTAL_COLUMNS; i++) {
for (int j = 0 ;j < TOTAL_ROWS; j++) {
colorArray[i][j] = Color.LIGHT_GRAY;
minefield[i][j] = ' ';
MyMouseAdapter.f = 1;
repaint();
}
}
placeMines();
}
public int getGridX(int x, int y) {
Insets myInsets = getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
x = x - x1 - GRID_X;
y = y - y1 - GRID_Y;
if (x < 0) { //To the left of the grid
return -1;
}
if (y < 0) { //Above the grid
return -1;
}
if ((x % (INNER_CELL_SIZE + 1) == 0) || (y % (INNER_CELL_SIZE + 1) == 0)) { //Coordinate is at an edge; not inside a cell
return -1;
}
x = x / (INNER_CELL_SIZE + 1);
y = y / (INNER_CELL_SIZE + 1);
if (x == 0 && y == TOTAL_ROWS - 1) { //The lower left extra cell
return x;
}
if (x < 0 || x > TOTAL_COLUMNS - 1 || y < 0 || y > TOTAL_ROWS - 2) { //Outside the rest of the grid
return -1;
}
return x;
}
public int getGridY(int x, int y) {
Insets myInsets = getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
x = x - x1 - GRID_X;
y = y - y1 - GRID_Y;
if (x < 0) { //To the left of the grid
return -1;
}
if (y < 0) { //Above the grid
return -1;
}
if ((x % (INNER_CELL_SIZE + 1) == 0) || (y % (INNER_CELL_SIZE + 1) == 0)) { //Coordinate is at an edge; not inside a cell
return -1;
}
x = x / (INNER_CELL_SIZE + 1);
y = y / (INNER_CELL_SIZE + 1);
if (x == 0 && y == TOTAL_ROWS - 1) { //The lower left extra cell
return y;
}
if (x < 0 || x > TOTAL_COLUMNS - 1 || y < 0 || y > TOTAL_ROWS - 2) { //Outside the rest of the grid
return -1;
}
return y;
}
public ImageIcon getIcon() {
return icon;
}
public void setIcon(ImageIcon icon) {
this.icon = icon;
}
}
-
import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Random;
import javax.swing.JFrame;
public class MyMouseAdapter extends MouseAdapter {
public static int f = 1;
public void mousePressed(MouseEvent e) {
switch (e.getButton()) {
case 1: //Left mouse button
Component c = e.getComponent();
while (!(c instanceof JFrame)) {
c = c.getParent();
if (c == null) {
return;
}
}
JFrame myFrame = (JFrame) c;
MyPanel myPanel = (MyPanel) myFrame.getContentPane().getComponent(0);
Insets myInsets = myFrame.getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
e.translatePoint(-x1, -y1);
int x = e.getX();
int y = e.getY();
myPanel.x = x;
myPanel.y = y;
myPanel.mouseDownGridX = myPanel.getGridX(x, y);
myPanel.mouseDownGridY = myPanel.getGridY(x, y);
myPanel.repaint();
break;
case 3: //Right mouse button
Component c1 = e.getComponent();
while (!(c1 instanceof JFrame)) {
c = c1.getParent();
if (c == null) {
return;
}
}
JFrame myFrame1 = (JFrame)c1;
MyPanel myPanel1 = (MyPanel) myFrame1.getContentPane().getComponent(0); //Can also loop among components to find MyPanel
Insets myInsets1 = myFrame1.getInsets();
int x2 = myInsets1.left;
int y2 = myInsets1.top;
e.translatePoint(-x2, -y2);
int x3 = e.getX();
int y3 = e.getY();
myPanel1.x = x3;
myPanel1.y = y3;
myPanel1.mouseDownGridX = myPanel1.getGridX(x3, y3);
myPanel1.mouseDownGridY = myPanel1.getGridY(x3, y3);
break;
default: //Some other button (2 = Middle mouse button, etc.)
//Do nothing
break;
}
}
public void mouseReleased(MouseEvent e) {
switch (e.getButton()) {
case 1: //Left mouse button
Component c = e.getComponent();
while (!(c instanceof JFrame)) {
c = c.getParent();
if (c == null) {
return;
}
}
JFrame myFrame = (JFrame)c;
MyPanel myPanel = (MyPanel) myFrame.getContentPane().getComponent(0); //Can also loop among components to find MyPanel
Insets myInsets = myFrame.getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
e.translatePoint(-x1, -y1);
int x = e.getX();
int y = e.getY();
myPanel.x = x;
myPanel.y = y;
int gridX = myPanel.getGridX(x, y);
int gridY = myPanel.getGridY(x, y);
if ((myPanel.mouseDownGridX == -1) || (myPanel.mouseDownGridY == -1)) {
//Had pressed outside
//Do nothing
} else {
if ((gridX == -1) || (gridY == -1)) {
//Do nothing
}else if (gridX == 0 && gridY == 9) {
myPanel.reset();
} else {
if ((myPanel.mouseDownGridX != gridX) || (myPanel.mouseDownGridY != gridY)) {
//Released the mouse button on a different cell where it was pressed
//Do nothing
} else {
//Released the mouse button on the same cell where it was pressed
if (!(myPanel.mouseDownGridX == -1) || (myPanel.mouseDownGridY == -1)) {
if (!(myPanel.colorArray[gridX][gridY] == Color.RED)) {
if (myPanel.bombCheck(gridX, gridY) == 0) {
myPanel.checkAround(gridX, gridY);
}
else{
myPanel.colorArray[gridX][gridY] = Color.BLACK ;
System.out.println("You've Lost!");
myPanel.reset();
myPanel.repaint();
}
}
}
}
}
}
myPanel.repaint();
break;
case 3: //Right mouse button
Component c1 = e.getComponent();
while (!(c1 instanceof JFrame)) {
c = c1.getParent();
if (c == null) {
return;
}
}
JFrame myFrame1 = (JFrame)c1;
MyPanel myPanel1 = (MyPanel) myFrame1.getContentPane().getComponent(0); //Can also loop among components to find MyPanel
Insets myInsets1 = myFrame1.getInsets();
int x2 = myInsets1.left;
int y2 = myInsets1.top;
e.translatePoint(-x2, -y2);
int x3 = e.getX();
int y3 = e.getY();
myPanel1.x = x3;
myPanel1.y = y3;
int gridX1 = myPanel1.getGridX(x3, y3);
int gridY1 = myPanel1.getGridY(x3, y3);
int flags = 10;
if ((myPanel1.mouseDownGridX == -1) || (myPanel1.mouseDownGridY == -1)) {
//Had pressed outside
//Do nothing
} else {
if ((gridX1 == -1) || (gridY1 == -1)) {
//Is releasing outside
//Do nothing
} else {
if ((myPanel1.mouseDownGridX != gridX1) || (myPanel1.mouseDownGridY != gridY1)) {
}else{
if (!(myPanel1.colorArray[gridX1][gridY1] == Color.WHITE)) {
if (myPanel1.checkflag(gridX1, gridY1) == 0) {
if (!(f > flags)) {
if (myPanel1.bombCheck(gridX1, gridY1) == 1) {
MyPanel.flagged ++;
if (MyPanel.flagged == 10) {
System.out.println("You've Won! Congratulations!");
myPanel1.reset();
myPanel1.colorArray[gridX1][gridY1] = Color.LIGHT_GRAY ;
myPanel1.repaint();
}
}
myPanel1.colorArray[gridX1][gridY1] = Color.RED ;
myPanel1.repaint();
f ++;
}
}
else {
myPanel1.colorArray[gridX1][gridY1] = Color.LIGHT_GRAY ;
myPanel1.repaint();
f --;
}
}
}
}
}
break;
default: //Some other button (2 = Middle mouse button, etc.)
//Do nothing
break;
}
}
}
-
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame myFrame = new JFrame("Color Grid");
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
myFrame.setLocation(400, 150);
myFrame.setSize(400, 400);
MyPanel myPanel = new MyPanel();
myFrame.add(myPanel);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
myFrame.addMouseListener(myMouseAdapter);
myFrame.setVisible(true);
myPanel.placeMines();
}
}
This is only my first year studying Computer science, but if my intuition is correct, my draw method is drawing the number behind the tiles. These are just my thoughts, I have relatively little to no experience with Java.
In your paintComponent() add something like this:
Font f = new Font("Dialog", Font.PLAIN, 12); // choose a font for the numbers
g.setFont(f);
// Draw cell numbers
for (int x = 0; x < TOTAL_COLUMNS; x++) {
for (int y = 0; y < TOTAL_ROWS; y++) {
if (/* check if the (x,y) cell is uncovered */) {
int around = minesAround(x, y);
g.drawString(String.valueOf(around), /*cell x coord*/, /*cell y coord*/);
}
}
}
Alternatively, you can use an image for each cell number instead of using a string.
The program was running fine before I put the Rectangle2D objects in an ArrayList, except that whenever I changed directions, the snake would just rotate rather than bend. Now the snake does not even show up, and my console gives me the error, as provided by Mad Programmer:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException:
Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:638)
at java.util.ArrayList.get(ArrayList.java:414)
at javaapplication968.JavaApplication968$Display.actionPerformed(JavaApplication968.java:110)
I know the issue is related to the ArrayLists, but how do I fix it?
Here is my class:
public class Display extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(1, this);
double xCoord = 50;
double yCoord = 50;
double xvel = 0;
double yvel = .01;
double ranx, xtemp;
double rany, ytemp;
int eaten = 0;
ArrayList<Rectangle2D> rects = new ArrayList<Rectangle2D>();
ArrayList<Double> xloc = new ArrayList<Double>();
ArrayList<Double> yloc = new ArrayList<Double>();
public Display(int xsize, int ysize) {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
xtemp = xsize;
ranx = (xtemp - 15) * Math.random();
ytemp = ysize;
rany = (ytemp - 15) * Math.random();
formSnake();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// Adds snake
g2.setColor(Color.YELLOW);
for (int i = 0; i < rects.size(); i++) {
g2.fill(rects.get(i));
}
// Adds fruit at random location
g2.setColor(Color.BLUE);
g2.fill(new Ellipse2D.Double(ranx, rany, 15, 15));
setBackground(Color.BLACK);
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
// Replaces each rectangle location with one before it
for (int i = rects.size() - 1; i > 0; i--) {
xloc.set(i, xloc.get(i - 1));
yloc.set(i, yloc.get(i - 1));
}
// Sets new head location
xloc.set(0, xloc.get(0) + xvel);
yloc.set(0, yloc.get(0) + yvel);
getEaten();
}
// Adds initial 3 2DRectangles to snake at start of game
public void formSnake() {
for (int i = 0; i < rects.size(); i++) {
xloc.add(xCoord);
yloc.add(yCoord - 16 * i);
rects.add(rects.size(),
new Rectangle2D.Double(xloc.get(i), yloc.get(i), 15, 15));
}
}
// Adds 1 2DRectangle to the front of the snake every time it eats
public void extend() {
// Vertical
if (xvel == 0) {
if (yvel <= 0) { // Up
xloc.add(xloc.get(xloc.size() - 1));
yloc.add(yloc.get(yloc.size() - 1) - 16);
rects.add(new Rectangle2D.Double(xloc.get(xloc.size() - 1),
yloc.get(yloc.size() - 1), 15, 15));
} else
// Down
xloc.add(xloc.get(xloc.size() - 1));
yloc.add(yloc.get(yloc.size() - 1) + 16);
rects.add(new Rectangle2D.Double(xloc.get(xloc.size() - 1), yloc
.get(yloc.size() - 1), 15, 15));
}
// Horizontal
else if (yvel == 0) {
if (xvel <= 0) { // Left
xloc.add(xloc.get(xloc.size() - 1) - 16);
yloc.add(yloc.get(yloc.size() - 1));
rects.add(new Rectangle2D.Double(xloc.get(xloc.size() - 1),
yloc.get(yloc.size() - 1), 15, 15));
} else
// Right
xloc.add(xloc.get(xloc.size() - 1) + 16);
yloc.add(yloc.get(yloc.size() - 1));
rects.add(new Rectangle2D.Double(xloc.get(xloc.size() - 1), yloc
.get(yloc.size() - 1), 15, 15));
}
}
public void getEaten() {
if (Math.abs(xCoord - ranx) < 15 && Math.abs(yCoord - rany) < 15) {
rany = ytemp * Math.random();
ranx = xtemp * Math.random();
eaten++;
extend();
}
}
//Directions
public void up() {
yvel = -0.5;
xvel = 0;
}
public void down() {
yvel = 0.5;
xvel = 0;
}
public void left() {
xvel = -0.5;
yvel = 0;
}
public void right() {
xvel = 0.5;
yvel = 0;
}
//Just for testing purposes
public void stop() {
xvel = 0;
yvel = 0;
}
//Direction implementation
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP || code == KeyEvent.VK_NUMPAD8) {
up();
}
if (code == KeyEvent.VK_DOWN || code == KeyEvent.VK_NUMPAD2) {
down();
}
if (code == KeyEvent.VK_RIGHT || code == KeyEvent.VK_NUMPAD6) {
right();
}
if (code == KeyEvent.VK_LEFT || code == KeyEvent.VK_NUMPAD4) {
left();
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
You seem to be getting a
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:638)
at java.util.ArrayList.get(ArrayList.java:414)
at javaapplication968.JavaApplication968$Display.actionPerformed(JavaApplication968.java:110)
At xloc.set(0, xloc.get(0) + xvel);, because there are no elements the xloc List
Change your formSnake method to do exactly what it says...// Adds initial 3 2DRectangles to snake at start of game instead of using rects.size(), which will be 0 when it's called...
// Adds initial 3 2DRectangles to snake at start of game
public void formSnake() {
for (int i = 0; i < 3; i++) {
xloc.add(xCoord);
yloc.add(yCoord - 16 * i);
rects.add(rects.size(),
new Rectangle2D.Double(xloc.get(i), yloc.get(i), 15, 15));
}
}
I am creating a program that takes draws a polygon and then fills the polygon with green. I am currently having an issue with the algorithm I have written as it only fills the top half of the polygon and then I get an IndexOutOfBounds error.
Here is the code for my algorithm:
public class FillPolygon
{
int left_most_edge, right_most_edge, scan = 0;
double[] xcoord;
double[][] table = new double[4][200]; //2d array containing:
//[0][-] -> ymax, [1][-] -> ymin, [2][-] -> dx, [3][-] -> x
public void initializeTable()
{
int i, j;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 200; j++)
{
table[i][j] = 0;
}//end for
}//end for
}//end initializeTable
public void help(int i)
{
double helpX, helpDX, helpYMax, helpYMin;
for (int j = i - 1; j >= 0; j--)
{
if ((table[1][j] == table[1][j + 1] && table[3][j] > table[3][j + 1]) || table[1][j] > table[1][j + 1])
{
helpYMax = table[0][j];
table[0][j] = table[0][j + 1];
table[0][j + 1] = helpYMax;
helpYMin = table[1][j];
table[1][j] = table[1][j + 1];
table[1][j + 1] = helpYMin;
helpDX = table[2][j];
table[2][j] = table[2][j + 1];
table[2][j + 1] = helpDX;
helpX = table[3][j];
table[3][j] = table[3][j + 1];
table[3][j + 1] = helpX;
}//end if
}//end for
}//end help
public double max (double x, double y)
{ //determines the greater of two values
double max;
if (x > y)
max = x;
else
max = y;
return max;
}//end max
public void edgeInsert(double xStart, double yStart, double xEnd, double yEnd, int number_entered_edges)
{
int j = number_entered_edges - 1; //removing the - 1 removes line on left side
double x;
if (yStart > yEnd)
{
table[0][j] = yStart;
table[1][j] = yEnd;
}//end if
else
{
table[0][j] = yEnd;
table[1][j] = yStart;
}//end else
if (table[1][j] == xStart)
x = xStart;
else
x = xEnd;
if (table[0][j] == yStart)
table[2][j] = -(-(xEnd - xStart) / (yEnd - yStart));
else
table[2][j] = -(xEnd - xStart) / (yEnd - yStart);
table[3][j] = x + table[2][j] / 2;
help(j);
}//end edgeInsert
public void loadTable(int number_vertices, int number_entered_edges,
double[] px, double[] py)
{ //take the x and y coordinats and build an edge table based off of them
int k;
double xStart, yStart, xEnd, yEnd;
xStart = px[number_vertices - 1];
yStart = trunc(py[number_vertices - 1]) + 0.5;
//start off with no edges in edge table
number_entered_edges = 0;
for (k = 0; k < number_vertices; k++)
{
xEnd = px[k];
yEnd = trunc(py[k]) + 0.5;
System.out.println("x: " + xEnd + " y: " + yEnd);
if (yStart == yEnd)
{
xStart = xEnd;
}//end if
else
{
//add edge to edge table
number_entered_edges++;
edgeInsert(xStart, yStart, xEnd, yEnd, number_entered_edges);
yStart = yEnd;
xStart = xEnd;
}//end else
}//end for
scan = (int)trunc(table[1][0]); //start at the top of the polygon
}//end loadTable
public void include(int number_entered_edges)
{ //pushing the right most edge
while ((right_most_edge + 1 < number_entered_edges) && (table[1][right_most_edge + 1] < scan))
{
right_most_edge++;
}//end while
}//end include
public void exclude()
{ //excluding edges that we no longer care about
for (int i = left_most_edge; i <= right_most_edge; i++)
{
if (table[0][i] < scan)
{
left_most_edge++;
for (int j = i; j >= left_most_edge; j--)
{
table[0][j] = table[0][j - 1];
table[2][j] = table[2][j - 1];
table[3][j] = table[3][j - 1];
}//end for
}//end if
}//end for
}//end exclude
public void updateX()
{ //increment x based on dx
for (int i = left_most_edge; i <= right_most_edge; i++)
{
table[3][i] += table[2][i];
}//end for
}//end updateX
public void sortOnX()
{ //sorting x values from least to greatest in edge table
int l = 0;
double t;
xcoord = new double[right_most_edge - left_most_edge + 1];
for (int i = left_most_edge; i <= right_most_edge; i++)
{
xcoord[l] = table[3][i];
for(int j = l - 1; j >= 0; j--)
{
if (xcoord[j] > xcoord[j + 1])
{
t = xcoord[j];
xcoord[j] = xcoord[j + 1];
xcoord[j + 1] = t;
}//end if
}//end for
l++;
}//end for
}//end sortOnX
public void fillScan(Graphics g)
{ //determines the line to be drawn for filling
for (int i = 0; i < xcoord.length; i += 2)
{
drawMyHorizontalLine(g, (int)Math.round(xcoord[i]), scan, (int)Math.round(xcoord[i + 1]));
}//end for
}//end fillScan
public double trunc(double num)
{ //trucates the number passed in to remove any decimal
double rem;
if ((num % 2) == 0)
return num;
else
{
rem = num % 2;
return num - rem;
}//end else
}//end trunc
public void drawMyPolygon(Graphics g)
{ //draws the polygon
g.setColor(Color.RED);
g.drawLine(100, 125, 150, 100); //from (100, 125) to (150, 100)
g.drawLine(150, 100, 250, 200); //from (150, 100) to (250, 200)
g.drawLine(250, 200, 300, 150); //from (250, 200) to (300, 150)
g.drawLine(300, 150, 250, 100); //from (300, 150) to (250, 100)
g.drawLine(250, 100, 150, 200); //from (250, 100) to (150, 200)
g.drawLine(150, 200, 100, 200); //from (150, 200) to (100, 200)
g.drawLine(100, 200, 100, 125); //from (100, 125) to (100, 125)
}//end drawMyPolygon
public void drawMyHorizontalLine(Graphics g, int x1, int y, int x2)
{ //draws the line for filling
g.setColor(Color.GREEN);
g.drawLine(x1, y, x2, y);
}//end drawMyHorizontalLine
public void fillMyPolygon(Graphics g, int number_vertices, int number_entered_edges, double[] px, double[] py)
{ //called methods to deal with edge table and fill the polygon
if (number_entered_edges < 3 || number_entered_edges > 200)
{
System.out.println("Polygon size error");
}//end if
else
{
loadTable(number_vertices, number_entered_edges, px, py);
while (left_most_edge < number_entered_edges)
{
scan++;
exclude();
updateX();
include(number_entered_edges);
sortOnX();
fillScan(g);
}//end while
}//end else
}//end fillMyPolygon
}//end FillPolygon
#Override
public void paint(Graphics g)
{
FillPolygon f = new FillPolygon();
double[] px = new double[7]; //contains all x coord.
double[] py = new double[7]; //contains all y coord.
//populate x coord.
px[0] = 100;
px[1] = 150;
px[2] = 250;
px[3] = 300;
px[4] = 250;
px[5] = 150;
px[6] = 100;
//populate y coord.
py[0] = 125;
py[1] = 100;
py[2] = 200;
py[3] = 150;
py[4] = 100;
py[5] = 200;
py[6] = 200;
f.initializeTable();
f.fillMyPolygon(g, 7, 7, px, py); //begin filling the polygon
f.drawMyPolygon(g); //draw polygon with red outline
}//end paint
I have no idea why I get the error or how to stop it. The error occurs on my line that says "drawMyHorizontalLine(g, (int)Math.round(xcoord[i]), scan, (int)Math.round(xcoord[i + 1]));"
I would really appreciate the help. Thanks.
This loop is your problem. You are walking the array two places at a time (i+= 2), but you are doing it until i < xcoord.length.
So when i == (xcoord.length - 1), that is xcoord[i] is the last element of the array, in your method call to drawMyHorizontalLine, xcoord[i + 1] will be past the end of the array.
public void fillScan(Graphics g)
{ //determines the line to be drawn for filling
for (int i = 0; i < xcoord.length; i += 2)
{
drawMyHorizontalLine(g, (int)Math.round(xcoord[i]), scan, (int)Math.round(xcoord[i + 1]));
}//end for
}//end fillScan
To fix this loop, just change to for(...; i < xcoord.length-1 ;i += 2). This move i two elements at a time as long as there are two elements remaining in the array.
This should fix your out of bounds error, not sure about your polygon only half filling. I don't quite grok your polygon representation.
It's because i + 1 is beyond the bounds of the xcoord array, in the last iteration of that for loop.
I changed your fillScan() method as follows, and it seemed to behave much better (starting with i = 1 and using i - 1 inside the loop, instead of i + 1).
public void fillScan(Graphics g) {
for (int i = 1; i < xcoord.length; i++) {
drawMyHorizontalLine(g, (int) Math.round(xcoord[i-1]),
scan, (int) Math.round(xcoord[i]));
}
}
So I'm trying to implement collision detection in my game and for some reason the collision isnt working properly.
public class ArenaKeys extends KeyAdapter {
arenaScreenBuild arena;
int xPos = 0, playerFace = 4;
int xPPos = 200, yPPos = 150;
int pX = 40, pY = 30;
AttackAshe aAtk = new AttackAshe();
int[][] mask = new int[400][92];
#SuppressWarnings("static-access")
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();// Get key pressed
if (keyCode == e.VK_RIGHT) {
playerFace = 4;
xPos += 5;
pX = (xPos + xPPos) / 5;
if (checkBoundary(pX, pY) == (false))
xPos -= 5;
} else if (keyCode == e.VK_LEFT) {
playerFace = 3;
xPos -= 5;
pX = (xPos + xPPos) / 5;
if (checkBoundary(pX, pY) == (false))
xPos += 5;
} else if (keyCode == e.VK_UP) {
playerFace = 2;
yPPos -= 5;
pY = yPPos / 5;
if (checkBoundary(pX, pY) == (false))
yPPos += 5;
} else if (keyCode == e.VK_DOWN) {
playerFace = 1;
yPPos += 5;
pY = yPPos / 5;
if (checkBoundary(pX, pY) == (false))
yPPos -= 5;
}
if (keyCode == e.VK_SPACE) {
aAtk.regArrow(arena.xPosition(), arena.yPosition());
arena.shoot(playerFace);
arena.xArrow = xPPos;
arena.yArrow = yPPos;
} else if (keyCode == e.VK_ESCAPE)
System.exit(0);
arena.moveArena(xPos);
arena.turnPlayer(playerFace);
arena.updateScreen(xPPos, yPPos);
}
public boolean checkBoundary(int x, int y) {
Rectangle t1 = new Rectangle(Turret.x, Turret.y, Turret.WIDTH,
Turret.HEIGHT);
Rectangle p = new Rectangle(pX, pY, Player.WIDTH, Player.HEIGHT);
if (t1.intersects(p))
// if (mask[x][y] == 0)
return false;
else
return true;
}
public static class Turret {
static int x = 168;
static int y = 40;
static final int WIDTH = 50;
static final int HEIGHT = 50;
}
public static class Player {
static final int WIDTH = 25;
static final int HEIGHT = 25;
}
public ArenaKeys(arenaScreenBuild arena) throws Exception {
this.arena = arena;
}
}
Approximately 20 units before the actual turret, the sprite stops being able to move any further. The sprite cannot go above or below the turret even if you go really high or really low.
What seems to be going wrong is that the sprite is colliding into the turret rectangle too early but I don't understand how that it possible. I draw the turret exactly 50 wide, 50 high at 168,40. The player is moving so it's x, y is different everytime but it's dimensions are 25 wide and 25 high.
The original turret is 126x111 approximately but I draw it as 50x50
25x25
public class arenaScreenBuild extends JPanel implements ActionListener {
String picPath = "pictures/";
String[] fileName = { "stageBridge.png", "turret.png", "Ashe.png",
"regArrow.png", "arenaScreen.png" };
ClassLoader cl = arenaScreenBuild.class.getClassLoader();
URL imgURL[] = new URL[5];
Toolkit tk = Toolkit.getDefaultToolkit();
Image imgBG, imgTurret, imgPlayer, imgRegArrow, imgBorder;
Boolean[] ptFunc = new Boolean[3];
int PLAYER_INITIAL_X = 200, PLAYER_INITIAL_Y = 150;
int xPos = 0, xPFace = 150, yPFace = 0;
int xPPos = 200, yPPos = 150;
int xVal, yVal, xArrow, yArrow, xTemp, yTemp;
Timer space;
int counter, facePosition = 1;
public arenaScreenBuild() throws Exception {
for (int x = 0; x < 5; x++) {
imgURL[x] = cl.getResource(picPath + fileName[x]);
}
imgBG = tk.createImage(imgURL[0]);
imgTurret = tk.createImage(imgURL[1]);
imgPlayer = tk.createImage(imgURL[2]);
imgRegArrow = tk.createImage(imgURL[3]);
imgBorder = tk.createImage(imgURL[4]);
for (int x = 0; x < 3; x++)
ptFunc[x] = true;
space = new Timer(100, this);
}
public void updateScreen() {
repaint();
}
public void moveArena(int x) {
xPos = x;
}
public void updateScreen(int x, int y) {
xPPos = x;
yPPos = y;
repaint();
}
public boolean arrow() {
return (true);
}
public void turnPlayer(int face) {
if (face == 4) {
xPFace = 150;
} else if (face == 3) {
xPFace = 100;
} else if (face == 2) {
xPFace = 50;
} else if (face == 1) {
xPFace = 0;
}
if (yPFace == 50)
yPFace = 0;
else if (yPFace == 0)
yPFace = 50;
}
public void paintComponent(Graphics g) {
g.drawImage(imgBG, 10, 30, 610, 490, xPos, 0, xPos + 600, 460, this);
g.drawImage(imgTurret, 850 - xPos, 200, 950 - xPos, 300, 0, 0, 126,
110, this);
g.drawImage(imgTurret, 1350 - xPos, 200, 1450 - xPos, 300, 0, 0, 126,
110, this);
g.drawImage(imgPlayer, xPPos, yPPos, 50 + (xPPos),
50 + (yPPos), xPFace, yPFace, xPFace + 50, yPFace + 50, this);
if (counter <= 5000 && counter > 0)
g.drawImage(imgRegArrow, xArrow, yArrow, this);
g.drawImage(imgBorder, 0, 0, 620, 600, 0, 0, 620, 600, this);
g.setColor(Color.WHITE);
g.drawString("x:" + (xPPos + xPos), 535, 525);
g.drawString("y:" + yPPos, 535, 545);
}
public int xPosition() {
xVal = xPPos + xPos;
return (xVal);
}
public int yPosition() {
yVal = yPPos;
return (yVal);
}
public void shoot(int i) {
facePosition = i;
xTemp = xPosition();
yTemp = yPosition();
space.start();
}
public void actionPerformed(ActionEvent e) {
counter++;
if (facePosition == 4) {
if (counter <= 5000) {
xArrow += 50;
}
}
else if (facePosition == 3) {
if (counter <= 5000) {
xArrow -= 50;
}
}
else if (facePosition == 2) {
if (counter <= 5000) {
yArrow -= 50;
}
}
else if (facePosition == 1) {
if (counter <= 5000) {
yArrow += 50;
}
}
if (xArrow == (xTemp + 100)) {
counter = 0;
space.stop();
}
updateScreen();
}
}
Turns out that my values for the x position were wrong. Also due to my previous boundary code, there were still remenants of it which messed me up therefore not allowing me to see the problem sooner.
For any one looking for how to make the collision detection boundary, just make 2 rectangles and use the
Rectangle rect1 = new Rectangle(topLeftX, topLeftY, rectangleWidth,rectangleHeight);
Rectangle rect2 = new Rectangle(topLeftX, topLeftY, rectangleWidth, rectangleHeight);
if (rect1.intersects(rect2))
//enter code to do if it intersects here