Я пытаюсь нарисовать двухмерную карту плиток из файла .txt в Java, но она использует только одну из плиток на карте, а нJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Я пытаюсь нарисовать двухмерную карту плиток из файла .txt в Java, но она использует только одну из плиток на карте, а н

Сообщение Anonymous »

Я просматриваю руководство по 2D-играм на Java от ryisnow на YouTube.
Мне удалось отобразить каждую плитку отдельно, но я не знаю, почему .txt не работает
вот пакет map01.txt

Код: Выделить всё

1001111111111111
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000002222000001
1000002222000001
1000002222000001
1000002222000001
1111111111111111

это мой пакет Tile.java

Код: Выделить всё

package tile;

import java.awt.image.BufferedImage;

public class Tile {

public BufferedImage image;
public boolean collision = false;
}

это мой TileManager.java

Код: Выделить всё

package tile;

import java.awt.Graphics2D;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.imageio.ImageIO;

import main.GamePanel;

public class TileManager {

GamePanel gp;
Tile[] tile;
int mapTileNum[][];

public TileManager(GamePanel gp) {

this.gp = gp;

tile = new Tile[10];
mapTileNum = new int[gp.maxScreenCol][gp.maxScreenRow];

getTileImage();
loadMap();
}

public void getTileImage() {

try {

tile[0] = new Tile();
tile[0].image = ImageIO.read(getClass ().getResourceAsStream("/tiles/Grass.png"));

tile[1] = new Tile();
tile[1].image = ImageIO.read(getClass ().getResourceAsStream("/tiles/Wall.png"));

tile[2] = new Tile();
tile[2].image = ImageIO.read(getClass ().getResourceAsStream("/tiles/Water.png"));

}catch(IOException e) {
e.printStackTrace();
}
}
public void loadMap() {

try {
InputStream is = getClass().getResourceAsStream("/maps/map01.txt");
BufferedReader br = new BufferedReader( new InputStreamReader(is));

int col = 0;
int row = 0;

while(col < gp.maxScreenCol && row < gp.maxScreenRow) {

String line = br.readLine();

while(col < gp.maxScreenCol) {

String numbers[] = line.split(" ");

int num = Integer.parseInt(numbers[col]);

mapTileNum[col][row] = num;
col++;
}
if(col == gp.maxScreenCol) {
col = 0;
row++;
}
}
br.close();

}catch(Exception e) {

}

}
public void draw(Graphics2D g2) {

int col = 0;
int row = 0;
int x = 0;
int y = 0;

while(col < gp.maxScreenCol && row < gp.maxScreenRow) {

int tileNum = mapTileNum[col][row];

g2.drawImage(tile[tileNum].image, x, y, gp.tileSize, gp.tileSize, null);
col++;
x += gp.tileSize;

if(col == gp.maxScreenCol) {
col = 0;
x = 0;
row++;
y += gp.tileSize;
}
}
}

}
а вот мой пакет GamePanel.java

Код: Выделить всё

package main;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

import entity.Player;
import tile.TileManager;

public class GamePanel extends JPanel implements Runnable{

// SCREEN SETTINGS
final int originalTileSize = 16; // 16x16 tile
final int scale = 3;

public final int tileSize = originalTileSize * scale; // 48x48 tile
public final int maxScreenCol = 16;
public final int maxScreenRow = 12;
public final int screenWidth = tileSize * maxScreenCol; // 768 pixels
public final int screenHeight = tileSize * maxScreenRow;  // 576 pixels

// FPS
int FPS = 60;

TileManager tileM = new TileManager(this);
KeyHandler keyH = new KeyHandler();
Thread gameThread;
Player player = new Player(this,keyH);

public GamePanel() {

this.setPreferredSize(new Dimension(screenWidth, screenHeight));
this.setBackground(Color.white);
this.setDoubleBuffered(true);
this.addKeyListener(keyH);
this.setFocusable(true);
}

public void startGameThread() {

gameThread = new Thread(this);
gameThread.start();
}

@Override
//  public void run() {
//
//      double drawInterval = 1000000000/FPS; //0.0166666 seconds
//      double nextDrawTime = System.nanoTime() + drawInterval;
//
//      while(gameThread != null) {
//
//
//
//          // UPDATE: update information such as character positions
//          update();
//
//          // 2 DRAW: draw the screen with the update information
//          repaint();
//
//
//          try {
//              double remainingTime = nextDrawTime - System.nanoTime();
//              remainingTime = remainingTime/1000000;
//
//              if(remainingTime < 0) {
//                  remainingTime = 0;
//              }
//              Thread.sleep((long) remainingTime);
//
//              nextDrawTime += drawInterval;
//
//          } catch (InterruptedException e) {
//              e.printStackTrace();
//          }
//      }
//
//  }

public void run() {

double drawInterval = 1000000000/FPS;
double delta = 0;
long lastTime = System.nanoTime();
long currentTime;
long timer = 0;
int drawCount =0;

while(gameThread != null) {

currentTime = System.nanoTime();

delta += (currentTime - lastTime) / drawInterval;
timer += (currentTime - lastTime);
lastTime = currentTime;

if(delta >= 1) {
update();
repaint();
delta--;
drawCount++;
}

if(timer >= 1000000000) {
System.out.println("FPS:" + drawCount);
drawCount = 0;
timer = 0;
}

}
}

public void update() {

player.update();

}
public void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2= (Graphics2D)g;

tileM.draw(g2);

player.draw(g2);

g2.dispose();
}

}
Мне казалось, что я правильно выполнил руководство, но оно не соответствует текстовому файлу.
как это должно выглядеть:
Изображение

как выглядит мой:
[img]https://i.sstatic. net/8RLgGZTK.jpg[/img]


Подробнее здесь: https://stackoverflow.com/questions/788 ... ly-using-o
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»