2015-10-24 3 views
1

У меня есть ошибка каждый раз, когда я пытаюсь запустить его, в нем появляется пустое окно и эти сообщения об ошибках.Java Game - неизвестная ошибка

Exception in thread "Thread-2" java.lang.IllegalArgumentException: Color parameter outside of expected range: Red Green 
    at java.awt.Color.testColorValueRange(Unknown Source) 
    at java.awt.Color.<init>(Unknown Source) 
    at java.awt.Color.<init>(Unknown Source) 
    at java.awt.Color.<init>(Unknown Source) 
    at com.tutorial.main.HUD.render(HUD.java:32) 
    at com.tutorial.main.Game.render(Game.java:118) 
    at com.tutorial.main.Game.run(Game.java:85) 
    at java.lang.Thread.run(Unknown Source) 

У меня есть подозрение, что это как-то связано с рендерингом, но не уверен, что кто-то может помочь.

Я вставил следующие коды:

  • игры
  • Окно
  • SmartEnemy
  • ИЛС
  • ID
  • Handler
package com.tutorial.main; 

import java.awt.Canvas; 
import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.image.BufferStrategy; 
import java.util.Random; 

public class Game extends Canvas implements Runnable { 

    private static final long serialVersionUID = 7580815534084638412L; 

    public static final int WIDTH = 640, HEIGHT = WIDTH/12 * 9; 

    private Thread thread; 
    private boolean running = true; 


    private Random r; 
    private Handler handler; 
    private HUD hud; 
    private Spawn spawner; 


    public Game() { 
    new Window(WIDTH, HEIGHT, "Lets Build a Game!", this); 

    handler = new Handler(); 
    hud = new HUD(); 
    spawner = new Spawn(handler, hud); 



    this.addKeyListener(new KeyInput(handler)); 


    r = new Random(); 

    // for(int i = 0; i <1; i++){ 

    //implementing Player1 
    handler.addObject(new Player(WIDTH/2 - 32, HEIGHT/2 - 32, ID.Player, handler)); 
    handler.addObject(new BasicEnemy(r.nextInt(Game.WIDTH), r.nextInt(Game.HEIGHT), ID.BasicEnemy, handler)); 

    //implementing Player2 
    //handler.addObject(new Player(WIDTH/2-32, HEIGHT/2+64, ID.Player2)); 
    /*for (int i = 0; i < 1; i++){ 
      //implementing BasicEnemy 
       handler.addObject(new BasicEnemy(r.nextInt(WIDTH), r.nextInt(HEIGHT), ID.BasicEnemy, handler)); 
      }*/ 

    } 

    public synchronized void start() { 
    thread = new Thread(this); 
    thread.start(); 
    } 

    public synchronized void stop() { 
    try { 
     thread.join(); 
     running = false; 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    } 

    public void run() { 
    this.requestFocus(); 
    long lastTime = System.nanoTime(); 
    double amountOfTicks = 60.0; 
    double ns = 1000000000/amountOfTicks; 
    double delta = 0; 
    long timer = System.currentTimeMillis(); 
    int frames = 0; 
    while (running) { 
     long now = System.nanoTime(); 
     delta += (now - lastTime)/ns; 
     lastTime = now; 
     while (delta >= 1) { 
     tick(); 
     delta--; 
     } 
     if (running) { 
     render(); 
     frames++; 

     if (System.currentTimeMillis() - timer > 1000) { 
      timer += 1000; 
      //System.out.println("FPS: " + frames); 
      frames = 0; 
     } 
     } 

    } 
    } 

    private void tick() { 
    handler.tick(); 
    hud.tick(); 
    spawner.tick(); 
    } 

    private void render() { 
    BufferStrategy bs = this.getBufferStrategy(); 
    if (bs == null) { 
     this.createBufferStrategy(3); 
     return; 
    } 

    Graphics g = bs.getDrawGraphics(); 

    g.setColor(Color.BLACK); 
    g.fillRect(0, 0, WIDTH, HEIGHT); 


    handler.render(g); 
    hud.render(g); 


    g.dispose(); 
    bs.show(); 
    } 


    public static float clamp(float 
    var, float min, float max) { 
    if (var >= max) { 
     return var = max; 

    } else if (var <= min) { 
     return var = min; 
    } else { 
     return var; 
    } 
    } 

    public static void main(String args[]) { 
    Game game = new Game(); 
    game.start(); 
    } 
} 
package com.tutorial.main; 

import java.awt.Canvas; 
import javax.swing.*; 
import java.awt.Dimension; 

public class Window extends Canvas { 

    private static final long serialVersionUID = -240840600533728354L; 

    public Window(int width, int height, String title, Game game) { 
    JFrame frame = new JFrame(title); 

    frame.setPreferredSize(new Dimension(width, height)); 
    frame.setMinimumSize(new Dimension(width, height)); 
    frame.setMaximumSize(new Dimension(width, height)); 

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setResizable(false); 
    frame.setLocationRelativeTo(null); 
    frame.add(game); 
    frame.setVisible(true); 

    } 

} 
package com.tutorial.main; 

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Rectangle; 

public class SmartEnemy extends GameObject{ 

    private Handler handler; 
    private GameObject player; 

    public SmartEnemy(int x, int y, ID id, Handler handler) { 
     super(x, y, id); 
     this.handler = handler; 

     for(int i = 0; i < handler.object.size(); i++){ 
      if(handler.object.get(i).getId() == ID.Player) player = handler.object.get(i); 
     } 


    } 


    public Rectangle getBounds(){ 
     return new Rectangle((int)x, (int)y, 32, 32); 
    } 

    public void tick() { 
     handler.addObject(new Trail(x, y,ID.Trail, Color.GREEN, 16, 16, 0.02f, handler)); 

     x += velX; 
     y += velY; 

     float diffX = x - player.getX() - 8; 
     float diffY = y - player.getY() - 8; 
     float distance = (float) Math.sqrt((x - player.getX()) * (x - player.getX()) + (y - player.getY()) * (y - player.getY())); 

     velX = (float) ((-1.0/distance) * diffX); 
     velY = (float) ((-1.0/distance) * diffY); 

     if (y <= 0 || y >= Game.HEIGHT - 37) velY *= -1; 
     if (x <= 0 || x >= Game.WIDTH - 16) velX*= -1; 


    } 

    public void render(Graphics g) { 
      g.setColor(Color.GREEN); 
      g.fillRect((int)x, (int)y, 16, 16); 

    } 

} 
package com.tutorial.main; 

import java.awt.Graphics; 
import java.util.LinkedList; 

public class Handler { 


    LinkedList <GameObject> object = new LinkedList <GameObject>(); 

    public void tick() { 
    for (int i = 0; i < object.size(); i++) { 
     GameObject tempObject = object.get(i); 
     tempObject.tick(); 
    } 
    }; 
    public void render(Graphics g) { 
    for (int i = 0; i < object.size(); i++) { 
     GameObject tempObject = object.get(i); 

     tempObject.render(g); 
    } 

    } 

    public void addObject(GameObject object) { 
    this.object.add(object); 
    } 

    public void removeObject(GameObject object) { 
    this.object.remove(object); 
    } 
} 
package com.tutorial.main; 

import java.awt.Color; 
import java.awt.Graphics; 

public class HUD { 

    public static float HEALTH = 100; 

    private float greenValue = 255; 


    private int level = 1; 
    private float score = 0; 

    public void tick(){ 
     HEALTH = Game.clamp(HEALTH, 0, 100); 



     greenValue = Game.clamp(greenValue, 0, 255); 
     greenValue = HEALTH*2; 


     score++; 
    } 
    public void render(Graphics g){ 
     //Background for Health bar 
     g.setColor(Color.gray); 
     g.fillRect(15, 15, 200, 32); 
     //Health Bar 
     g.setColor(new Color(75, (float) greenValue, 0)); 
     g.fillRect(15, 15, (int) (HEALTH * 2), 32); 
     g.setColor(Color.WHITE); 
     g.drawRect(15, 15, 200, 32); 

     g.drawString("Score: " + score, 15, 60); 
     g.drawString("Level: " + level, 15, 75); 
    } 
    /*int level = 1, point = 0; 
    //point scoring system 
    for(int i = 2; i > 1; i++){ 
     if(HEALTH > 0){ 
      point++; 
      System.out.println(point); 
      } 
     } 
    }*/ 



    private void score(float score){ 
     this.score = score; 
    } 


    public float getScore(){ 
     return score; 
    } 


    public int getLevel(){ 
     return level; 
    } 


    public void setLevel(int level){ 
     this.level = level; 
    } 
} 
package com.tutorial.main; 

import java.awt.Graphics; 
import java.awt.Rectangle; 

public abstract class GameObject { 

    protected float x, y; 
    protected ID id; 
    protected float velX, velY; 


    public GameObject(float x, float y, ID id){ 

     this.x = x; 
     this.y = y; 
     this.id = id; 

    } 



    public abstract void tick(); 


    public abstract void render(Graphics g); 


    public abstract Rectangle getBounds(); 
    public void setX(int x){ 
     this.x = x; 
    } 

    public void setY(int y){ 
     this.y = y; 
    } 

    public int getX(){ 
     return (int) x; 
    } 

    public int getY(){ 
     return (int) y; 
    } 

    public void setId(ID id){ 
     this.id = id; 
    } 

    public ID getId(){ 
     return id; 
    } 

    public void setVelX(int velX){ 
     this.velX = velX; 
    } 

    public void setVelY(int velY){ 
     this.velY = velY; 
    } 

    public float getVelX(){ 
     return velX; 
    } 

    public float getVelY(){ 
     return velY; 
    } 

} 
+0

Что такое линия 32 в HUD? – Mureinik

+0

Исключение: 'Параметр цвета за пределами ожидаемого диапазона: Красный Зеленый ... в com.tutorial.main.HUD.render (HUD.java:32)' поэтому проблема может быть в этой строке 'g.setColor (новый цвет (75, (float) greenValue, 0)); ' – sinclair

ответ

1

excetion вызывается этот конструктор вызова:

new Color(75, (float) greenValue, 0) 

Вы используете Color(float, float, float), так как второй параметр имеет тип float. Как описано в javadocs, этот конструктор принимает 3 float s, которые представляют компоненты rgb. Диапазоны от 0.0f до 1.0f, а не от 0 до 255, поэтому вы получаете ошибку (75 - слишком большой).

Похоже, что вы не должны указывать второй параметр, чтобы использовать этот оператор с помощью конструктора Color(int, int, int).

Смежные вопросы