package jsalis.game;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import jsalis.framework.Animator;
import jsalis.framework.Sprite;
import loader.ResourceLoader;
public class Gun extends Sprite {
public static final int MAX_COOL_DOWN = 65;
public static final int MIN_COOL_DOWN = 15;
public static final int MAX_BULLET_LIFE = 50;
public static final int MIN_BULLET_LIFE = 10;
private LinkedList<Bullet> bulletList = new LinkedList<Bullet>();
private GunType type;
private Point firePoint = new Point();
private boolean facingLeft;
private int coolDownTime;
private ArrayList<BufferedImage> spriteL, spriteR;
private Animator animator;
public Gun(GunType type) {
this.type = type;
switch (type) {
case PISTOL:
loadSprite("character_shoot.gif");
firePoint.y = 30;
break;
case SMG:
loadSprite("character_shoot.gif");
break;
}
this.width = spriteL.get(0).getWidth();
this.height = spriteL.get(0).getHeight();
this.setFacingLeft(false);
}
private void loadSprite(String path) {
try {
spriteR = ResourceLoader.getImageArray(path, 6, 64, 42);
} catch (IOException e) {
e.printStackTrace();
}
spriteL = ResourceLoader.flipImageArrayHorizontal(spriteR);
animator = new Animator(spriteL, 2);
animator.setRepeating(false);
}
public GunType getType() {
return type;
}
public void setFacingLeft(boolean b) {
if (facingLeft != b) {
facingLeft = b;
if (facingLeft) {
firePoint.x = 0;
} else {
firePoint.x = this.width - Character.X_OFFSET;
}
}
}
public boolean fire() {
if (coolDownTime > 0) {
return false;
}
animator.setEnabled(true);
/* PISTOL */
float velX = 10, velY = 0;
int lifeScale = (MAX_BULLET_LIFE - MIN_BULLET_LIFE) / GunType.MAX_STAT;
int bulletLife = MIN_BULLET_LIFE + (type.getRange() * lifeScale);
if (facingLeft) {
velX = -velX;
}
bulletList.add(new Bullet(this.x + firePoint.x, this.y + firePoint.y, velX, velY, bulletLife));
int coolScale = (MAX_COOL_DOWN - MIN_COOL_DOWN) / GunType.MAX_STAT;
coolDownTime = MAX_COOL_DOWN - (type.getFireRate() * coolScale);
return true;
}
public void tick() {
animator.tick();
for (int i = 0; i < bulletList.size(); i++) {
Bullet bullet = bulletList.get(i);
bullet.tick();
if (bullet.isDead()) {
bulletList.remove(bullet);
}
}
if (coolDownTime > 0) {
coolDownTime --;
}
}
public void render(Graphics2D g) {
for (Bullet bullet : bulletList) {
bullet.render(g);
}
int i = animator.getCurrentFrame();
if (facingLeft) {
g.drawImage(spriteL.get(i), (int)x - Character.X_OFFSET, (int)y , null);
} else {
g.drawImage(spriteR.get(i), (int)x, (int)y, null);
}
}
}