Here the error i am getting...
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Maze.Map.readFile(Map.java:60)
at Maze.Map.<init>(Map.java:23)
at Maze.Board.<init>(Board.java:16)
at Maze.Maze.<init>(Maze.java:15)
at Maze.Maze.main(Maze.java:9)
Below is my code!
package Maze;
import javax.swing.*;
public class Maze
{
public static void main(String[] args)
{
new Maze();
}
public Maze()
{
JFrame f = new JFrame();
f.setTitle("Maze Game");
f.add(new Board());
f.setSize(464, 485);
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
package Maze;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel implements ActionListener
{
private Timer timer;
private Map m;
public Board()
{
m = new Map();
timer = new Timer(25, this);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
for(int y = 0; y < 14; y++)
{
for(int x = 0; x < 14; x++)
{
if(m.getMap(x, y).equals("g"))
{
g.drawImage(m.getFloor(), x * 32, y * 32, null);
}
if(m.getMap(x, y).equals("w"))
{
g.drawImage(m.getWall(), x * 32, y * 32, null);
}
}
}
}
}
package Maze;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.ImageIcon;
public class Map
{
private Scanner m;
private String Map[] = new String[14];
private Image floor,
wall;
public Map()
{
ImageIcon img = new ImageIcon("C://Test//MazeGame//floor.jpg");
floor = img.getImage();
img = new ImageIcon("C://Test//MazeGame//wall.jpg");
wall = img.getImage();
openFile();
readFile();
closeFile();
}
public Image getFloor()
{
return floor;
}
public Image getWall()
{
return wall;
}
public String getMap(int x, int y)
{
String index = Map[y].substring(x, x + 1);
return index;
}
public void openFile()
{
try
{
m = new Scanner(new File("C://Test//MazeGame//Map.txt"));
}catch(Exception e)
{
System.out.print("Error Loading Map!");
}
}
public void readFile()
{
while(m.hasNext())
{
for(int i = 0; i < 14; i++)
{
Map[i] = m.next();
}
}
}
public void closeFile()
{
m.close();
}
}
I don't know if this is your error (you haven't told us which line is line 60 of your Map class, the line that is causing your exception), but this is dangerous code:
while(m.hasNext())
{
for(int i = 0; i < 14; i++)
{
Map[i] = m.next();
}
}
You're calling hasNext() once per loop iteration, but calling next() 14 times! There should be a strict 1 to 1 correlation in that each next() should match with a preceding hasNext().
Also, there's no reason for the nested for loop since the while loop will handle all you need. You probably would get by with something like:
int i = 0;
while(m.hasNext()) {
Map[i] = m.next();
i++;
}
But it would be safer to use an ArrayList rather than an array.
As an aside, please learn and follow Java coding conventions. Methods and fields/variables/parameters should all start with a lower-case letter, so Map[i] is not allowed, but rather should be map[i]. Doing this will help us to better understand and follow your code and thus help you.
Related
I don't really understand why this program draws three pawns instead of one and two of which seem to have a random(probably not so random) positions. enter image description here
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GamePanel extends JPanel implements MouseListener {
static final int SCREEN_EDGE = 800;
static final int GAME_UNITS = 64;
static final int UNIT_SIZE = 100;
final int[] x = new int[GAME_UNITS];
final int[] y = new int[GAME_UNITS];
boolean running = false;
public GamePanel() {
this.setPreferredSize(new Dimension(SCREEN_EDGE, SCREEN_EDGE));
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
int[] position = {0,0};
int[] position1 = {1, 0};
new Pawn(position,-1);
}
private void startGame() {
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g){
int counter = 1;
for (int y = 0; y < SCREEN_EDGE/UNIT_SIZE; y++) {
// 1 == "white" 2 == "black"
int color = (y % 2 == 0) ? 1 : 2;
for (int x = 0; x < SCREEN_EDGE/UNIT_SIZE; x++) {
g.setColor(color == 1 ? new Color(239,217, 181) : new Color(180, 136,98));
g.fillRect(x*UNIT_SIZE, y*UNIT_SIZE, UNIT_SIZE, UNIT_SIZE);
color = color == 1 ? 2 : 1;
}
}
for (int i = 0; i < Figure.figures.length; i++) {
JLabel figureSprite = new JLabel(Figure.figures[i].image, JLabel.CENTER);
figureSprite.setSize(90,90);
figureSprite.setLocation(Figure.figures[i].position[0] + 5,Figure.figures[i].position[1] + 5);
this.add(figureSprite);
}
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
public class MyKeyAdapter extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
}
}
}
import javax.swing.*;
public abstract class Figure{
protected int value;
protected ImageIcon image;
protected int[][] possibleMoves;
public int[] position;
// white = -1 black = 1
protected int whiteOrBlack;
protected static int figureCount = 1;
// int[figureCount][0 = x][1 = y][2 = color]
public static Figure[] figures = new Figure[figureCount];
public Figure(int value, int[] position, int[][] possibleMoves , int whiteOrBlack) {
this.value = value;
this.position = position;
this.possibleMoves = possibleMoves;
this.whiteOrBlack = whiteOrBlack;
Figure[] oldFigures = figures;
figures = new Figure[figureCount];
for (int i = 0; i < oldFigures.length; i++) {
figures[i] = oldFigures[i];
}
figures[figureCount - 1] = this;
figureCount++;
}
public abstract void move(int[] coordinates);
}
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class Pawn extends Figure{
public Pawn(int[] position, int whiteOrBlack) {
super(1, position, new int[3][2], whiteOrBlack);
super.image = new ImageIcon(getClass().getClassLoader().getResource("graphics/" + (whiteOrBlack == -1 ? "whitePawn.png" : "blackPawn.png")));
Image newImage = super.image.getImage().getScaledInstance(90,90, Image.SCALE_AREA_AVERAGING);
super.image = new ImageIcon(newImage);
}
public void checkMoves(){
for (int i = 0; i < figures.length; i++) {
if((position[0] - 1) == figures[i].position[0] && (position[1] + this.whiteOrBlack) == figures[i].position[1] && figures[i].whiteOrBlack != this.whiteOrBlack) {
possibleMoves[0][0] = position[0] - 1;
possibleMoves[0][1] = position[1] + this.whiteOrBlack;
}else possibleMoves[0] = new int[2];
if((position[0]) != figures[i].position[0] && (position[1]) != figures[i].position[1]){
possibleMoves[1][0] = position[0];
possibleMoves[1][1] = position[1] + 1;
}else possibleMoves[1] = new int[2];
if((position[0] + 1) == figures[i].position[0] && (position[1] + this.whiteOrBlack) == figures[i].position[1] && figures[i].whiteOrBlack != this.whiteOrBlack) {
possibleMoves[2][0] = position[0] + 1;
possibleMoves[2][1] = position[1] + this.whiteOrBlack;
}else possibleMoves[2] = new int[2];
}
}
#Override
public void move(int[] coordinates) {
}
}
import javax.swing.*;
public class GameFrame extends JFrame {
public GameFrame(){
this.add(new GamePanel());
this.setTitle("Chess");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setResizable(false);
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
public class ChessGame {
public static void main(String[] args) {
new GameFrame();
}
}
I tried few thing like changing JLabel to BufferedImage but it would've generate other problems down the line like not being able to use MouseListener so i feel stuck. I would love to know why this code generates 3 textures too.
It looks like you are adding FigureSprites from within the drawComponent() method. The more often you draw the window, the more figures you have to draw.
Instead within drawComponent() just draw the current state but do not modify it. Adding figures has to come from somewhere else. For example, you could create the necessary pawns in the constructor. Or in extra methods that might get triggered based on user input.
In case you modify the GamePanel's state enough so that it should get painted freshly, just invoke repaint(). Swing will mark this component for repainting and decide on it's own when to run the paint() method, which in turn will run paintComponent().
I'm a beginning Java programmer. I'm trying to construct a Space Invaders game that can be played directly in the console. Later, I would like to add a graphical interface through JFrame; however, at this time, I have restricted myself to creating a non-functional JFrame window. I have the classes saved in a few files - Constants.java, Entity.java, Player.java, and Board.java, SpaceInvaders.java - and I have compiled these files in the specified order. My problem is that when I attempt to run the main method, nothing is shown. No window pops up. No output is displayed in the console. I suspect that the problem lies in the class Board, perhaps in the thread construction in the method gameInit() or in the method run(). I cannot find any information regarding threads in my course textbook - I obtained the thread code from the website http://zetcode.com/tutorials/javagamestutorial/spaceinvaders/ and I will cite it in my final version of the project.
Do let me know if you can offer me any pointers. I apologize for my lack of familiarity with the formatting of stackoverflow.com.
I've enclosed a copy of my code below.
Constants.java
import java.io.*;
public interface Constants {
public static final int MOTION_WIDTH = 20;
public static final int MOTION_LENGTH = 20;
public static final int DELAY = 17;
}
Entity.java
import java.io.*;
public class Entity {
private int xPosition;
private int yPosition;
public void setXPosition(int newXPosition) {
this.xPosition = newXPosition;
}
public int getXPosition() {
return xPosition;
}
public void setYPosition(int newYPosition) {
this.yPosition = newYPosition;
}
public int getYPosition() {
return yPosition;
}
}
Player.java
import java.io.*;
import java.awt.event.KeyEvent;
public class Player extends Entity implements Constants{
private final int START_X_POSITION = 0;
private final int START_Y_POSITION = 0;
int x = 0;
public Player() {
setXPosition(START_X_POSITION);
setYPosition(START_Y_POSITION);
}
public void move() {
setXPosition((getXPosition()) + x);
if ((getXPosition()) <= 0) {
setXPosition(0);
}
if ((getXPosition()) >= MOTION_WIDTH) {
setXPosition(MOTION_WIDTH);
}
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
x = 1;
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
x = -1;
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
x = 0;
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
x = 0;
}
}
}
Board.java
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
public class Board extends JPanel implements Runnable, Constants {
Player player;
boolean gameRunning = true;
Thread animator;
char[][] motion = new char[MOTION_WIDTH][MOTION_LENGTH];
public Board() {
addKeyListener(new KeyListener());
setFocusable(true);
gameInit();
setDoubleBuffered(true);
}
//Ensure that I cite this
public void addNotify() {
super.addNotify();
gameInit();
}
public void gameInit() {
player = new Player();
for (int i = 0; i < MOTION_WIDTH; i++) {
for (int j = 0; j < MOTION_LENGTH; j++) {
motion[i][j] = '0';
}
}
motion[0][0] = '^';
if (animator == null) {
animator = new Thread(this);
animator.start();
}
}
private class KeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
player.keyPressed(e);
}
public void keyReleased(KeyEvent e) {
player.keyReleased(e);
}
}
public void paint() {
for (int i = 0; i < MOTION_WIDTH; i++) {
for (int j = 0; j < MOTION_LENGTH; j++) {
motion[i][j] = '0';
}
}
motion[player.getXPosition()][player.getYPosition()] = '^';
for (int i = 0; i < MOTION_WIDTH; i++) {
for (int j = 0; j < MOTION_LENGTH; j++) {
System.out.print(motion[i][j]);
}
System.out.println();
}
}
public void animationCycle() {
player.move();
paint();
}
//Ensure that I cite this
public void run() {
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (gameRunning) {
paint();
animationCycle();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - timeDiff;
if (sleep < 0)
sleep = 2;
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
beforeTime = System.currentTimeMillis();
}
}
}
SpaceInvaders.java
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
public class SpaceInvaders extends JFrame implements Constants {
public void SpaceInvaders() {
add(new Board());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
requestFocusInWindow();
}
public static void main(String[] args) {
new SpaceInvaders();
}
}
In the class SpaceInvaders the constructor you provided is not really a constructor. Please remove the return-type void. So it should read
public SpaceInvaders() {
add(new Board());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
requestFocusInWindow();
}
public static void main(String[] args) {
new SpaceInvaders();
}
Here is an info on constructors from the Java docs:
A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
(https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html)
With the modification applied the JFrame shows up and also a lot of 0 and a ^ are printed on the console.
I don't see the thread start in your code. I think you have to start the thread as below example
class Board implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Board b1=new Board();
Thread t1 =new Thread(b1);
t1.start();
}
}
And also the construct should not have the return type
public void SpaceInvaders() {
}
change to
public SpaceInvaders() {
}
I am currently working on creating the game Snake. I had the idea of creating a basic 2-dimensional arraylist so I can create cells but I can't find any form of help on creating that 2d arraylist to store the x and y values of each of the cells. I need help on how to create that 2d arraylist and how to use it.
Snake.java
package snake;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.List;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Snake extends JPanel implements KeyListener {
private static final long serialVersionUID = 1L;
static final int BOX_WIDTH = 600;
static final int BOX_HEIGHT = BOX_WIDTH;
int UPDATE_RATE = 300;
ArrayList<Cell> CellList = new ArrayList<Cell>();
//ode below????
//2d arrayList
ArrayList[][] Cell = new ArrayList[10][10];
public Snake() {
setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT));
/*for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
CellList.add(new Cell(i,j));
}
} */
Thread gameThread = new Thread() {
public void run() {
while(true){
repaint();
try {Thread.sleep(1000/UPDATE_RATE);}
catch (InterruptedException ex) {}
}
}
};
gameThread.start();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("SNEK");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Snake snake = new Snake();
frame.setContentPane(snake);
frame.setSize(BOX_WIDTH, BOX_HEIGHT);
frame.pack();
frame.addKeyListener(snake);
frame.setVisible(true);
}
});
}
public void paintComponent(Graphics g) {
g.setColor(Color.pink);
g.fillRect(0, 0, BOX_WIDTH, BOX_HEIGHT);
/*for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
CellList.get(i,j).draw(g);
}
} */
}
#Override
public void keyPressed(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {}
}
Cell.java
package snake;
import java.awt.Color;
import java.awt.Graphics;
public class Cell extends Snake{
private static final long serialVersionUID = 1L;
final int CELL_HEIGHT = 10;
final int CELL_WIDTH = 10;
int status = 0;
int xPos;
int yPos;
public Cell(int x, int y) {
xPos = x * 120;
yPos = y * 120;
}
public void draw(Graphics g) {
g.setColor(Color.magenta);
g.fillRect(xPos, yPos, CELL_WIDTH, CELL_HEIGHT);
}
}
If you want to make games using java, I suggest you to use game-development application framework-libGDX
Download: https://libgdx.badlogicgames.com/download.html
It's easy to use, plus you build games for desktop,android,ios and html at the same time.There are lots of tutorial on YouTube about libGDX.
Here are some of them:
https://www.youtube.com/watch?v=QKK4kDogg-8&list=PLaNw_AbDFccHbzuObI4xHHp6WtiN2cRQv
https://www.youtube.com/watch?v=EJwXzmUQChg&list=PLXY8okVWvwZ0JOwHiH1TntAdq-UDPnC2L
https://www.youtube.com/watch?v=a8MPxzkwBwo&list=PLZm85UZQLd2SXQzsF-a0-pPF6IWDDdrXt
You most certainly don't need a 2d array list.
Instead, you need a 2d array of Cells:
Instead of this:
ArrayList[][] Cell = new ArrayList[10][10];
Use this:
Cell[][] cells = new Cell[10][10];
Then in the constructor:
public Snake() {
setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT));
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
cells[i][j] = new Cell(/*do what ever you ned here*/);
}
}
...
I need help changing the color of a rectangle in a grid. So far, I have the rectangles and the grid (which are lines drawn separating the rectangles), and I want to change the color of a single rectangle when it's clicked.
I added the line "System.out.println("Something")" in the loop where the color is supposed to change, and it always returns "Something." That's why I'm confused. Thanks for any and all help!
Class Grid:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.Timer;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Grid extends JPanel{
private int a = 50;
private int b = 50;
private Lifeform[][] Life;
private boolean[][]life = new boolean[a][b];
private Timer t;
Grid(){
//creates grid of rectangles
Life = new Lifeform[a][b];
int ypos = 0;
for(int i = 0; i < Life.length; i++){
int xpos = 0;
for(int j = 0; j < Life[0].length; j++){
Rectangle r = new Lifeform();
r.setBounds(xpos, ypos, 50, 50);
Life[i][j] = (Lifeform) r;
xpos += 50;
}
ypos += 50;
}
t = new Timer(64, new Movement());
this.addMouseListener(new mouse());
}
public void paintComponent(Graphics g){
for(Lifeform[] n : Life){
//makes rectangles white
g.fillRect(this.getX(), this.getY(), this.getWidth(), this.getHeight());
g.setColor(Color.white);
}
for (int i = 0; i <= 25; i++){
g.drawLine(0, 50*i, 1500, 50*i);
g.setColor(Color.black);
}
for (int i = 0; i <= 25; i++){
g.drawLine(50*i, 0, 50*i, 750);
g.setColor(Color.black);
}
}
private JFrame createGrid(){
JFrame frame = new JFrame("Alveolate");
frame.add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,700);
frame.setVisible(true);
return frame;
}
public class mouse implements MouseListener{
//colors rectangles (it doesn't work)
public void mouseClicked(MouseEvent e) {
Point p = new Point(e.getX(),e.getY());
for(int i = 0; i < Life.length; i++){
for(int j = 0; j < Life[i].length; j++){
Lifeform spot = Life[i][j];
if (spot.contains(p)){
spot.setColor(Color.red);
System.out.println("Something");
}
}
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
public class Movement implements ActionListener{
public void actionPerformed ( ActionEvent e ){
for (int i = 0; i < Life.length; i++){
for (int j = 0; j < Life[i].length; j++){
if(Life[i][j].getColor().equals(Color.black)){
life[i][j] = true;
}
else{
life[i][j] = false;
}
}
}
repaint();
}
}
public void startTimer(){
t.start();
}
public void stopTimer(){
t.stop();
}
public static void main(String[] args) {
Grid ABC = new Grid();
ABC.createGrid();
ABC.startTimer();
}
}
Class Lifeform:
import java.awt.Color;
import java.awt.Rectangle;
public class Lifeform extends Rectangle {
private Color c;
public Lifeform() {
c = Color.WHITE;
}
public Color getColor() {
return c;
}
public boolean setColor( Color c ) {
boolean rtn = false;
if( c != null ) {
this.c = c;
rtn = true;
}
return rtn;
}
}
try
for(Lifeform[] n : Life){
for(Lifeform lf : n){
g.setColor(lf.getColor());
g.fillRect((int)lf.getX(), (int)lf.getY(), (int)lf.getWidth(), (int)lf.getHeight());
}
}
in your paintComponent method
try this:
for(int i = 0; i < 50; i++){
for(int j = 0; j < 50; j++){
....
}
}
Didn't read all you code but it seems like you definitely set the color of your Lifeform to red. This means that your rendering code never actually uses this fact to display that Lifeform. It seems like the only time you draw your rectangles is in paintComponent. This paint needs to be called each time you want a redraw to happen. You can use repaint on your JFrame or JPanel to get this to happen. Also, the render code you have there seems to only ever display white rectangles
g.fillRect(this.getX(), this.getY(), this.getWidth(), this.getHeight());
g.setColor(Color.white);
This is in a loop through your Lifeform[][]. Instead you should probably have a double for loop to get every Lifeform and use the x and y and color from that to draw. Something like:
g.fillRect(Life[i][j].getX(), Life[i][j].getY(), ..., ..., Life[i][j].getColor())
Also, Life should be named life with a lowercase 'l'. It's way confusing seeing names without conventions.
This my code for the simple maze game. Its being compiled and class file of MazeGame.java and Board.java are being created but not of Player.java and Map.java. The code is being compiled error free but its not running. Please help me out.
//MazeGame.java
package mygame;
import javax.swing.*;
public class MazeGame {
public static void main(String[] args) {
new MazeGame();
}
public MazeGame() {
JFrame f= new JFrame();
f.setTitle("Maze Game");
f.setSize(450,450);
f.setLocationRelativeTo(null);
f.add(new Board());
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
//Board.java
package mygame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.*;
public class Board extends JPanel implements ActionListener {
private Timer timer;
private Map m;
private Player p;
private boolean win=false;
private String Message="";
private Font font = new Font("Comic Sans",Font.BOLD,50);
public Board() {
m = new Map();
p = new Player();
addKeyListener(new Al());
setFocusable(true);
timer = new Timer(25,this);
timer.start();
}
public void paint(Graphics g)
{
super.paint(g);
if(!win)
{
for(int y=0; y<14; y++) {
for(int x=0; x<14; x++) {
if(m.getMap(x,y).equals("f")) {
g.drawImage(m.getFinish(),x*32,y*32,null);
}
if(m.getMap(x,y).equals("g")) {
g.drawImage(m.getGrass(),x*32,y*32,null);
}
if(m.getMap(x,y).equals("w")) {
g.drawImage(m.getWall(),x*32,y*32,null);
}
}
}
g.drawImage(p.getPlayer(),p.getTileX()*32,p.getTileY()*32,null);
}
if(win)
{
g.setColor(Color.BLUE);
g.setFont(font);
g.drawString(Message,100,300);
}
}
public class Al extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if((keyCode==KeyEvent.VK_W) || (keyCode==KeyEvent.VK_UP)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(0,-1);
}
}
if((keyCode==KeyEvent.VK_S) || (keyCode==KeyEvent.VK_DOWN)) {
if(!(m.getMap(p.getTileX(),p.getTileY()+1).equals("w"))) {
p.move(0,1);
}
}
if((keyCode==KeyEvent.VK_A) || (keyCode==KeyEvent.VK_LEFT)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(-1,0);
}
}
if((keyCode==KeyEvent.VK_D) || (keyCode==KeyEvent.VK_RIGHT)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(1,0);
}
}
}
}
public void actionPerformed(ActionEvent e) {
if(m.getMap(p.getTileX(),p.getTileY()).equals("f")) {
Message = "WINNER!!!";
win = true;
}
repaint();
}
}
//Map.java
package mygame;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.*;
public class Map {
private Scanner s;
private String Map[] = new String[14];
private Image grass,wall,finish;
public Map() {
ImageIcon img = new ImageIcon("G://sonali_java//mygame//grass.png");
grass = img.getImage();
img = new ImageIcon("G://sonali_java//mygame//wall.png");
wall = img.getImage();
img = new ImageIcon("G://sonali_java//mygame//finish.png");
finish = img.getImage();
openFile();
readFile();
closeFile();
}
public String getMap(int x,int y) {
String index = Map[y].substring(x,x+1);
return index;
}
public Image getGrass() {
return grass;
}
public Image getWall() {
return wall;
}
public Image getFinish() {
return finish;
}
public void openFile() {
try {
s= new Scanner(new File("G://sonali_java//mygame//Map.txt"));
}
catch(Exception e) {
System.out.println("Error Loading File!!!!");
}
}
public void readFile() {
while(s.hasNext()) {
for(int i=0; i<14; i++) {
Map[i] = s.next();
}
}
}
public void closeFile() {
s.close();
}
}
//Player.java
package mygame;
import java.awt.*;
public class Player {
private int tileX,tileY;
private Image player;
public Player() {
tileX=1;
tileY=1;
ImageIcon img = new ImageIcon("G://sonali_java//mygane//object.png");
player = img.getImage();
}
public Image getPlayer() {
return player;
}
public int getTileX() {
return tileX;
}
public int getTileY() {
return tileY;
}
public void move(int dx, int dy) {
tileX += dx;
tileY += dy;
}
}
I dont want to be mad but you are defining different folder locations
in some places "G://sonali_java//mygane//object.png", check "mygaNe"
in some places "G://sonali_java//mygame//Map.txt", check "mygaMe"
Are you sure while loading it does not throw a NullPointerException ?
Are you aware that you can, place code like
public void draw(Graphics g){
g.drawImage(playerImg, getX(), getY(), null);
}
in your player class, thus leaving the player class with drawing the player and simply calling the players draw method inside your Board paint method? This can also be done for drawing the map. Remember to call the draw methods in the paint method.
ALSO, THIS
ImageIcon img = new ImageIcon("G://sonali_java//mygane//object.png");
check your directory location