我正在创建一个双人游戏,我在创建两个可移动玩家图像方面遇到了一些困难。我应该只做一个玩家一个玩家两个claas还是这个玩家?这是我目前的非工作代码:
package game;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
public class Speler {
private Image image;
private int x = 0, y = 0, velX=0, velY = 0;
private int eerste;
public Speler(int welke){
welke = eerste;
if( welke < 10){ImageIcon ii = new ImageIcon("C:\\Users\\gil\\Pictures\\blauw vierkant.png" );
image = ii.getImage();
x = 40;
y = 160;}
else{ ImageIcon ii = new ImageIcon("C:\\Users\\gil\\Pictures\\paars vierkant.png" );
image = ii.getImage();
x = 520;
y = 10;}
}
public void move(){
if (x<0)
{
velX = 0;
x=0;
}
if (x>545)
{
velX = 0;
x=545;
}
if (y<0)
{
velY = 0;
y=0;
}
if (y>323)
{
velY = 0;
y=323;
}
x = x + velX;
y = y + velY;
}
public void keyPressed(KeyEvent e){
int c = e.getKeyCode();
if (eerste < 10){
if (c == KeyEvent.VK_Q)
{
velX = -1;
velY = 0;
}
if (c == KeyEvent.VK_Z)
{
velX = 0;
velY = -1;
}
if (c == KeyEvent.VK_D)
{
velX = 1;
velY = 0;
}
if (c == KeyEvent.VK_S)
{
velX = 0;
velY = 1;}
else{
if (c == KeyEvent.VK_LEFT)
{
velX = -1;
velY = 0;
}
if (c == KeyEvent.VK_UP)
{
velX = 0;
velY = -1;
}
if (c == KeyEvent.VK_RIGHT)
{
velX = 1;
velY = 0;
}
if (c == KeyEvent.VK_DOWN)
{
velX = 0;
velY = 1;
}
}
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){
velX = 0;
velY = 0;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return image;
}
public void Drawspeler(Graphics g){
Graphics2D g2d1 = (Graphics2D) g;
g2d1.drawImage(image,x,y,null);
}
}
package game;
import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
public class Board extends JPanel implements ActionListener{
private Timer tm;
private Speler speler1;
private Speler speler2;
public Board(){
addKeyListener(new Indrukken());
setFocusable(true);
setFocusTraversalKeysEnabled(false);
speler1 = new Speler(1);
speler2 = new Speler(50);
tm = new Timer(10, this);
tm.start();
}
public void paintComponent(Graphics g ) {
super.paintComponent(g);
speler1.Drawspeler(g);
speler2.Drawspeler(g);
}
public void actionPerformed(ActionEvent e){
speler1.move();
speler2.move();
repaint();
}
private class Indrukken extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e){
speler1.keyPressed(e);
speler2.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e){
speler1.keyReleased(e);
speler2.keyReleased(e);
}
}
}