I am making a 2D game and I've decided implementing a player-following camera to it, so you can explore a big map, and load a small part of the map in the window.
But now I have a little problem, I want the map to follow the player, so the player is always centered, example on how it should look like this but a bit more centered ( did it in paint) :
(source: gyazo.com)
But currently it looks like this:
(source: gyazo.com)
Because offX & offY = 0, I need to think of a formula to make the camera centered by the player.
This is how I work out (move the camera), right in the drawMap method:
private void renderMap(Graphics2D g) {
int[][] tiledMap = this.map.getMap();
for (int i = 0; i < this.map.getHeight(); i++) {
for (int j = 0; j < this.map.getWidth(); j++) {
int currentRow = tiledMap[i][j] ;
if (currentRow == 0) {
g.drawImage(img, (j + offX) * map.getTileSize(), (i + offY) * map.getTileSize(), this);
}
if (currentRow == 1) {
g.setColor(Color.green);
g.fillRect((j + offX) * map.getTileSize(),
(i + offY) * map.getTileSize(), map.getTileSize(),
map.getTileSize());
}
}
}
}
Basically it ads the offX to the tile x and offY to the tile y.
The tilesize is 30 px, so the map is moving by tile size which is a problem I need to sort aswell, OR just move the player by the tile size, and then the walking will be just too fast, because the camera can only load by one tile, if we move one tile per player movement, the camera eventually won't stay centred to the player.
How can I make the camera be centred all the time to the player?
This is my code:
package snow;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.swing.JPanel;
public class GameController extends JPanel {
private static final long serialVersionUID = 1L;
private Player myPlayer = new Player(5, 5, 25, 25);
private TileMap map;
private Image img;
public GameController() {
this.map = new TileMap(new File("src/snow/Tiles/map1.txt"));
try {
this.img = ImageIO.read(new File("data/snow.png"));
} catch (IOException e1) {
e1.printStackTrace();
}
try {
this.map.buildTile();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void update() {
}
public void render(Graphics2D g) {
g.setColor(Color.red);
g.fillRect(myPlayer.getX(), myPlayer.getY(),
myPlayer.getWidth(), myPlayer.getHeight());
}
public void paintComponent(Graphics g) {
Graphics2D gfx = (Graphics2D) g;
g.setColor(Color.BLACK);
g.fillRect(0, 0, 765, 503);
renderMap(gfx);
render(gfx);
}
private void renderMap(Graphics2D g) {
int[][] tiledMap = this.map.getMap();
for (int i = 0; i < this.map.getHeight(); i++) {
for (int j = 0; j < this.map.getWidth(); j++) {
int currentRow = tiledMap[i][j] ;
if (currentRow == 0) {
g.drawImage(img, (j + offX) * map.getTileSize(), (i + offY) * map.getTileSize(), this);
}
if (currentRow == 1) {
g.setColor(Color.green);
g.fillRect((j + offX) * map.getTileSize(),
(i + offY) * map.getTileSize(), map.getTileSize(),
map.getTileSize());
}
}
}
}
private int offX = 0, offY = 0;
public void movePlayer(int x, int y) {
int[][] tiledMap = this.map.getMap();
myPlayer.updateX(x);
myPlayer.updateY(y);
offX = +10;
offY = +7;
}
}
package snow;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class TileMap {
private File tileMap;
private int tileWidth;
private int tileHeight;
private int tileSize = 30;
private int[][] map;
public TileMap(File tileMap) {
this.tileMap = tileMap;
}
public void buildTile() throws NumberFormatException, IOException {
try {
BufferedReader reader = new BufferedReader(new FileReader(this.tileMap));
this.tileWidth = Integer.parseInt(reader.readLine());
this.tileHeight = Integer.parseInt(reader.readLine());
map = new int[this.tileHeight][this.tileWidth];
for (int i = 0; i < this.tileHeight; i++) {
String line = reader.readLine();
String[] chars = line.split(" ");
for (int j = 0; j < this.tileWidth; j++) {
if (j >= chars.length) {
return;
}
map[i][j] = Integer.parseInt(chars[j]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public int[][] getMap() {
return this.map;
}
public int getWidth() {
return this.tileWidth;
}
public int getHeight() {
return this.tileHeight;
}
public int getTileSize() {
return this.tileSize;
}
}
I don't entirely understand your code, but I would suggest that inside this code block
for (int i = 0; i < this.map.getHeight(); i++) {
for (int j = 0; j < this.map.getWidth(); j++) {
you say something like
currentRow = map[myPlayer.getX()-this.map.getWidth()/2][myPlayer.getY()-this.map.getHeight()/2]
and then leave the rest of your drawing code as is.
Related
I am writing a space invaders clone for a school project, I am in the process of writing the aliens and their algorithm for movement with the use of an array.
My issue is a bunch of errors occur when I run the code but I can`t find why?
any help would be appreciated and bare in mind I am very inexperienced with game development and java
bellow is my GamePanel class, and then my Alien class
package Main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
import entity.Alien;
import entity.Controller;
import entity.Player;
import entity.playerBullet;
public class GamePanel extends JPanel implements Runnable{
public final int screenHeight = 600;
public final int screenWidth = 800;
public final int playerSize = 48;
int fps = 60;
KeyHandler keyH = new KeyHandler();
Thread gameThread;
public Player player = new Player(this,keyH);
public CollisionChecker cChecker = new CollisionChecker(this);
private Controller c = new Controller(null);
Alien alien;
//player default position
int playerX = 100;
int playerY = 100;
int playerSpeed = 4;
public GamePanel() {
this.setPreferredSize(new Dimension (screenWidth, screenHeight));
this.setBackground(Color.black);
this.setDoubleBuffered(true);
this.addKeyListener(keyH);
this.setFocusable(true);
}
public void startGameThread() {
gameThread = new Thread (this);
gameThread.start();
alien.initAlien();
}
public void run() {
double drawInterval = 1000000000/fps; // 0.01666 seconds = 60 times per seconds
double nextDrawTime = System.nanoTime() + drawInterval;
while(gameThread != null) {
System.out.println("this game is runing");
// update information such as character positions
// draw the screen with the updated information
update();
repaint();
try {
double remainingTime = nextDrawTime - System.nanoTime();
remainingTime = remainingTime/1000000;
if(remainingTime<0) {
remainingTime = 0;
}
Thread.sleep ((long) remainingTime);
nextDrawTime += drawInterval;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void update() {
player.update();
c.tick();
alien.moveAliens();
}
public void paintComponent(Graphics g) {
// to draw something
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
player.draw(g2);
c.render(g );
g2.dispose();
alien.render(g );
}
}
Alien class
package entity;
import java.awt.Color;
import java.awt.Graphics;
public class Alien {
boolean isVisible;
boolean moveLeft;
boolean moveRight;
Alien[] a = new Alien[10];
private int x;
private int y;
int ax = 10;
int ay = 10;
public Alien(int x, int y) {
}
public void initAlien() {
for(int i=0;i<a.length; i++) {
a[i] = new Alien(ax,ay);
ax += 40;
if(i==4) {
ax=10;
ay+=40;
}
}
}
public void moveAliens() {
for(int i=0;i<a.length; i++) {
if (a[i].moveLeft ==true) {
a[i].x -=2;
}
if (a[i].moveRight ==true) {
a[i].x+=2;
}
for(int i1 = 0; i<a.length; ) {
if(a[i].x>600) {
for(int j =0;j<a.length; j++) {
a[j].moveLeft = true;
a[j].moveRight = false;
a[j].y += 5;
}
}
if(a[i].x<0) {
for(int j = 0; j< a.length; j++) {
a[j].moveLeft = false;
a[j].moveRight = true;
a[j].y += 5;
}
}
}
}
}
I'm making a battleship game using SWING. The program reads a file with the following data: height, length, matrix of positions populated with the number of boats. The problem is the matrix that the mouse captures is inverted in comparison with the one in the file and I don't know what to do. I will appreciate any help.
Below is the code:
Frame:
import Model.ArcMap;
import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
public class GameFrame extends JFrame {
private GameCanvas canvas;
// CanvasThread updateScreenThread = new CanvasThread(canvas);
private ArcMap archive;
private int width;
private int hight;
public static final int AREA = 60;
public GameFrame(ArcMap archve) {
this.archive = archve;
this.width = archve.getArcWidth();
this.hight = archive.getArcHeight();
canvas = new GameCanvas(archive);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setTitle("Stellar Battle");
add(BorderLayout.CENTER, canvas);
setResizable(false);
// Define largura e altura da janela principal
setSize(AREA * width, canvas.AREA * hight);
setLocationRelativeTo(null);
// setVisible(true);
// Inicia Thread com timer para redesenhar a tela.
// updateScreenThread.start();
canvas.addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
int x = e.getX();
int y = e.getY();
int x_pos = x / canvas.AREA;
int y_pos = y / canvas.AREA;
System.out.println(canvas.getShot(x_pos, y_pos);
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
}
}
Canvas:
import Model.ArcMap;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.Buffer;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class GameCanvas extends Canvas {
public static final int AREA = 40;
private int margin = 0;
private int rows;
private int cols;
private ArcMap achive;
private int[][] explosionMatrix = new int[rows][cols];
public GameCanvas(ArcMap archive) {
this.achive = archive;
this.rows = archive.getArcHeight();
this.cols = archive.getArcWidth();
explosionMatrix = archive.getArcMatrix();
setSize(AREA * rows, AREA * cols);
}
//#Override
public void paint(Graphics g) {
int lenthI = rows;
int lenthJ = cols;
g.setColor(new Color(131, 209, 232));
g.fillRect(0, 0, cols * AREA, rows * AREA);
g.setColor(Color.white);
for (int i = 0; i < cols ; i++) {
g.drawLine(i * AREA, 0, i * AREA, AREA * rows);
for (int j = 0; j < rows; j++) {
g.drawLine(0, j * AREA, AREA * cols, j * AREA);
}
}
this.oque();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(explosionMatrix[i][j]);
}
System.out.println("");
}
// Prepare an ImageIcon
ImageIcon icon = new ImageIcon("images/ondas_1.jpg");
ImageIcon iconShot = new ImageIcon("images/explosion.png");
// Prepare an Image object to be used by drawImage()
final Image img = icon.getImage();
final Image imgShot = iconShot.getImage();
this.oque();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
g.drawImage(img, i * AREA, j * AREA, AREA, AREA, null);
if (explosionMatrix[i][j] == 1) {
g.drawImage(imgShot, i * AREA, j * AREA, AREA, AREA, null);
}
}
}
this.oque();
}
public void setShot(int x, int y) {
explosionMatrix[x][y] = 1;
}
public int getShot(int x, int y) {
return explosionMatrix[x][y];
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getCols() {
return cols;
}
public void setCols(int cols) {
this.cols = cols;
}
public int[][] getExplosionMatrix() {
return explosionMatrix;
}
public void setExplosionMatrix(int[][] explosionMatrix) {
this.explosionMatrix = explosionMatrix;
}
public void oque() {
System.out.println("");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(explosionMatrix[i][j]);
}
System.out.println("");
}
}
}
Hi, I'm developing a snake game. To create the snake I'm using ArrayList. While moving the snake I'm getting the following error: "java.lang.IndexOutOfBoundsException: Index: 3, Size: 3". Below is my program. In Snake.update() method I have problem.
Game.java:
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Game extends JFrame {
public Game(){
add(new GamePanel());
setTitle("Game Test3");
setVisible(true);
setAlwaysOnTop(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String[] args) {
new Game();
}
}
GamePanel.java:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class GamePanel extends JPanel implements Runnable, KeyListener {
public static int width = 300;
public static int height = 400;
private Thread thread;
private Image image;
private Graphics2D g;
private Food food;
private Snake snake;
public GamePanel() {
setPreferredSize(new Dimension(width, height));
setFocusable(true);
}
public void addNotify() {
super.addNotify();
if (thread == null) {
thread = new Thread(this);
thread.start();
}
addKeyListener(this);
}
public void run() {
image = createImage(width, height);
g = (Graphics2D) image.getGraphics();
RenderingHints reneringHints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHints(reneringHints);
food = new Food();
snake = new Snake();
while (true) {
gameRender();
gameUpdate();
gameDraw();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void gameDraw() {
Graphics2D g2 = (Graphics2D) getGraphics();
g2.drawImage(image, 0, 0, this);
g2.dispose();
}
private void gameRender() {
g.setColor(Color.black);
g.fillRect(0, 0, width, height);
// food drawing
food.draw(g);
// snake drawing
snake.draw(g);
}
private void gameUpdate() {
food.update();
snake.update();
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
snake.setLeft(true);
}
if (key == KeyEvent.VK_RIGHT) {
snake.setRight(true);
}
if (key == KeyEvent.VK_UP) {
snake.setUp(true);
}
if (key == KeyEvent.VK_DOWN) {
snake.setDown(true);
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
snake.setLeft(false);
}
if (key == KeyEvent.VK_RIGHT) {
snake.setRight(false);
}
if (key == KeyEvent.VK_UP) {
snake.setUp(false);
}
if (key == KeyEvent.VK_DOWN) {
snake.setDown(false);
}
}
public void keyTyped(KeyEvent e) {
}
}
//snake body
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.ArrayList;
public class Snake {
private int x;
private int y;
private int r;
int body;
Rectangle rectangle;
ArrayList<Rectangle> rc = new ArrayList<Rectangle>();
private boolean left;
private boolean right;
private boolean up;
private boolean down;
public Snake() {
x = 150;
y = 150;
r = 4;
body = 3;
for (int i = 0; i < body; i++) {
rc.add(new Rectangle(x - i * r * 3, y, r * 3, r * 3));
}
}
public void draw(Graphics2D g) {
for (int i = 0; i < body; i++) {
if (i == 0) {
g.setColor(Color.red);
} else {
g.setColor(Color.green);
}
g.fillOval(rc.get(i).x, rc.get(i).y, rc.get(i).width,
rc.get(i).height);
}
}
public void update() {
for (int i = body; i > 0; i--) {
rc.set(i, rc.get(i - 1));
}
if (left) {
rc.get(0).x -= 1;
System.out.println("vbnv");
}
if (right) {
rc.get(0).x += 1;
}
if (up) {
rc.get(0).y -= 1;
}
if (down) {
rc.get(0).y += 1;
}
}
public void setLeft(boolean b) {
left = b;
}
public void setRight(boolean b) {
right = b;
}
public void setUp(boolean b) {
up = b;
}
public void setDown(boolean b) {
down = b;
}
}
Without reading the code I can tell that somewhere you are trying to get non-existent element. Read the message of exception, it tells you that your ArrayList consist of three elements (which means that the last element has index of 2) while you try to get the element with index of 3.
Update: yes, the problem is here:
for (int i = body; i > 0; i--) {
rc.set(i, rc.get(i - 1));
}
body equals to 3, and rc after the constructor invocation has the size of 3. set method replaces already existing element with the specified index (see the documentation), but element with index of 3 doesn't exist. That's the cause of an exception.
Your problem is in this loop:
for (int i = body; i > 0; i--) {
rc.set(i, rc.get(i - 1));
}
During the first iteration around this loop, you will be calling:
rc.set(3, <someValue>);
3 is not a valid index in a list of length 3. The largest valid index is 2.
for (int i = body; i > 0; i--)
In this for, i is assigned with the value of body(which is 3) and it looks like your ArrayList rc has only 3 elements in it. Therefore, when you try to access the index 3 using rc.set(3, something), its giving the IndexOutOfBoundsException.
Always remember, whether it is Arrays or ArrayList, the max possible index accessible in them is always array.length - 1 and ArrayList.size() - 1.
I am new to java 2d graphics and I have problem handling mouseclick event.
Is it possible for you to tell me why there is nothing going on after updating mouse status to clicked ?
What I want to do is to change the image in array at 0 2 to another image. Nothing happens tho. Thanks for your help in advance.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.*;
import java.awt.*;
import javax.swing.ImageIcon;
import javax.swing.*;
public class Board extends JPanel implements MouseListener {
private static boolean[] keyboardState = new boolean[525];
private static boolean[] mouseState = new boolean[3];
private static Image[][] images;
Image house;
int w = 0;
int h = 0;
int xPos;
int yPos;
ImageIcon ii = new ImageIcon(this.getClass().getResource("house.gif"));
ImageIcon iii = new ImageIcon(this.getClass().getResource("house1.gif"));
public Board() {
house = ii.getImage();
h = house.getHeight(null);
w = house.getWidth(null);
images = new Image[10][10];
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
images[i][j] = house;
}
}
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
g2d.drawImage(images[i][j],w*i,h*j,null);
}
}
//g2d.drawImage(house,15,15,null);
}
public void checkMouse()
{
if(mouseState[0])
{
images[0][2] = iii.getImage();
repaint();
super.repaint();
}
}
#Override
public void mousePressed(MouseEvent e)
{
mouseKeyStatus(e, true);
checkMouse();
}
#Override
public void mouseReleased(MouseEvent e)
{
mouseKeyStatus(e, false);
repaint();
}
public static boolean mouseButtonState(int button)
{
return mouseState[button - 1];
}
private void mouseKeyStatus(MouseEvent e, boolean status)
{
if(e.getButton() == MouseEvent.BUTTON1)
mouseState[0] = status;
else if(e.getButton() == MouseEvent.BUTTON2)
mouseState[1] = status;
else if(e.getButton() == MouseEvent.BUTTON3)
mouseState[2] = status;
}
You need to register a MouseListener for your Board JPanel so that mouseKeyStatus can be called
addMouseListener(this);
Aside: Override paintComponent rather than paint when implementing custom painting in Swing and remember to invoke super.paintComponent(g).
I want to print each digit of pi number as a colored pixel, so, I get an input, with the pi number, then parse it into a list, each node containing a digit (I know, I'll use an array later), but I never get this painted to screen... Can someone help me to see where I'm wrong?
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.MemoryImageSource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PiPainter extends JPanel
{
private static final long serialVersionUID = 6416932054834995251L;
private static int pixels[];
private static List<Integer> pi = new ArrayList<Integer>();
private final static int[] color = {
0xFF000000, 0xFF787878, 0xFF008B00, 0xFF00008B, 0xFF008B8B,
0xFF008B00, 0xFFCDCD00, 0xFFFF4500, 0xFF8B0000, 0xFFFF0000
};
public static void readFile(String name)
{
File file = new File(name);
BufferedReader reader = null;
char[] digits;
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
while((text = reader.readLine()) != null)
{
digits = text.toCharArray();
for(char el : digits)
if(el != ' ')
pi.add(Character.getNumericValue(el));
}
} catch (Exception e)
{
e.printStackTrace();
}
}
public void paint(Graphics gg)
{
// page containing pi number, http://gc3.net84.net/pi.htm
// other source, http://newton.ex.ac.uk/research/qsystems/collabs/pi/pi6.txt
readFile("c:\\pi.txt");
int h = 300;
int w = 300;
int digit;
int i = 0;
pixels = new int[w * h];
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
pixels[i] = color[pi.get(i)];
i++;
}
}
Image art = createImage(new MemoryImageSource(w, h, pixels, 0, w));
gg.drawImage(art, 0, 0, this);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.getContentPane().add(new PiPainter(), BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}
I'm not familiar with MemoryImageSource. Here's the first 16 300 digits of π, repeated in a BufferedImage and using your color table.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class PiRaster extends JPanel {
private static final int W = 30;
private static final int H = 30;
private static List<Integer> pi = new ArrayList<Integer>();
BufferedImage image;
private int[] clut = {
0x000000, 0x787878, 0x008B00, 0x00008B, 0x008B8B,
0x008B00, 0xCDCD00, 0xFF4500, 0x8B0000, 0xFF0000
};
public PiRaster() {
this.setPreferredSize(new Dimension(W * 16, H * 10));
String s = ""
+ "31415926535897932384626433832795028841971693993751"
+ "05820974944592307816406286208998628034825342117067"
+ "98214808651328230664709384460955058223172535940812"
+ "84811174502841027019385211055596446229489549303819"
+ "64428810975665933446128475648233786783165271201909"
+ "14564856692346034861045432664821339360726024914127";
for (int i = 0; i < s.length(); i++) {
pi.add(s.charAt(i) - '0');
}
}
#Override
public void paintComponent(Graphics g) {
if (image == null) {
image = (BufferedImage) createImage(W, H);
int i = 0;
for (int row = 0; row < H; row++) {
for (int col = 0; col < W; col++) {
image.setRGB(col, row, clut[pi.get(i)]);
if (++i == pi.size()) {
i = 0;
}
}
}
}
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new PiRaster());
frame.pack();
frame.setVisible(true);
}
});
}
}
#trashgod
Thanks for your answer, I changed it a little bit to achieve what I was looking for ; )
Now you can change the width easily to achieve a better view of the image and fit the contents, and the number don't repeats, making it easy to perceive patterns (if there might be). Oh, and I added about 2~3 lines at the end, to clarify it.
package edu.pi;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class PiRaster extends JPanel
{
private static final long serialVersionUID = -1298205187260747210L;
private static int W;
private static int H;
private static List<Integer> pi = new ArrayList<Integer>();
BufferedImage image;
private int[] clut = {
0x000000, 0x787878, 0x008B00, 0x00008B, 0x008B8B,
0x008B00, 0xCDCD00, 0xFF4500, 0x8B0000, 0xFF0000
};
public PiRaster()
{
String s = "3."
+ "14159265358979323846264338327950288419716939937510"
+ "58209749445923078164062862089986280348253421170679"
+ "82148086513282306647093844609550582231725359408128"
+ "48111745028410270193852110555964462294895493038196"
+ "44288109756659334461284756482337867831652712019091"
+ "45648566923460348610454326648213393607260249141273"
+ "72458700660631558817488152092096282925409171536436"
+ "78925903600113305305488204665213841469519415116094"
+ "33057270365759591953092186117381932611793105118548"
+ "07446237996274956735188575272489122793818301194912"
+ "98336733624406566430860213949463952247371907021798"
+ "60943702770539217176293176752384674818467669405132"
+ "00056812714526356082778577134275778960917363717872"
+ "14684409012249534301465495853710507922796892589235"
+ "42019956112129021960864034418159813629774771309960"
+ "51870721134999999837297804995105973173281609631859"
+ "50244594553469083026425223082533446850352619311881"
+ "71010003137838752886587533208381420617177669147303"
+ "59825349042875546873115956286388235378759375195778"
+ "18577805321712268066130019278766111959092164201989";
char temp;
for (int i = 0; i < s.length(); i++)
{
temp = s.charAt(i);
if (temp >= 48 && temp <= 57)
pi.add(s.charAt(i) - '0');
}
W = 50;
H = s.length() / W + 3;
this.setPreferredSize(new Dimension(W * 10, H * 10));
}
#Override
public void paintComponent(Graphics g)
{
if (image == null)
{
image = (BufferedImage) createImage(W, H);
int i = 0;
boolean end = false;
for (int row = 0; row < H && !end; row++)
{
for (int col = 0; col < W && !end; col++)
{
image.setRGB(col, row, clut[pi.get(i)]);
if (++i == pi.size())
{
i = 0;
end = true;
}
}
}
}
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
JFrame frame = new JFrame("Pi raster");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new PiRaster());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}