Torna indietro   Hardware Upgrade Forum > Software > Programmazione

Insta360 Link 2 Pro e 2C Pro: le webcam 4K che ti seguono, anche con gimbal integrata
Insta360 Link 2 Pro e 2C Pro: le webcam 4K che ti seguono, anche con gimbal integrata
Le webcam Insta360 Link 2 Pro e Link 2C Pro sono una proposta di fascia alta per chi cerca qualità 4K e tracciamento automatico del soggetto senza ricorrere a configurazioni complesse. Entrambi i modelli condividono sensore, ottiche e funzionalità audio avanzate, differenziandosi per il sistema di tracciamento: gimbal a due assi sul modello Link 2 Pro, soluzione digitale sul 2C Pro
Motorola edge 70: lo smartphone ultrasottile che non rinuncia a batteria e concretezza
Motorola edge 70: lo smartphone ultrasottile che non rinuncia a batteria e concretezza
Motorola edge 70 porta il concetto di smartphone ultrasottile su un terreno più concreto e accessibile: abbina uno spessore sotto i 6 mm a una batteria di capacità relativamente elevata, un display pOLED da 6,7 pollici e un comparto fotografico triplo da 50 MP. Non punta ai record di potenza, ma si configura come alternativa più pragmatica rispetto ai modelli sottili più costosi di Samsung e Apple
Display, mini PC, periferiche e networking: le novità ASUS al CES 2026
Display, mini PC, periferiche e networking: le novità ASUS al CES 2026
Sono molte le novità che ASUS ha scelto di presentare al CES 2026 di Las Vegas, partendo da una gamma di soluzioni NUC con varie opzioni di processore passando sino agli schermi gaming con tecnologia OLED. Il tutto senza dimenticare le periferiche di input della gamma ROG e le soluzioni legate alla connettività domestica
Tutti gli articoli Tutte le news

Vai al Forum
Rispondi
 
Strumenti
Old 08-06-2011, 02:43   #1
Narat
Junior Member
 
Iscritto dal: Oct 2007
Messaggi: 28
[JAVA] Problema bufferstrategy ed eventi tastiera

Salve a tutti sto creando un gioco in java con l'utilizzo del bufferimage ma ho un problema cioè: quando creo un pannello oppure utilizzo il frame per creare il menu del gioco come clicco su new game gli eventi della tastiera non funzionano più.

Sapete dirmi il perchè?
grazie in anticipo, vi allego il codice ^_^
Codice:
package GUI;

import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import Thread.ZombieAction;
import Thread.BulletMovements;
import Thread.CreateZombie;
import Thread.CreateEnergyBall;
import Thread.ZombieMovements;
import World.ObjectClass;
import World.UploadImages;
import Players.BulletPlayer;
import Players.Direction;
import Players.Zombie;
import Players.EnergyBall;
import Players.Player;
import World.World;
import XML.LoadMap;
import MouseKeyboardEvents.*;

public class Game extends JFrame implements Runnable,KeyListener{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final int UP = 0;
	private static final int DOWN = 1;
	private static final int LEFT = 2;
	private static final int RIGHT = 3;
	private static final int SHOT = 4;
	private boolean [] premuti = new boolean[5];
	private static MotionDispatcher motion=null;
	private BufferStrategy strategy;
	private static World world;
	private static Player player;
	private static Window window;
	/**
	 * Constructor
	 */
	public Game()
	{
		initWindow();
		initComponnents();
	}

	/**
	 * initiate the window
	 */
	private void initWindow()
	{
//		setSize(window.getDimensionPixelX(), window.getDimensionPixelY());
		setTitle("Gioco");
		setSize(800,672);
		setUndecorated(true);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setResizable(false);
		setVisible(true);
		setIgnoreRepaint(true);
//		setFocusable(true);
	}

	/**
	 * initiate the componnents
	 */
	private void initComponnents()
	{
		setFocusTraversalKeysEnabled(false);
		addKeyListener(this);
	}
	private void initBufferStrategy(){
		createBufferStrategy(2); 
		strategy = getBufferStrategy(); 
		requestFocus();
	}
	
	/**
	 * Draw the frame
	 * @param panel 
	 * @param graphics graphic
	 */
	public void newGame(MainPanel panel){
		initBufferStrategy();
		createMap();
//		initComponnents();
		Game.this.requestFocus();
		run();
	}
	private void draw(Graphics2D g)
	{
		Player p = null;
		int windowX=window.getPrinterPartX();
		int windowY=window.getPrinterPartY();

		int posX=window.indexWindowX(player,world);
		int posY=window.indexWindowY(player,world);

		for(int i=0; i < world.getLIVELLO()-1; i++)
		{
			for(int j=0; j < windowX; j++)
			{
				for(int k=0; k < windowY; k++)
				{
					if(i == 0){
						if(world.getWorld()[i][posX][posY] instanceof ObjectClass)
						{
							ObjectClass ob = (ObjectClass) world.getWorld()[i][posX][posY];
							g.drawImage(UploadImages.getSummerTiles()[ob.getID()],ob.getPositionWidth()-window.getPositionWidth(), ob.getPositionHeight()-window.getPositionHeight(), null);
						}
					}
					else if(i==1) 
					{
						if(world.getWorld()[i][posX][posY] instanceof Player)
						{
							p= (Player) world.getWorld()[i][posX][posY];
							drawPlayer(g, p);
						}
						else if(world.getWorld()[i][posX][posY] instanceof ObjectClass)
						{
							ObjectClass ob=(ObjectClass) world.getWorld()[1][posX][posY];
							if(ob.getID() != 0)
								g.drawImage(UploadImages.getSummerTiles()[ob.getID()],ob.getPositionWidth()-window.getPositionWidth(), ob.getPositionHeight()-window.getPositionHeight(), null);
						}else if(world.getWorld()[i][posX][posY] instanceof Zombie)
						{
							Zombie e= (Zombie) world.getWorld()[1][posX][posY];
							drawZombie(g,e);
						}else if(world.getWorld()[i][posX][posY] instanceof BulletPlayer)
						{
							BulletPlayer b=(BulletPlayer) world.getWorld()[1][posX][posY];
							drawBullet(g,b);
						}
						else if(world.getWorld()[i][posX][posY] instanceof EnergyBall){
							EnergyBall eb = (EnergyBall) world.getWorld()[i][posX][posY];
							g.drawImage(UploadImages.getEnergyBall(),eb.getPositionWidth()-window.getPositionWidth(), eb.getPositionHeight()-window.getPositionHeight(), null);
						}
					}
					posY++;
				}
				posY=window.indexWindowY(player,world);

				posX++;
			}
			posX=window.indexWindowX(player,world);
		}
		lifeBar(g, p);
		g.dispose();
		
		strategy.show();
		//		PrintWorld();
	}
	private void lifeBar(Graphics2D g, Player p){
		if(p.getHP() >= 100){
			g.drawImage(UploadImages.getLifeBar().get(10),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 100 && p.getHP() >= 90){
			g.drawImage(UploadImages.getLifeBar().get(9),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 90 && p.getHP() >= 80){
			g.drawImage(UploadImages.getLifeBar().get(8),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 80 && p.getHP() >= 70){
			g.drawImage(UploadImages.getLifeBar().get(7),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 70 && p.getHP() >= 60){
			g.drawImage(UploadImages.getLifeBar().get(6),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 60 && p.getHP() >= 50){
			g.drawImage(UploadImages.getLifeBar().get(5),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 50 && p.getHP() >= 40){
			g.drawImage(UploadImages.getLifeBar().get(4),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 40 && p.getHP() >= 30){
			g.drawImage(UploadImages.getLifeBar().get(3),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 30 && p.getHP() >= 20){
			g.drawImage(UploadImages.getLifeBar().get(2),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 20 && p.getHP() >= 1){
			g.drawImage(UploadImages.getLifeBar().get(1),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() <= 0){
			g.drawImage(UploadImages.getLifeBar().get(0),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}
	}
	private void drawBullet(Graphics2D g, BulletPlayer b){
		if(b.getDirection() == Direction.UP){
			g.drawImage(UploadImages.getAmmo().get(Direction.UP), b.getPositionWidth()-window.getPositionWidth(),b.getPositionHeight()-window.getPositionHeight(),null);
		}else if(b.getDirection() == Direction.DOWN){
			g.drawImage(UploadImages.getAmmo().get(Direction.DOWN), b.getPositionWidth()-window.getPositionWidth(),b.getPositionHeight()-window.getPositionHeight(),null);
		}else if(b.getDirection() == Direction.LEFT){
			g.drawImage(UploadImages.getAmmo().get(Direction.LEFT), b.getPositionWidth()-window.getPositionWidth(),b.getPositionHeight()-window.getPositionHeight(),null);
		}else if(b.getDirection() == Direction.RIGHT){
			g.drawImage(UploadImages.getAmmo().get(Direction.RIGHT), b.getPositionWidth()-window.getPositionWidth(),b.getPositionHeight()-window.getPositionHeight(),null);
		}
	}

	private void drawZombie(Graphics2D g, Zombie e) {
		// TODO Auto-generated method stub
		//		if(e.getDirection() == Direction.STOPUP)
		//			g.drawImage(UploadImages.getEnemySTOP().get(Direction.STOPUP), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
		//		else if(e.getDirection() == Direction.STOPDOWN)
		//			g.drawImage(UploadImages.getEnemySTOP().get(Direction.STOPDOWN), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
		//		else if(e.getDirection() == Direction.STOPLEFT)
		//			g.drawImage(UploadImages.getEnemySTOP().get(Direction.STOPLEFT), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
		//		else if(e.getDirection() == Direction.STOPRIGHT)
		//			g.drawImage(UploadImages.getEnemySTOP().get(Direction.STOPRIGHT), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);

		if(!e.isAttacking() && !e.isDead()){
			if(e.getDirection() == Direction.UP){
				g.drawImage(UploadImages.getZombieUP().get(e.getSteps()), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
			}
			else if(e.getDirection() == Direction.DOWN){
				g.drawImage(UploadImages.getZombieDown().get(e.getSteps()), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
			}
			else if(e.getDirection() == Direction.LEFT){
				g.drawImage(UploadImages.getZombieLeft().get(e.getSteps()), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
			}
			else if(e.getDirection() == Direction.RIGHT){
				g.drawImage(UploadImages.getZombieRight().get(e.getSteps()), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
			}
		}
		else
		{
			g.drawImage(world.getZombieSprite().get(e.getId()).getCurrentImage(), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
		}
	}

	private void drawPlayer(Graphics2D g, Player p) 
	{
		if(p.getDirection() == Direction.STOPUP && p.getHP() > 0 && p.isShot())
			g.drawImage(UploadImages.getMercenaryShot().get(Direction.UP),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPDOWN && p.getHP() > 0 && p.isShot())
			g.drawImage(UploadImages.getMercenaryShot().get(Direction.DOWN),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPLEFT && p.getHP() > 0 && p.isShot())
			g.drawImage(UploadImages.getMercenaryShot().get(Direction.LEFT),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPRIGHT && p.getHP() > 0 && p.isShot())
			g.drawImage(UploadImages.getMercenaryShot().get(Direction.RIGHT),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPUP && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenarySTOP().get(Direction.STOPUP), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPDOWN && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenarySTOP().get(Direction.STOPDOWN), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPLEFT && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenarySTOP().get(Direction.STOPLEFT), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPRIGHT && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenarySTOP().get(Direction.STOPRIGHT), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.UP && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenaryN().get(p.getSteps()),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.DOWN && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenaryS().get(p.getSteps()), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.RIGHT && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenaryE().get(p.getSteps()), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.LEFT && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenaryW().get(p.getSteps()), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getHP() <= 0)
			g.drawImage(SpriteDeadPlayer.getCurrentImagePlayer(), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
	}

	/**
	 * Run the program
	 */
	@Override
	public void run()
	{
		Graphics2D graphics2D;

		while( true )
		{
			
			// GET THE BACK BUFFER
			graphics2D = (Graphics2D) strategy.getDrawGraphics();
			// DO
			draw(graphics2D);
			// WAIT
			//			System.out.println(player.getHP());
			//			PrintWorld();
			
			try{
				Thread.sleep(20);
			}catch (InterruptedException e){}
		}

		//System.exit(0);
	}

	public World getWorld() {
		return world;
	}

	public Player getPlayer() {
		return player;
	}

	public Window getWindow() {
		return window;
	}
	public void PrintWorld(){
		for (int i = 0; i < world.getDimensionX(); i++) {
			for (int j = 0; j < world.getDimensionY(); j++) {
				System.out.print(world.getWorld()[1][i][j]);
			}
			System.out.println();
		}
		System.out.println();
		System.out.println();
	}
	private void createMap(){
		LoadMap loadMap = new LoadMap();
		world = new World(loadMap);
		player = loadMap.getPlayer();
		window = new Window(800, 672,player,world);
		new CreateZombie(world, player).start();
		new ZombieMovements(world).start();
		new BulletMovements(player,world).start();
		new CreateEnergyBall(world).start();
		new ZombieAction(world).start();
	}
	public static void main(String [] args){
		//				Toolkit kit = Toolkit.getDefaultToolkit();
		//				Dimension dimension = kit.getScreenSize();
		UploadImages.loadImageMap();
		UploadImages.loadImageMercenary();
		
		Game game = new Game();
//		game.newGame();
		
		MainPanel panel = new MainPanel(game);
		game.getContentPane().add(panel);
		game.add(panel);
		
//		LoadMap loadMap = new LoadMap();
//		world = new World(loadMap);
//		player = loadMap.getPlayer();
//		window = new Window(800, 672,player,world);
		//		window = new Window((int)dimension.getWidth(), (int)dimension.getHeight(),player,world);
		//		player = new Player("Filippo",30,30, Direction.STOPDOWN,world); 
		//		new Enemy(31, 31, Direction.DOWN, world, player);
//		new CreateZombie(world, player).start();
//		new ZombieMovements(world).start();
//		new BulletMovements(player,world).start();
//		new CreateEnergyBall(world).start();
//		new ZombieAction(world).start();
//		new Game().run();
	}

	@Override
	public void keyPressed(KeyEvent e){
		int key=e.getKeyCode();

		switch (key) {
		case KeyEvent.VK_UP:premuti[UP]=true;
		break;
		case KeyEvent.VK_DOWN: premuti[DOWN]=true;
		break;
		case KeyEvent.VK_LEFT: premuti[left]=true;
		break;
		case KeyEvent.VK_RIGHT: premuti[right]=true;
		break;
		case KeyEvent.VK_E: premuti[SHOT]=true;
		default:
			break;
		}
		if (motion == null || motion.getState() == Thread.State.TERMINATED) {
			motion = new MotionDispatcher(this);
			motion.start();
		}

	}

	@Override
	public void keyReleased(KeyEvent e) {
		int key=e.getKeyCode();
		switch (key) {
		case KeyEvent.VK_UP:
			premuti[UP]=false;
			break;
		case KeyEvent.VK_DOWN: 
			premuti[DOWN]=false;
			break;
		case KeyEvent.VK_LEFT: 
			premuti[left]=false;
			break;
		case KeyEvent.VK_RIGHT: 
			premuti[right]=false;
			break;
		case KeyEvent.VK_E:
			premuti[SHOT]=false;
		default:
			break;
		}

		if(!premuti[UP] && !premuti[DOWN] && !premuti[left] && !premuti[right]) {
			
		}
	}
	
	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	public boolean[] getPremuti() {
		return premuti;
	}

	public void setPremuti(boolean[] premuti) {
		this.premuti = premuti;
	}
}
Narat è offline   Rispondi citando il messaggio o parte di esso
Old 08-06-2011, 10:19   #2
banryu79
Senior Member
 
L'Avatar di banryu79
 
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
Quote:
Originariamente inviato da Narat Guarda i messaggi
Salve a tutti sto creando un gioco in java con l'utilizzo del bufferimage ma ho un problema cioè: quando creo un pannello oppure utilizzo il frame per creare il menu del gioco come clicco su new game gli eventi della tastiera non funzionano più.

Sapete dirmi il perchè?
Ciao, l'uso di BufferStrategy non c'entra con il tuo problema.
Il componente-sorgente di un KeyEvent è il componente propietario del focus (focus owner).

Nel codice vedo che cerchi di assicurare che Game (in quanto componet sul quale è registrato il key listener) sia il focus owner (ti consiglio di sostituire le chiamate requestFocus() con requestFocusInWindows()).

Però quando rendi visible a video un'altro component (sia esso un menu piuttosto che altro) esso diventa il focus owner, di conseguenza poi succede che eventuali key event vengano generati con quel component come sorgente su cui non c'è nessun listener registrato per ascoltarli (il focus viene spostato ovviamente anche quando l'utente fa click con il mouse su un'altro component).

Dovresti quindi far richiedere a Game il focus (requestFocusInWindow()) ogni volta che lo perde (ad esempio al termine dell'interazione con l'eventuale componente terzo la cui apertura ha causato la perdita del focus).

Se non ti serve ascoltare altri eventi da tastiera su altri componenti a parte che Game forse potresti ovviare in questo modo:

- registri su Game un focus listener (addFocusListener) interessato ad ascoltare gli eventi "focus lost";

- quando il focus listener riceve un evento "focus lost" chiede a quell'evento quale è il component che ha ricevuto il focus (getOppositeComponent);

- se l'opposite component che ha ricevuto il focus NON prevede un'interazione con l'utente immediata e temporanea ed è neccessario far riottenere subito a Game il focus allora <A> altrimenti <B>;

<A>
- il focus listener fa in modo che Game invochi requestFocusInWindow() in modo da riottenere il focus input e quindi ricominciare a intercettare gli eventi da tastiera.

<B>
- il focus listener registra sull'opposite component un component listener (addComponentListener) interessato ad ascoltare gli eventi di "component hidden";
- quando il component listener riceve l'evento "component hidden" fa in modo che Game invochi requestFocusInWindow() in modo da riottenere il focus input e quindi ricominciare a intercettare gli eventi da tastiera, inoltre deregistra se stesso dall'opposite component.
__________________

As long as you are basically literate in programming, you should be able to express any logical relationship you understand.
If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it.
(Chris Crawford)

Ultima modifica di banryu79 : 08-06-2011 alle 10:22.
banryu79 è offline   Rispondi citando il messaggio o parte di esso
Old 08-06-2011, 12:41   #3
Narat
Junior Member
 
Iscritto dal: Oct 2007
Messaggi: 28
ciao banryu79 grazie per la risposta.
Ho provato come mi hai detto e purtroppo non funziona non so se sono io che sto sbagliando ma non va.
Ti allego il codice con le modifiche che ho fatto grazie ancora
Codice:
package GUI;

import java.awt.Graphics2D;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import Thread.ZombieAction;
import Thread.BulletMovements;
import Thread.CreateZombie;
import Thread.CreateEnergyBall;
import Thread.ZombieMovements;
import World.ObjectClass;
import World.UploadImages;
import Players.BulletPlayer;
import Players.Direction;
import Players.Zombie;
import Players.EnergyBall;
import Players.Player;
import World.World;
import XML.LoadMap;
import MouseKeyboardEvents.*;

public class Game extends JFrame implements Runnable,KeyListener, FocusListener, ComponentListener{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final int UP = 0;
	private static final int DOWN = 1;
	private static final int LEFT = 2;
	private static final int RIGHT = 3;
	private static final int SHOT = 4;
	private boolean [] premuti = new boolean[5];
	private static MotionDispatcher motion=null;
	private BufferStrategy strategy;
	private static World world;
	private static Player player;
	private static Window window;
	/**
	 * Constructor
	 */
	public Game()
	{
		initWindow();
		initComponnents();
	}

	/**
	 * initiate the window
	 */
	private void initWindow()
	{
//		setSize(window.getDimensionPixelX(), window.getDimensionPixelY());
		pack();
		setTitle("Gioco");
		setSize(800,672);
//		setUndecorated(true);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setResizable(false);
		setVisible(true);
		setIgnoreRepaint(true);
//		setFocusable(true);
	}

	/**
	 * initiate the componnents
	 */
	private void initComponnents()
	{
		addComponentListener(this);
		addFocusListener(this);
//		setFocusTraversalKeysEnabled(false);
		addKeyListener(this);
	}
	private void initBufferStrategy(){
		createBufferStrategy(2); 
		strategy = getBufferStrategy(); 
		requestFocus();
	}
	
	/**
	 * Draw the frame
	 * @param panel 
	 * @param graphics graphic
	 */
	public void newGame(MainPanel panel){
		
		
	
		initBufferStrategy();
		createMap();
//		initComponnents();
//		game.requestFocus();
		run();
	}
	private void draw(Graphics2D g)
	{
		requestFocusInWindow();
		Player p = null;
		int windowX=window.getPrinterPartX();
		int windowY=window.getPrinterPartY();

		int posX=window.indexWindowX(player,world);
		int posY=window.indexWindowY(player,world);

		for(int i=0; i < world.getLIVELLO()-1; i++)
		{
			for(int j=0; j < windowX; j++)
			{
				for(int k=0; k < windowY; k++)
				{
					if(i == 0){
						if(world.getWorld()[i][posX][posY] instanceof ObjectClass)
						{
							ObjectClass ob = (ObjectClass) world.getWorld()[i][posX][posY];
							g.drawImage(UploadImages.getSummerTiles()[ob.getID()],ob.getPositionWidth()-window.getPositionWidth(), ob.getPositionHeight()-window.getPositionHeight(), null);
						}
					}
					else if(i==1) 
					{
						if(world.getWorld()[i][posX][posY] instanceof Player)
						{
							p= (Player) world.getWorld()[i][posX][posY];
							drawPlayer(g, p);
						}
						else if(world.getWorld()[i][posX][posY] instanceof ObjectClass)
						{
							ObjectClass ob=(ObjectClass) world.getWorld()[1][posX][posY];
							if(ob.getID() != 0)
								g.drawImage(UploadImages.getSummerTiles()[ob.getID()],ob.getPositionWidth()-window.getPositionWidth(), ob.getPositionHeight()-window.getPositionHeight(), null);
						}else if(world.getWorld()[i][posX][posY] instanceof Zombie)
						{
							Zombie e= (Zombie) world.getWorld()[1][posX][posY];
							drawZombie(g,e);
						}else if(world.getWorld()[i][posX][posY] instanceof BulletPlayer)
						{
							BulletPlayer b=(BulletPlayer) world.getWorld()[1][posX][posY];
							drawBullet(g,b);
						}
						else if(world.getWorld()[i][posX][posY] instanceof EnergyBall){
							EnergyBall eb = (EnergyBall) world.getWorld()[i][posX][posY];
							g.drawImage(UploadImages.getEnergyBall(),eb.getPositionWidth()-window.getPositionWidth(), eb.getPositionHeight()-window.getPositionHeight(), null);
						}
					}
					posY++;
				}
				posY=window.indexWindowY(player,world);

				posX++;
			}
			posX=window.indexWindowX(player,world);
		}
		lifeBar(g, p);
		g.dispose();
		
		strategy.show();
		//		PrintWorld();
	}
	private void lifeBar(Graphics2D g, Player p){
		if(p.getHP() >= 100){
			g.drawImage(UploadImages.getLifeBar().get(10),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 100 && p.getHP() >= 90){
			g.drawImage(UploadImages.getLifeBar().get(9),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 90 && p.getHP() >= 80){
			g.drawImage(UploadImages.getLifeBar().get(8),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 80 && p.getHP() >= 70){
			g.drawImage(UploadImages.getLifeBar().get(7),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 70 && p.getHP() >= 60){
			g.drawImage(UploadImages.getLifeBar().get(6),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 60 && p.getHP() >= 50){
			g.drawImage(UploadImages.getLifeBar().get(5),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 50 && p.getHP() >= 40){
			g.drawImage(UploadImages.getLifeBar().get(4),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 40 && p.getHP() >= 30){
			g.drawImage(UploadImages.getLifeBar().get(3),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 30 && p.getHP() >= 20){
			g.drawImage(UploadImages.getLifeBar().get(2),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() < 20 && p.getHP() >= 1){
			g.drawImage(UploadImages.getLifeBar().get(1),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}else if(p.getHP() <= 0){
			g.drawImage(UploadImages.getLifeBar().get(0),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight()-20, null);
		}
	}
	private void drawBullet(Graphics2D g, BulletPlayer b){
		if(b.getDirection() == Direction.UP){
			g.drawImage(UploadImages.getAmmo().get(Direction.UP), b.getPositionWidth()-window.getPositionWidth(),b.getPositionHeight()-window.getPositionHeight(),null);
		}else if(b.getDirection() == Direction.DOWN){
			g.drawImage(UploadImages.getAmmo().get(Direction.DOWN), b.getPositionWidth()-window.getPositionWidth(),b.getPositionHeight()-window.getPositionHeight(),null);
		}else if(b.getDirection() == Direction.LEFT){
			g.drawImage(UploadImages.getAmmo().get(Direction.LEFT), b.getPositionWidth()-window.getPositionWidth(),b.getPositionHeight()-window.getPositionHeight(),null);
		}else if(b.getDirection() == Direction.RIGHT){
			g.drawImage(UploadImages.getAmmo().get(Direction.RIGHT), b.getPositionWidth()-window.getPositionWidth(),b.getPositionHeight()-window.getPositionHeight(),null);
		}
	}

	private void drawZombie(Graphics2D g, Zombie e) {
		// TODO Auto-generated method stub
		//		if(e.getDirection() == Direction.STOPUP)
		//			g.drawImage(UploadImages.getEnemySTOP().get(Direction.STOPUP), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
		//		else if(e.getDirection() == Direction.STOPDOWN)
		//			g.drawImage(UploadImages.getEnemySTOP().get(Direction.STOPDOWN), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
		//		else if(e.getDirection() == Direction.STOPLEFT)
		//			g.drawImage(UploadImages.getEnemySTOP().get(Direction.STOPLEFT), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
		//		else if(e.getDirection() == Direction.STOPRIGHT)
		//			g.drawImage(UploadImages.getEnemySTOP().get(Direction.STOPRIGHT), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);

		if(!e.isAttacking() && !e.isDead()){
			if(e.getDirection() == Direction.UP){
				g.drawImage(UploadImages.getZombieUP().get(e.getSteps()), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
			}
			else if(e.getDirection() == Direction.DOWN){
				g.drawImage(UploadImages.getZombieDown().get(e.getSteps()), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
			}
			else if(e.getDirection() == Direction.LEFT){
				g.drawImage(UploadImages.getZombieLeft().get(e.getSteps()), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
			}
			else if(e.getDirection() == Direction.RIGHT){
				g.drawImage(UploadImages.getZombieRight().get(e.getSteps()), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
			}
		}
		else
		{
			g.drawImage(world.getZombieSprite().get(e.getId()).getCurrentImage(), e.getPositionWidth()-window.getPositionWidth(),e.getPositionHeight()-window.getPositionHeight(),null);
		}
	}

	private void drawPlayer(Graphics2D g, Player p) 
	{
		if(p.getDirection() == Direction.STOPUP && p.getHP() > 0 && p.isShot())
			g.drawImage(UploadImages.getMercenaryShot().get(Direction.UP),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPDOWN && p.getHP() > 0 && p.isShot())
			g.drawImage(UploadImages.getMercenaryShot().get(Direction.DOWN),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPLEFT && p.getHP() > 0 && p.isShot())
			g.drawImage(UploadImages.getMercenaryShot().get(Direction.LEFT),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPRIGHT && p.getHP() > 0 && p.isShot())
			g.drawImage(UploadImages.getMercenaryShot().get(Direction.RIGHT),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPUP && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenarySTOP().get(Direction.STOPUP), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPDOWN && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenarySTOP().get(Direction.STOPDOWN), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPLEFT && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenarySTOP().get(Direction.STOPLEFT), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.STOPRIGHT && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenarySTOP().get(Direction.STOPRIGHT), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.UP && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenaryN().get(p.getSteps()),p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.DOWN && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenaryS().get(p.getSteps()), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.RIGHT && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenaryE().get(p.getSteps()), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getDirection() == Direction.LEFT && p.getHP() > 0)
			g.drawImage(UploadImages.getMercenaryW().get(p.getSteps()), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
		else if(p.getHP() <= 0)
			g.drawImage(SpriteDeadPlayer.getCurrentImagePlayer(), p.getPositionWidth()-window.getPositionWidth(),p.getPositionHeight()-window.getPositionHeight(),null);
	}

	/**
	 * Run the program
	 */
	@Override
	public void run()
	{
		Graphics2D graphics2D;

		while( true )
		{
			// GET THE BACK BUFFER
			graphics2D = (Graphics2D) strategy.getDrawGraphics();
			// DO
			draw(graphics2D);
			// WAIT
			//			System.out.println(player.getHP());
			//			PrintWorld();
			
			try{
				Thread.sleep(20);
			}catch (InterruptedException e){}
		}

		//System.exit(0);
	}

	public World getWorld() {
		return world;
	}

	public Player getPlayer() {
		return player;
	}

	public Window getWindow() {
		return window;
	}
	public void PrintWorld(){
		for (int i = 0; i < world.getDimensionX(); i++) {
			for (int j = 0; j < world.getDimensionY(); j++) {
				System.out.print(world.getWorld()[1][i][j]);
			}
			System.out.println();
		}
		System.out.println();
		System.out.println();
	}
	private void createMap(){
		LoadMap loadMap = new LoadMap();
		world = new World(loadMap);
		player = loadMap.getPlayer();
		window = new Window(800, 672,player,world);
		new CreateZombie(world, player).start();
		new ZombieMovements(world).start();
		new BulletMovements(player,world).start();
		new CreateEnergyBall(world).start();
		new ZombieAction(world).start();
	}
	public static void main(String [] args){
		//				Toolkit kit = Toolkit.getDefaultToolkit();
		//				Dimension dimension = kit.getScreenSize();
		UploadImages.loadImageMap();
		UploadImages.loadImageMercenary();
		
		Game game = new Game();
//		game.newGame();
		MainPanel panel = new MainPanel(game);
		game.getContentPane().add(panel);
		game.add(panel);
		
//		LoadMap loadMap = new LoadMap();
//		world = new World(loadMap);
//		player = loadMap.getPlayer();
//		window = new Window(800, 672,player,world);
		//		window = new Window((int)dimension.getWidth(), (int)dimension.getHeight(),player,world);
		//		player = new Player("Filippo",30,30, Direction.STOPDOWN,world); 
		//		new Enemy(31, 31, Direction.DOWN, world, player);
//		new CreateZombie(world, player).start();
//		new ZombieMovements(world).start();
//		new BulletMovements(player,world).start();
//		new CreateEnergyBall(world).start();
//		new ZombieAction(world).start();
//		new Game().run();
	}

	@Override
	public void keyPressed(KeyEvent e){
		int key=e.getKeyCode();

		switch (key) {
		case KeyEvent.VK_UP:premuti[UP]=true;
		break;
		case KeyEvent.VK_DOWN: premuti[DOWN]=true;
		break;
		case KeyEvent.VK_LEFT: premuti[left]=true;
		break;
		case KeyEvent.VK_RIGHT: premuti[right]=true;
		break;
		case KeyEvent.VK_E: premuti[SHOT]=true;
		default:
			break;
		}
		if (motion == null || motion.getState() == Thread.State.TERMINATED) {
			motion = new MotionDispatcher(this);
			motion.start();
		}

	}

	@Override
	public void keyReleased(KeyEvent e) {
		int key=e.getKeyCode();
		switch (key) {
		case KeyEvent.VK_UP:
			premuti[UP]=false;
			break;
		case KeyEvent.VK_DOWN: 
			premuti[DOWN]=false;
			break;
		case KeyEvent.VK_LEFT: 
			premuti[left]=false;
			break;
		case KeyEvent.VK_RIGHT: 
			premuti[right]=false;
			break;
		case KeyEvent.VK_E:
			premuti[SHOT]=false;
		default:
			break;
		}

		if(!premuti[UP] && !premuti[DOWN] && !premuti[left] && !premuti[right]) {
			
		}
	}
	
	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	public boolean[] getPremuti() {
		return premuti;
	}

	public void setPremuti(boolean[] premuti) {
		this.premuti = premuti;
	}

	@Override
	public void focusGained(FocusEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void focusLost(FocusEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("ENTRAFocusLost");
		requestFocusInWindow();
	}

	@Override
	public void componentHidden(ComponentEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("componentHidden");
		requestFocusInWindow();
	}

	@Override
	public void componentMoved(ComponentEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void componentResized(ComponentEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void componentShown(ComponentEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}
Narat è offline   Rispondi citando il messaggio o parte di esso
Old 09-06-2011, 10:03   #4
Narat
Junior Member
 
Iscritto dal: Oct 2007
Messaggi: 28
nessun altro sa come aiutarmi per risolvere questo problema?
Narat è offline   Rispondi citando il messaggio o parte di esso
Old 09-06-2011, 15:32   #5
banryu79
Senior Member
 
L'Avatar di banryu79
 
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
Ciao, beh, non hai implementato quello che ti suggerivo (ma che a questo punto mi riservo di provare appena ho tempo, per verificarne il funzionamento).

Comunque ho una soluzione alternativa più "radicale": agganciare un KeyEventDispatcher al KeyboardFocusManager globale.
Alla pressione dei tasti a cui sei interessato, il KeyEventDispatcher eseguirà le azioni che ti servono, a prescindere da quale component sia il "focus owner" in quel momento.

Qui trovi un esempio di implementazione di un KeyEventDispatcher collegato al KeyboardFocusManager, tanto per farsi l'occhio.

Stabiliamo che:
con il termine "dispatcher" intendiamo KeyEventDispatcher;
con il termine "kf manager" intendiamo KeyboardFocusManager

Diciamo che:
1 - Game non è più un KeyListener ma definisce e istanzia un dispatcher per processare la pressione dei tasti con la stessa logica del listener di prima;
2 - Appena Game (in quanto finestra) diventa visibile, registra il dispatcher presso il kf manager;
3 - Appena Game (in quanto finestra) viene chiusa, de-registra il dispatcher dal kf manager.

il punto 1) lo localizziamo nel costruttore di Game.
il punto 2) e 3) li possimao localizzare rispettivamente nei metodi windowOpened e windowClosing di un WindowListener che ascolterà "eventi finestra" (WindowEvent) emessi da Game.

Game può essere il WindowListener di se stesso, oppure nel costruttore di Game istanziamo al volo in forma anonima un WindowsAdapter che ascolta Game.

Calato nel tuo contesto dovrebbe essere qualcosa del tipo:
Codice:
public class Game extends JFrame implements Runnable {
    
    // membri di Game...
    
    public Game() {
        // implementazione del dispatcher custom
        final KeyEventDispatcher DISPATCHER = new KeyEventDispatcher() {
                private final boolean ON = true;
                private final boolean OFF = false;

                @Override public boolean dispatchKeyEvent(KeyEvent e) {
                    if (e.getID() == KeyEvent.KEY_PRESSED)
                        return keyPressed(e);
                    if (e.getID() == KeyEvent.KEY_RELEASED)
                        return keyReleased(e);
                }

                private boolean keyPressed(KeyEvent e) {
                    boolean consumed = true;

                    switch (e.getKeyCode()) {
                        case KeyEvent.VK_UP: premuti[UP] = ON;
                        break;
                        case KeyEvent.VK_DOWN: premuti[DOWN] = ON;
                        break;
                        case KeyEvent.VK_LEFT: premuti[left] = ON;
                        break;
                        case KeyEvent.VK_RIGHT: premuti[right] = ON;
                        break;
                        case KeyEvent.VK_E: premuti[SHOT] = ON;
                        default:
                            consumed = false;
                    }

                    if (motion == null || motion.getState() == Thread.State.TERMINATED) {
                        motion = new MotionDispatcher(this);
                        motion.start();
                    }

                    return consumed;
                }

                private boolean keyReleased(KeyEvent e) {
                    boolean consumed = true;

                    switch (e.getKeyCode()) {
                        case KeyEvent.VK_UP: premuti[UP] = OFF;
                        break;
                        case KeyEvent.VK_DOWN: premuti[DOWN] = OFF;
                        break;
                        case KeyEvent.VK_LEFT: premuti[left] = OFF;
                        break;
                        case KeyEvent.VK_RIGHT: premuti[right] = OFF;
                        break;
                        case KeyEvent.VK_E: premuti[SHOT] = OFF;
                        default:
                            consumed = false;
                    }

                    if(!premuti[UP] && !premuti[DOWN] && !premuti[left] && !premuti[right]) {
                        // fai quel che devi...
                    }

                    return consumed;
                }
            };

            // implementazione del window listener per collegamento 
            // del dispatcher con il kf manager
            WindowAdapter kfmanagerHack = new WindowAdapter() {
                @Override public void windowOpened(WindowEvent e) {
                    KeyboardFocusManager.getCurrentKeyboardFocusManager()
                            .addKeyEventDispatcher(DISPATCHER);
                }
                
                @Override public void windowClosing(WindowEvent e) {
                    KeyboardFocusManager.getCurrentKeyboardFocusManager()
                            .removeKeyEventDispatcher(DISPATCHER);
                }
            };
            this.addWindowListener(kfmanagerHack);

            initWindow();
            initComponnents();
    }

}
Nota_1: Game ora non dovrà più implementare KeyListener, FocusListener e ComponentListener.
Nota_2: Puoi rimuovere tutte le chiamate a requestFocusInWindow presenti in Game, non sono più strettamente neccessarie.

P.S.: codice non testato e non completo. E' giusto per darti un'idea.

Ciao
__________________

As long as you are basically literate in programming, you should be able to express any logical relationship you understand.
If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it.
(Chris Crawford)

Ultima modifica di banryu79 : 09-06-2011 alle 15:38.
banryu79 è offline   Rispondi citando il messaggio o parte di esso
Old 09-06-2011, 15:45   #6
Narat
Junior Member
 
Iscritto dal: Oct 2007
Messaggi: 28
Grazie ancora per l'aiuto, purtroppo sono con l'acqua alla gola devo finire questo progetto e fare l'esame.

Ti faro' sapere se riesco a far funzionare questi benedetti tasti :P

Grazie ancora
Narat è offline   Rispondi citando il messaggio o parte di esso
Old 09-06-2011, 15:52   #7
banryu79
Senior Member
 
L'Avatar di banryu79
 
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
C'è un errore nell'implementazione del metodo dispatchKeyEvent, deve essere così:
Codice:
                @Override public boolean dispatchKeyEvent(KeyEvent e) {
                    if (e.getID() == KeyEvent.KEY_PRESSED)
                        return keyPressed(e);
                    if (e.getID() == KeyEvent.KEY_RELEASED)
                        return keyReleased(e);
                    return false;
                }
__________________

As long as you are basically literate in programming, you should be able to express any logical relationship you understand.
If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it.
(Chris Crawford)
banryu79 è offline   Rispondi citando il messaggio o parte di esso
Old 09-06-2011, 16:13   #8
Narat
Junior Member
 
Iscritto dal: Oct 2007
Messaggi: 28
ho un problema con il MotionDispatcher praticamente io al motion dispatcher passo la classe game ora mi dice di passare un keyeventDispatcher

ti passo la classe MotionDispatcher

Codice:
package MouseKeyboardEvents;

import GUI.Game;
import GUI.Window;
import Players.Direction;
import Players.Player;
import World.World;

public class MotionDispatcher extends Thread {
	private static final int UP = 0;
	private static final int DOWN = 1;
	private static final int LEFT = 2;
	private static final int RIGHT = 3;
	private static final int SHOT = 4;
	private static final int DIM=5;
	private int sleep;
	private Window window;
	private World world;
	//private Game game;
	private Player player;
	private boolean [] premuti = new boolean[DIM];

	public MotionDispatcher(Game game){
		//this.game=game;
		this.premuti=game.getPremuti();
		this.player=game.getPlayer();
		this.window=game.getWindow();
		this.world=game.getWorld();
		sleep=70;
	}

	public void run() {
		while(true){		
			//			Nord Ovest
			if(premuti[UP] && premuti[left] && !premuti[DOWN] && !premuti[right]){

			}
			//			Nord Est
			else if(premuti[UP] && premuti[right] && !premuti[DOWN] && !premuti[left]){

			}
			//			UPd Ovest
			else if(premuti[DOWN] && premuti[left] && !premuti[right] && !premuti[UP]){

			}
			//			UPd Est
			else if(premuti[DOWN] && premuti[right] && !premuti[UP] && !premuti[left]){

			}
			//			UP
			else if(premuti[UP] && !premuti[DOWN] && !premuti[left] && !premuti[right]) {
				sleep=70;
				player.setDirection(Direction.UP);
				player.playerUp(window, world);
				window.windowUp();
			}
			//			DOWN
			else if(premuti[DOWN] && !premuti[UP] && !premuti[left] && !premuti[right]){
				sleep=70;
				player.setDirection(Direction.DOWN);
				player.playerDown(window, world);
				window.windowDown();
			}
			//			LEFT
			else if(premuti[left] && !premuti[UP] && !premuti[DOWN] && !premuti[right]){
				sleep=70;
				player.setDirection(Direction.LEFT);
				player.playerLeft(window, world);
				window.windowLeft();
			}
			//			RIGHT
			else if(premuti[right] && !premuti[UP] && !premuti[DOWN] && !premuti[left]){
				sleep=70;
				player.setDirection(Direction.RIGHT);
				player.playerRight(window, world);
				window.windowRight();
			}
			else if(premuti[SHOT] && !premuti[right] && !premuti[UP] && !premuti[DOWN] && !premuti[left]){
				sleep=300;
				player.setShot(true);
				player.deathOccurs();
				player.shot(window, world);
				player.setShot(false);
			}
			else if(!premuti[right] && !premuti[UP] && !premuti[DOWN] && !premuti[left]){
				sleep=70;
				if(player.getDirection() == Direction.UP)
					player.setDirection(Direction.STOPUP);
				else if(player.getDirection() == Direction.DOWN)
					player.setDirection(Direction.STOPDOWN);
				else if(player.getDirection() == Direction.LEFT)
					player.setDirection(Direction.STOPLEFT);
				else if(player.getDirection() == Direction.RIGHT)
					player.setDirection(Direction.STOPRIGHT);
				player.setSteps(0);
			}
			player.deathOccurs();
			try {
				sleep(sleep);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
anche se faccio prima a mandarti tutto il progetto se andiamo a vedere :P
Narat è offline   Rispondi citando il messaggio o parte di esso
Old 09-06-2011, 16:21   #9
banryu79
Senior Member
 
L'Avatar di banryu79
 
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
Quote:
Originariamente inviato da Narat Guarda i messaggi
ho un problema con il MotionDispatcher praticamente io al motion dispatcher passo la classe game ora mi dice di passare un keyeventDispatcher

ti passo la classe MotionDispatcher

Codice:
... snip.
anche se faccio prima a mandarti tutto il progetto se andiamo a vedere :P
Ciao, allora:
1) non ho capito cosa significa: "ho un problema con il MotionDispatcher praticamente io al motion dispatcher passo la classe game ora mi dice di passare un keyeventDispatcher"

ma, in ogni caso:
2) le modifiche che ti ho suggerito di apportare a Game non hanno alcuna conseguenza circa il fatto che la tua classe MotionDispatcher richiede un'istanza della classe Game come parametro nel costruttore.

@EDIT: a scanso di equivoci, non ti ho postato soluzioni complete e funzionanti ma i miei vogliono solo essere suggerimenti di implementazione. Adattarli al tuo contesto (che non conosco) e renderli funzionanti nel dettaglio spetta a te
__________________

As long as you are basically literate in programming, you should be able to express any logical relationship you understand.
If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it.
(Chris Crawford)

Ultima modifica di banryu79 : 09-06-2011 alle 16:32.
banryu79 è offline   Rispondi citando il messaggio o parte di esso
Old 09-06-2011, 16:32   #10
banryu79
Senior Member
 
L'Avatar di banryu79
 
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
Aspetta, ho capito dove hai il problema e perchè.
Dammi qualche minuto che ti scrivo il post.
__________________

As long as you are basically literate in programming, you should be able to express any logical relationship you understand.
If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it.
(Chris Crawford)
banryu79 è offline   Rispondi citando il messaggio o parte di esso
Old 09-06-2011, 16:35   #11
Narat
Junior Member
 
Iscritto dal: Oct 2007
Messaggi: 28
Scusami se mi spiego come un cane

ti inserisco l'immagine cosi capisci meglio
http://imageshack.us/photo/my-images...609a16290.png/

Ultima modifica di Narat : 09-06-2011 alle 16:40.
Narat è offline   Rispondi citando il messaggio o parte di esso
Old 09-06-2011, 16:39   #12
banryu79
Senior Member
 
L'Avatar di banryu79
 
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
Ristrutturiamo la "soluzione" così.
- Game implementa WindowListener che registra su se stesso in costruzione;
- Game ha un KeyEventDispatcher che istanzia e registra presso il KeyboradFocusManager quando capita windowOpened
- Game deregistra il dispatcher quando capita windowClosing

ecco:
Codice:
public class Game extends JFrame implements Runnable, WindowListener {
    // membri di Game...
    private KeyEventDispatcher dispatcher;

	/**
	 * Constructor
	 */
	public Game()
	{
            this.addWindowListener(this);

            initWindow();
            initComponnents();
	}

        public void windowOpened(WindowEvent e) {

            dispatcher = new KeyEventDispatcher() {
                private final boolean ON = true;
                private final boolean OFF = false;

                @Override public boolean dispatchKeyEvent(KeyEvent e) {
                    if (e.getID() == KeyEvent.KEY_PRESSED)
                        return keyPressed(e);
                    if (e.getID() == KeyEvent.KEY_RELEASED)
                        return keyReleased(e);
                    return false;
                }

                private boolean keyPressed(KeyEvent e) {
                    boolean consumed = true;

                    switch (e.getKeyCode()) {
                        case KeyEvent.VK_UP: premuti[UP] = ON;
                        break;
                        case KeyEvent.VK_DOWN: premuti[DOWN] = ON;
                        break;
                        case KeyEvent.VK_LEFT: premuti[left] = ON;
                        break;
                        case KeyEvent.VK_RIGHT: premuti[right] = ON;
                        break;
                        case KeyEvent.VK_E: premuti[SHOT] = ON;
                        default:
                            consumed = false;
                    }

                    if (motion == null || motion.getState() == Thread.State.TERMINATED) {
                        motion = new MotionDispatcher(Game.this);
                        motion.start();
                    }

                    return consumed;
                }

                private boolean keyReleased(KeyEvent e) {
                    boolean consumed = true;

                    switch (e.getKeyCode()) {
                        case KeyEvent.VK_UP: premuti[UP] = OFF;
                        break;
                        case KeyEvent.VK_DOWN: premuti[DOWN] = OFF;
                        break;
                        case KeyEvent.VK_LEFT: premuti[left] = OFF;
                        break;
                        case KeyEvent.VK_RIGHT: premuti[right] = OFF;
                        break;
                        case KeyEvent.VK_E: premuti[SHOT] = OFF;
                        default:
                            consumed = false;
                    }

                    if(!premuti[UP] && !premuti[DOWN] && !premuti[left] && !premuti[right]) {
                        // fai quel che devi...
                    }

                    return consumed;
                }
            };
            
            KeyboardFocusManager.getCurrentKeyboardFocusManager()
                .addKeyEventDispatcher(dispatcher);
        }

        public void windowClosing(WindowEvent e) {
            KeyboardFocusManager.getCurrentKeyboardFocusManager()
                .removeKeyEventDispatcher(dispatcher);
        }

        public void windowClosed(WindowEvent e) {}

        public void windowIconified(WindowEvent e) {}

        public void windowDeiconified(WindowEvent e) {}

        public void windowActivated(WindowEvent e) {}

        public void windowDeactivated(WindowEvent e) {}
        
        // ecc...
}
__________________

As long as you are basically literate in programming, you should be able to express any logical relationship you understand.
If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it.
(Chris Crawford)
banryu79 è offline   Rispondi citando il messaggio o parte di esso
Old 09-06-2011, 16:55   #13
Narat
Junior Member
 
Iscritto dal: Oct 2007
Messaggi: 28
Incredibile non va io non so che pesci prendere cmq ti do il link del gioco

http://www.megaupload.com/?d=AKRXD02E
Narat è offline   Rispondi citando il messaggio o parte di esso
Old 09-06-2011, 17:22   #14
Narat
Junior Member
 
Iscritto dal: Oct 2007
Messaggi: 28
Ti ringrazio dell'aiuto ma non va e non riesco a capire il perché, senza il menu va bene, se aggiungo il menu no mhaa
Narat è offline   Rispondi citando il messaggio o parte di esso
Old 09-06-2011, 17:36   #15
Narat
Junior Member
 
Iscritto dal: Oct 2007
Messaggi: 28
Cmq ho notato che il focus lo porde non appena carico la mappa da un file xml
Narat è offline   Rispondi citando il messaggio o parte di esso
Old 11-06-2011, 02:58   #16
Narat
Junior Member
 
Iscritto dal: Oct 2007
Messaggi: 28
Ti ringrazio per l'aiuto ma dopo tanto sbattimento un ragazzo mi ha detto come risolvere il problema è bastato avviare il thread new Thread(this).start() ed il gioco e' partito tranquillamente funzionando anche i tasti scusami se ti ho stressato grazie ancora
Narat è offline   Rispondi citando il messaggio o parte di esso
 Rispondi


Insta360 Link 2 Pro e 2C Pro: le webcam 4K che ti seguono, anche con gimbal integrata Insta360 Link 2 Pro e 2C Pro: le webcam 4K che t...
Motorola edge 70: lo smartphone ultrasottile che non rinuncia a batteria e concretezza Motorola edge 70: lo smartphone ultrasottile che...
Display, mini PC, periferiche e networking: le novità ASUS al CES 2026 Display, mini PC, periferiche e networking: le n...
Le novità ASUS per il 2026 nel settore dei PC desktop Le novità ASUS per il 2026 nel settore de...
Le novità MSI del 2026 per i videogiocatori Le novità MSI del 2026 per i videogiocato...
Dipartimento dell'Energia degli Stati Un...
Leapmotor B03X al debutto europeo: &egra...
Pixelmator Pro debutta su iPad: la versi...
Il gioco di Batman: The Dark Knight &egr...
Cancellata la missione Mars Sample Retur...
Matthew McConaughey registra la propria ...
Microsoft AI Diffusion Report: l'adozion...
Questo gioco è stato cancellato d...
Smartphone in ripresa a fine 2025: Apple...
Windows distrutto in una frase: il 'nuo...
iPhone 17 Pro da 512 GB in offerta: pote...
Apple lancia Creator Studio: Final Cut P...
Bandcamp vieta la musica generata dall'I...
Volvo contro Sunwoda, botta e risposta: ...
GRU Space vuole costruire un hotel sulla...
Chromium
GPU-Z
OCCT
LibreOffice Portable
Opera One Portable
Opera One 106
CCleaner Portable
CCleaner Standard
Cpu-Z
Driver NVIDIA GeForce 546.65 WHQL
SmartFTP
Trillian
Google Chrome Portable
Google Chrome 120
VirtualBox
Tutti gli articoli Tutte le news Tutti i download

Strumenti

Regole
Non Puoi aprire nuove discussioni
Non Puoi rispondere ai messaggi
Non Puoi allegare file
Non Puoi modificare i tuoi messaggi

Il codice vB è On
Le Faccine sono On
Il codice [IMG] è On
Il codice HTML è Off
Vai al Forum


Tutti gli orari sono GMT +1. Ora sono le: 15:41.


Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Served by www3v