How can I sort objects? - java

I'm trying draw some objects in an opengl world . these objects have transparency so. and when I rotate them the transparency doesn't blend color .
How can I sort the draw order, so I can draw from more distant object to closest?
I've tryed with bounding box and get the more distance point .
then sort objects with a bubblesort. Then I give to Renderer the IndexArray sorted.
This is Bounding box.
public class BoundingBox extends java.lang.Object {
private UlVertexBuffer mVb=null;
private UlIndexBuffer mIb=null;
private UlTransform mTransform=null;
private UlVertexBuffer subsetVertexBuffer;
private UlMatrix4x4[] mM=new UlMatrix4x4[2];
private float array[][]=new float[2][16];
private float minX,minY,minZ,maxX,maxY,maxZ=0; // min and max value of the vector components
public BoundingBox (UlVertexBuffer vb, UlIndexBuffer ib)
{
FloatBuffer fb =(FloatBuffer) vb.getData(UlVertexBuffer.VERTEX_FIELD_POSITION).position(0);
float [] fa = new float [fb.capacity()];
fb.get(fa);
ShortBuffer sb = (ShortBuffer)ib.getData();
short [] sa = new short[sb.capacity()];
sb.get(sa);
calcBox(fa,sa);
mM[0]=new UlMatrix4x4(array[0]);
mM[1]=new UlMatrix4x4(array[1]);
}
public void calcBox(UlVertexBuffer vb, UlIndexBuffer ib)
{
FloatBuffer fb =(FloatBuffer) vb.getData(UlVertexBuffer.VERTEX_FIELD_POSITION).position(0);
float [] fa = new float [fb.capacity()];
fb.get(fa);
ShortBuffer sb = (ShortBuffer)ib.getData();
short [] sa = new short[sb.capacity()];
sb.get(sa);
calcBox(fa,sa);
}
public void calcBox(float[] vertexArray,short[] indexArray)
{
for(int j=0;j<indexArray.length ;j++)
{
short i=(short) (indexArray[j]*3);
if(vertexArray[i]>maxX)
{
maxX=vertexArray[i];
}
if(vertexArray[i]<minX)
{
minX=vertexArray[i];
}
if(vertexArray[i+1]>maxY)
{
maxY=vertexArray[i+1];
}
if(vertexArray[i]<minY)
{
minY=vertexArray[i+1];
}
if(vertexArray[i+2]>maxZ)
{
maxZ=vertexArray[i+2];
}
if(vertexArray[i+2]<minZ)
{
minZ=vertexArray[i+2];
}
}
array[0][0]=minX;
array[0][5]=minY;
array[0][10]=minZ;
array[0][15]=1;
array[1][0]=maxX;
array[1][5]=maxY;
array[1][10]=maxZ;
array[1][15]=1;
}
public float[][] getBoundingBox()
{
return array;
}
public UlMatrix4x4 matrixBox(int index)
{
if(mM[0]==null||mM[1]==null){
mM[0]= new UlMatrix4x4(array[0]);
mM[1]= new UlMatrix4x4(array[1]);
}
return mM[index];
}
public UlVector3 getVertex(int Index)
{
UlVector3 vertex=null;
switch (Index)
{
case 0:
vertex.set(array[0][0], array[0][1], array[0][2]);
break;
case 1:
vertex.set(array[1][0], array[0][1], array[0][2]);
break;
case 2:
vertex.set(array[1][0], array[0][1], array[1][2]);
break;
case 3:
vertex.set(array[0][0], array[0][1], array[1][2]);
break;
case 4:
vertex.set(array[0][0], array[1][1], array[0][2]);
break;
case 5:
vertex.set(array[1][0], array[1][1], array[0][2]);
break;
case 6:
vertex.set(array[1][0], array[1][1], array[1][2]);
break;
case 7:
vertex.set(array[0][0], array[1][1], array[1][2]);
break;
}
return vertex;
}
public float getMaxDistance(UlVector3 P1)
{float Mdistance=getDistance(P1, getVertex(0));
for(int i=1; i<8;i++)
{
if(Mdistance<getDistance(P1, getVertex(i)))
{
Mdistance=getDistance(P1, getVertex(i));
}
}
return Mdistance;
}
private float getDistance(UlVector3 P1,UlVector3 P2)
{
float distance =0;
float dx=P2.getX()-P1.getX();
float dy=P2.getY()-P1.getY();
float dz=P2.getZ()-P1.getZ();
return (float) Math.sqrt(dx*dx+dy*dy+dz*dz);
}
public void reverseMatrix()
{
array[0]=mM[0].toArray();
array[1]=mM[1].toArray();
}
}
this is the DrawUnscrambler
public class DrawUnscrambler {
private UlVector3 mCamPos=null;
private UlMesh mMesh= null;
private UlSubset mSubsets[]=null;
private int mIndex[]=null;
private boolean sorted=false;
public UlVector3 getmCamPos() {
return mCamPos;
}
public void setmCamPos(UlVector3 mCamPos) {
this.mCamPos = mCamPos;
}
public UlMesh getmMesh() {
return mMesh;
}
public void setmMesh(UlMesh mMesh) {
this.mMesh = mMesh;
}
public UlSubset[] getmSubsets() {
return mSubsets;
}
public void setmSubsets(UlSubset[] mSubsets) {
this.mSubsets = mSubsets;
}
public int[] getmIndex() {
return mIndex;
}
public void setmIndex(int[] mIndex) {
this.mIndex = mIndex;
}
public DrawUnscrambler(UlMesh mesh,UlVector3 CamPosition)
{
mMesh=mesh;
setmCamPos(CamPosition);
initIndex();
getSubset();
SubsetSort();
}
private void getSubset()
{mSubsets= new UlSubset[mMesh.subsetCount()];
for(int i =0 ; i <mMesh.subsetCount()-1;i++ )
{
mSubsets[i]=mMesh.getSubset(i);
}
}
private void initIndex()
{
mIndex= new int[mMesh.subsetCount()];
for(int i =0 ; i <=mMesh.subsetCount()-1;i++)
{
mIndex[i]=i;
}
}
private void SubsetSort()
{
for(int i =0; i <mMesh.subsetCount()-1;i++)
{
for(int j=0;j<mMesh.subsetCount()-2-i;j++)
{// controlla qui
if(mSubsets[mIndex[j]].getmBoundingBox().getMaxDistance(mCamPos)<mSubsets[mIndex[j+1]].getmBoundingBox().getMaxDistance(mCamPos))
{
int t=mIndex[j];
mIndex[j]=mIndex[j+1];
mIndex[j+1]=t;
}
}
}
sorted=true;
}
public int getSubsetIndex(int i)
{
if(sorted)
{
return mIndex[i];
}
else
{
if(mMesh!=null)
{
initIndex();
getSubset();
SubsetSort();
}
}
return mIndex[i];
}
}
The indexArray is the array sorted that is passed to Renderer in draw function
but it's don't change draw order. How can I do it?

Related

RPG game code error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I keep getting this error in my code. Can someone fix it and how is the code written? Can it be improved by maybe using setters and getters only?
Exception in thread "main" java.lang.NullPointerException
at Player.attack(Player.java:72)
at Main.main(Main.java:15)
My code:
Player.java
public class Player {
String name;
String race;
int hp;
int power;
int armour;
Weapon weapon;
public Player (String n, String r, int h, int p, int a) {
name = n;
race =r;
hp = h;
power = p;
armour = a;
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setRace (String r) {
race = r;
}
public String getRace() {
return race;
}
public void setHP (int h) {
hp = h;
}
public int getHP() {
return hp;
}
public void setPower (int p) {
power = p;
}
public int getPower() {
return power;
}
public void setArmour (int a) {
armour = a;
}
public int getArmour() {
return armour;
}
public boolean dead() {
return hp <= 0;
}
public boolean equip(Weapon weapon) {
this.weapon = weapon;
return true;
}
public boolean receiveDamage(int i) {
if ((hp - i) > 0) {
hp = hp - i;
return true;
}
hp = 0;
return false;
}
public boolean attack(Player player) {
return player.receiveDamage(weapon.useWeapon());
}
}
Main.java
public class Main {
public static void main(String args[]) {
Player Mensch = new Player("Mensch", "Mensch", 85, 12, 10);
Player Ork = new Player("Shrek", "Ork", 50, 14, 6);
Weapon MenschW = new Weapon("mächtiges Schwert", 15, 100);
Weapon OrkW = new Weapon("große Axt", 7, 100);
Mensch.equip(Mensch.weapon);
Ork.equip(Ork.weapon);
while (!Mensch.dead() && !Ork.dead() ) { //Alternativ: for (player hp >=0)
System.out.println("Mensch gegen Ork " + Mensch.attack(Ork));
if (Mensch.dead() || Ork.dead()) {
break;
}
System.out.println("Mensch gegen Ork " + Ork.attack(Mensch));
}
System.out.println("Ork ist tot: " + Ork.dead());
System.out.println("Mensch ist tot: " + Mensch.dead());
}
}
Weapon.java
import java.util.concurrent.ThreadLocalRandom;
public class Weapon {
String name;
int damage;
int hp;
public Weapon(String string, int d, int hp) {
// TODO Auto-generated constructor stub
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setDamage (int d) {
damage = d;
}
public int getDamage() {
return damage;
}
public void setWHP (int h) {
hp = h;
}
public int getWHP() {
return hp;
}
public int useWeapon() {
if
(broken())
return 0;
hp = hp - 5;
return (damage / 2) + random();
}
private int random() {
return ThreadLocalRandom.current().nextInt(1, damage + 1);
}
private boolean broken() {
return hp <= 0;
}
}
I know its a lot of code but I keep getting the same error, also I'm quite new to java so I would appreciate some tips or suggestions to make my code better or more failsave. The code doesn't do much yet but it will (hopefully) be a simple game soon in which two characters fight eachother with some calculations on damageoutput of each player. In this case a Human and Ork. Feel free to try it out
Change
Mensch.equip(Mensch.weapon); // Mensch.weapon is not initialized in constructor so it is null.
Ork.equip(Ork.weapon); // Ork.weapon is not initialized in constructor so it is null as well.
To
// Use your newly created weapons in the main instead.
Mensch.equip(MenschW );
Ork.equip(OrkW);

Java Applet will not load on Web or in HTML file, what am I doing wrong?

I am attempting to create a Java applet, and yes, I know, deprecated, blah blah blah, I have my reasons. I cannot seem to get the file to load for any reason via either placing it on my website or by using an HTML file to load it locally. Any help in this matter would be most appreciated, as this is frustrating me to no end.
<html>
<head>
<title>
Applet
</title>
</head>
<body>
<h2>Applet</h2>
<embed
archive="eloRating.jar"
code="eloRatingSystem"
width=550 height=300>
This means you done goofed
</applet>
</body>
</html>
.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.util.ArrayList;
#SuppressWarnings("serial")
public class eloRatingSystem extends JApplet /*implements Runnable*/{
/*****************************************************************************/
private static final int BUTTON_HEIGHT = 50;
private static final int BUTTON_WIDTH = 150;
/*****************************************************************************/
private Button newPlayer, editPlayer, editTeams, commitMatch, downloadBook;
private JButton editPopUp;
/*****************************************************************************/
private JComponent[] inputs;
private JComponent[] tables;
/*****************************************************************************/
private int testRow;
private int playerCounter;
/*****************************************************************************/
private ArrayList<Player> pList;
/*****************************************************************************/
private String[] titles;
/*****************************************************************************/
private ListenForAction lForAction;
/*****************************************************************************/
private modifyExcel book;
/*****************************************************************************/
private JPanel panel;
/*****************************************************************************/
private JTable playerTable;
/*****************************************************************************/
private TableRowSorter<?> sorter;
/*****************************************************************************/
Dimension d;
/*****************************************************************************/
/*****************************Initialization**********************************/
public void init() {
inputs = new JComponent[]{
new JLabel("Enter The Player's Name"),
};
testRow = 10000;
playerCounter = 0;
lForAction = new ListenForAction();
book = new modifyExcel();
book.openExcel();
titles = new String[6];
panel = new JPanel();
pList = new ArrayList<Player>();
d = new Dimension(500,140);
titles = book.setTitles();
/*DEBUG
JOptionPane.showMessageDialog(null, titles[0] + titles[1] + titles[2] + titles[3] + titles[4] + titles[5], "Work", JOptionPane.PLAIN_MESSAGE);
*/
editPopUp = new JButton("Edit Player");
newPlayer = new Button("Add Player");
editPlayer = new Button("Edit Player");
editTeams = new Button("Edit Teams");
commitMatch = new Button("Commit Match");
downloadBook = new Button("Download Excel File");
setLayout(null);
//editPopUp.setBounds(0,0,BUTTON_WIDTH,BUTTON_HEIGHT);
newPlayer.setBounds(75, 180, BUTTON_WIDTH, BUTTON_HEIGHT);
editPlayer.setBounds(235, 180, BUTTON_WIDTH, BUTTON_HEIGHT);
editTeams.setBounds(395, 180, BUTTON_WIDTH, BUTTON_HEIGHT);
commitMatch.setBounds(555, 180, BUTTON_WIDTH, BUTTON_HEIGHT);
panel.add(editPopUp);
newPlayer.addActionListener(lForAction);
editPlayer.addActionListener(lForAction);
editPopUp.addActionListener(lForAction);
initPlayers(book.getRows());
//System.out.println(pList[4].getName());
tables = new JComponent[]{
new JScrollPane(playerTable = new JTable(new MyTableModel(pList))),
panel
};
playerTable.setAutoCreateRowSorter(true);
createSorter();
add(newPlayer);
add(editPlayer);
add(editTeams);
add(commitMatch);
this.setBackground(Color.BLACK);
this.setVisible(true);
}
public void start() {
}
public void destroy() {
}
public void stop() {
}
public void paint(Graphics g){
}
public void run() {
this.setVisible(true);
}
/*****************************Initialize Players*************************************
* This function calls for a read in of all players and data listed
* inside of an excel spreadsheet. The players are added to an Array
* List for easy access and dynamic storage capabilities. *
/************************************************************************************/
public void initPlayers(int i){
for(int x = 0; x < (i-1); x++){
//System.out.println("Made it Here");
pList.add(book.setPlayer((x+1)));
/*DEBUG
JOptionPane.showMessageDialog(null, pList[x].getName());
*/
}
playerCounter = (book.getRows()-1);
}
/***************************************************************************************
* This function defines an Action Listener for defining button activity
* The buttons all refer to this listener to create their functionality
***************************************************************************************/
public class ListenForAction implements ActionListener{
String S;
int active = 0;
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newPlayer){
S = JOptionPane.showInputDialog(null, inputs, "Add New Player", JOptionPane.PLAIN_MESSAGE);
if (S != null){
addPlayer(S);
}
/*DEBUG
JOptionPane.showMessageDialog(null, pList[playerCounter - 1].getName());
pList[0].setElo(2300);
pList[0].calculateElo(6, "LOSE");
JOptionPane.showMessageDialog(null, pList[0].getElo());
*/
} else if (e.getSource() == editPlayer){
JOptionPane.showOptionDialog(null, tables, "Edit Player Info", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);
} else if (e.getSource() == editPopUp){
if (active == 0) {
editPopUp.setText("Stop Editing");
testRow = playerTable.getSelectedRow();
active = 1;
} else {
editPopUp.setText("Edit Player");
testRow = 1000000;
active = 0;
}
}
}
}
/************************************************************************************
* Custom Table Model to allow for a list of editable size and data
* The players are stored read into this via the Array List and the
* Data is displayed in a list that can be sorted by column.
*************************************************************************************/
private class MyTableModel extends AbstractTableModel {
ArrayList<Player> list = null;
MyTableModel(ArrayList<Player> list) {
this.list = list;
}
public int getColumnCount() {
return titles.length;
}
public int getRowCount() {
return list.size();
}
public String getColumnName(int col) {
return titles[col];
}
public void setValueAt(Object value, int row, int col){
switch(col) {
case 0:
pList.get(row).setName((String)value);
break;
case 1:
pList.get(row).setElo((Integer)value);
break;
case 2:
pList.get(row).setAttendance((Integer)value);
break;
case 3:
pList.get(row).setMVP((Integer)value);
break;
case 4:
pList.get(row).setWins((Integer)value);
break;
case 5:
pList.get(row).setLose((Integer)value);
break;
}
System.out.println(pList.get(row).getName() + pList.get(row).getAttendance());
}
public boolean isCellEditable(int row, int column)
{
//System.out.println(Flag);
if(testRow == playerTable.getSelectedRow()){
return true;
} else {
return false;
}
}
public Object getValueAt(int row, int col) {
Player object = list.get(row);
switch (col) {
case 0:
return object.getName();
case 1:
return object.getElo();
case 2:
return object.getAttendance();
case 3:
return object.getMVP();
case 4:
return object.getWin();
case 5:
return object.getLose();
default:
return "unknown";
}
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
}
private void addPlayer(String S){
pList.add(new Player(S));
tables = new JComponent[]{
new JScrollPane(playerTable = new JTable(new MyTableModel(pList))),
panel
};
playerCounter++;
createSorter();
}
public void createSorter(){
playerTable.setPreferredScrollableViewportSize(d);
playerTable.setAutoResizeMode(getHeight());
playerTable.setAutoCreateRowSorter(true);
sorter = (TableRowSorter<?>)playerTable.getRowSorter();
sorter.setRowFilter(new RowFilter<TableModel, Integer>(){
#Override
public boolean include(RowFilter.Entry<? extends TableModel, ? extends Integer> entry){
boolean included = true;
Object cellValue = entry.getModel().getValueAt(entry.getIdentifier(), 0);
if(cellValue == null || cellValue.toString().trim().isEmpty()){
included = false;
}
return included;
}
});
}
}
.
public class Player {
private String Name;
private int Elo = 1600, Attendance = 0, MVP = 0, Win = 0, Lose = 0;
public Player(String n, int e, int a, int m, int w, int l){
Name = n;
Elo = e;
Attendance = a;
MVP = m;
Win = w;
Lose = l;
}
public Player(String n){
Name = n;
}
public Player() {
}
/***********************************************/
public void setName(String n){
Name = n;
}
public void setElo(int e){
Elo = e;
}
public void setAttendance(int a){
Attendance = a;
}
public void setMVP(int m){
MVP = m;
}
public void setWins(int w){
Win = w;
}
public void setLose(int l){
Lose = l;
}
/************************************************/
public void addAttendance(int e){
Attendance += e;
}
public void addElo(int e){
Elo += e;
}
public void addMVP(int e){
MVP += e;
}
public void addWins(int e){
Win += e;
}
public void addLose(int e){
Lose += e;
}
/************************************************/
public void calculateElo(int oE, String win){
double tRatingP; //holds the players transformed Elo Rating for calculation
double tRatingO; //holds the opponents transformed Elo Rating for calculation
double expectedP; //Players expected score
double pointP = 0;
int eloValue = 32; //default elo value
if (Elo > 2400){
eloValue = 24;
}
switch(win){
case "WIN": pointP = 1;
break;
case "DRAW": pointP = 0.5;
break;
case "LOSE": pointP = 0;
break;
}
tRatingP = 10^(Elo/400);
tRatingO = 10^(oE/400);
expectedP = tRatingP/(tRatingP+tRatingO);
this.setElo((int)Math.round(Elo + (eloValue*(pointP-expectedP))));
}
/************************************************/
public String getName(){
return Name;
}
public int getElo(){
return Elo;
}
public int getAttendance(){
return Attendance;
}
public int getMVP(){
return MVP;
}
public int getWin(){
return Win;
}
public int getLose(){
return Lose;
}
}
.
import java.io.File;
import java.util.Date;
import jxl.*;
import jxl.write.*;
public class modifyExcel {
private Player pHolder;
private String[] tHolder = new String[6];
private Workbook eloBook;
Sheet sheet;
public void openExcel(){
try {
eloBook = Workbook.getWorkbook(new File("./eloSpreadsheet.xls"));
} catch(Exception e){
throw new Error(e);
}
sheet = eloBook.getSheet(0);
}
public void appendExcel(Player p){
}
public String[] setTitles(){
for(int x = 0; x<=5; x++){
tHolder[x] = sheet.getCell(x, 0).getContents();
}
return(tHolder);
}
public Player setPlayer(int i){
//System.out.println("Made it Here " + i);
pHolder = new Player();
pHolder.setName(sheet.getCell(0, i).getContents());
pHolder.setElo(Integer.parseInt(sheet.getCell(1, i).getContents()));
pHolder.setAttendance(Integer.parseInt(sheet.getCell(2, i).getContents()));
pHolder.setMVP(Integer.parseInt(sheet.getCell(3, i).getContents()));
pHolder.setWins(Integer.parseInt(sheet.getCell(4, i).getContents()));
pHolder.setLose(Integer.parseInt(sheet.getCell(5, i).getContents()));
return(pHolder);
}
public int getRows(){
return(sheet.getRows());
}
}
For further information, I cannot even get the java console to appear which I assume means the applet is not loading at all.
You have incorrect ending of "embed" tag. It should be:
</embed>
instead:
</applet>

using Adjacency list structure for directed graph java

I have problem to implement the transpose of a graph using only Adjacency List, without Edge List. Every vertex of the graph has a positional list that stores adjacent vertexes. When you have to transpose the graph, every element stored in a list of a vertex A, has to be removed and used as a source vertex. So if we have the situation
A -> B
B after its removal, add to its own adjacent list the old source Vertex A
We have as result:
B -> A
when I update the lists, i override the last information stored in, so I lose connection between vertexes.
public class Vertice implements Comparable<Vertice>{
public Vertice(int valore){
this.valore = valore;
this.color = Color.WHITE;
this.distanza = 0;
this.padre = null;
adiacenze = new NodePositionList<Vertice>();
}
public int getValore() {
return valore;
}
public void setValore(int valore) {
this.valore = valore;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Position<Vertice> getPadre() {
return padre;
}
public void setPadre(Position<Vertice> padre) {
this.padre = padre;
}
public int getDistanza() {
return distanza;
}
public void setDistanza(int distanza) {
this.distanza = distanza;
}
public enum Color{
BLACK, WHITE, GREY;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("v_" + valore );
return sb.toString();
}
public boolean equals(Vertice v){
return this.compareTo(v) == 0;
}
#Override
public int compareTo(Vertice o) {
return this.valore - o.getValore();
}
public int getFin() {
return fin;
}
public void setFin(int fin) {
this.fin = fin;
}
public Position<Vertice> getRiferimentoVertice() {
return riferimentoVertice;
}
public void setRiferimentoVertice(Position<Vertice> riferimentoVertice) {
this.riferimentoVertice = riferimentoVertice;
}
public Iterable<Vertice> getAdiacenze() {
return adiacenze;
}
public void setAdiacenze(NodePositionList<Vertice> adiacenze) {
this.adiacenze = adiacenze;
}
public Position<Vertice> addNodoAdiacente(Vertice v){
Position<Vertice> newVertice = adiacenze.addLast(v);
v.setRiferimentoAsAdiacenza(newVertice);
return newVertice;
}
public Position<Vertice> removeNodoAdiacente(Position<Vertice> v){
return adiacenze.remove(v);
}
public Position<Vertice> getRiferimentoAsAdiacenza() {
return riferimentoAsAdiacenza;
}
public void setRiferimentoAsAdiacenza(Position<Vertice> riferimentoAsAdiacenza) {
this.riferimentoAsAdiacenza = riferimentoAsAdiacenza;
}
public boolean hasAdiacent(){
return adiacenze.size() == 0;
}
public boolean hasRedEdge(){
return redEdge;
}
public void setHasRedEdge(boolean redEdge){
this.redEdge = redEdge;
}
private boolean redEdge;
private int valore;
private Color color;
private Position<Vertice> padre;
private int distanza;
private int fin;
private Position<Vertice> riferimentoVertice;
private Position<Vertice> riferimentoAsAdiacenza;
private NodePositionList<Vertice> adiacenze;
here the "Grafo.java" class
public class Grafo {
public Grafo(int numV){
verticiGrafo = new NodePositionList<Vertice>();
listaArchi = new NodePositionList<Arco>();
this.V = numV;
}
public Position<Vertice> addVertice(Vertice v){
Position<Vertice> newAdded = verticiGrafo.addLast(v);
v.setRiferimentoVertice(newAdded);
return newAdded;
}
public NodePositionList<Vertice> getVertici(){
return verticiGrafo;
}
public Position<Arco> addArco(Arco a){
a.getSorgente().element().addNodoAdiacente(a.getDestinazione().element());
Position<Arco> newAdded = listaArchi.addLast(a);
a.setRiferimentoArco(newAdded);
return newAdded;
}
public Position<Arco> connect(Position<Vertice> sorgente, Position<Vertice> destinazione){
Arco a = new Arco(sorgente, destinazione);
Vertice v_sorgente = sorgente.element();
Vertice v_destinazione = destinazione.element();
v_sorgente.addNodoAdiacente(v_destinazione);
Position<Arco> newAdded = listaArchi.addLast(a);
a.setRiferimentoArco(newAdded);
return newAdded;
}
public Position<Arco> removeArco(Position<Arco> a){
a.element().getSorgente().element().removeNodoAdiacente(a.element().getDestinazione());
return listaArchi.remove(a);
}
public Iterable<Arco> archi(){
return listaArchi;
}
public void invertiArco(Position<Arco> a){
Arco a1 = a.element();
Position<Vertice> temp = a1.getDestinazione();
a1.setDestinazione(a1.getSorgente());
a1.setSorgente(temp);
Vertice sorgente = a1.getSorgente().element();
Vertice destinatario = a1.getDestinazione().element();
sorgente.addNodoAdiacente(destinatario);
}
public Position<Arco> getArcoByVertici(Position<Vertice> sorgente, Position<Vertice> destinazione){
for(Arco a: listaArchi){
if(a.getColor() == EdgeColor.NONE){
Vertice dest = a.getDestinazione().element();
Vertice sorg = a.getSorgente().element();
if(sorg.equals(sorgente.element()) && dest.equals(destinazione.element())){
return a.getRiferimentoArco();
}
}
}
return null;
}
public void removeAllAdiacenze(){
for(Vertice v: this.getVertici()){
v.setAdiacenze( new NodePositionList<Vertice>());
}
}
public void setColorArco(Position<Arco> a, EdgeColor ec){
a.element().setColor(ec);
}
public NodePositionList<Arco> getListaArchi() {
return listaArchi;
}
public void setListaArchi(NodePositionList<Arco> listaArchi) {
this.listaArchi = listaArchi;
}
private NodePositionList<Vertice> verticiGrafo;
private NodePositionList<Arco> listaArchi; //lista archi uscenti
public final int V;
}
here the method on the "Ricerca.java" class that I'm trying to make
public static Grafo traspostaGrafo(Grafo g){
NodePositionList<Vertice> npl = g.getVertici();
Position<Vertice> u = npl.first();
while (u != npl.getTail()){
u.element().setColor(Color.WHITE);
NodePositionList<Vertice> adiacenti = g.getListaAdiacenti(u.element().getValore());
Position<Vertice> adiacente = adiacenti.first();
while (adiacente != adiacenti.getTail() && adiacente.element().getFlag() == 0){
g.addNodoAdiacente(adiacente.element(), u.element());
g.removeNodoAdiacente(adiacente);
adiacente = adiacenti.next(adiacente);
u.element().setFlag(1);
}
}
return g
}

Moving two things with WASD and arrow keys

Here is my code and I am trying to get this cat to move with a, s, w, d and this box to move with the arrow keys. I was using switch case statements and the box works, but not the cat. I am new to programming and I really need help. Do I need to use key bindings instead?:
public class Other extends Applet implements ActionListener, KeyListener {
public static final int MOVE_STOP = 0;
public static final int MOVE_UP = 1;
public static final int MOVE_DOWN = 2;
public static final int MOVE_RIGHT = 3;
public static final int MOVE_LEFT = 4;
public static final int MOVE_W = 5;
public static final int MOVE_S = 6;
public static final int MOVE_D = 7;
public static final int MOVE_A = 8;
int CursorDirection = MOVE_STOP;
int cursordirection = MOVE_STOP;
private ArrayList<Integer> keysDown;
public void init()
{
this.addKeyListener(this);
keysDown = new ArrayList<Integer>();
rect = new Rectangle(1000, 715, 35, 35);
}
public void paint(Graphics g){
setSize(2000, 2000);
this.CalculateMappyPosition();
//i edited the background out
}
#Override
public void keyPressed(KeyEvent e) {
if (!keysDown.contains(e.getKeyCode()))
keysDown.add(new Integer(e.getKeyCode()));
moveRect();
}
#Override
public void keyReleased(KeyEvent e) {
keysDown.remove(new Integer(e.getKeyCode()));
}
public void CalculateMappyPosition() {
switch (CursorDirection) {
case MOVE_UP:
rect.y-= 100;
break;
case MOVE_DOWN:
rect.y+= 100;
break;
case MOVE_LEFT:
rect.x-= 5;
break;
case MOVE_RIGHT:
rect.x+= 5;
break;
case MOVE_A:
cat.x1-= 5;
break;
case MOVE_S:
cat.y1+= 100;
break;
case MOVE_D:
cat.x1+= 5;
break;
case MOVE_W:
cat.y1-= 100;
break;
default:
break;
}
}
public void moveRect()
{
repaint();
if(keysDown.contains(KeyEvent.VK_UP))
up();
}
if (keysDown.contains(KeyEvent.VK_DOWN))
down();
}
if(keysDown.contains(KeyEvent.VK_LEFT))
left();
}
if(keysDown.contains(KeyEvent.VK_RIGHT))
right();
}
if(keysDown.contains(KeyEvent.VK_A)){
a();
}
if(keysDown.contains(KeyEvent.VK_S)){
s();
}
if(keysDown.contains(KeyEvent.VK_D)){
}
if(keysDown.contains(KeyEvent.VK_W)){
w();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
public void up(){
CursorDirection = MOVE_UP;
}
public void down(){
CursorDirection = MOVE_DOWN;
}
public void left(){
CursorDirection = MOVE_LEFT;
}
public void right(){
CursorDirection = MOVE_RIGHT;
}
public void a(){
CursorDirection = MOVE_A;
}
public void s(){
CursorDirection = MOVE_S;
}
public void d(){
CursorDirection = MOVE_D;
}
public void w(){
CursorDirection = MOVE_W;
}
}

TicTacToe game, no output

In this code I want to create a 3x3 board game, but nothing appears on the screen..(code compiles correctly but doesn't show output)
I think the problem is in the main method... Can't figure it out... Please help!
package games;
import games.board.*;
public class BoardGameTester {
/**
* #param args
*/
private static Board gb;
public static void main(String[] args) {
// TODO Auto-generated method stub
gb = new Board(3, 3);
}
}
Here is a board.java:
package games.board;
public class Board {
private Cell[][] cells;
public Board(int rows, int columns) {
cells = new Cell[rows][columns];
for( int r = 0; r < cells[0].length; r++ ) {
for (int c = 0; c < cells[1].length; c++) {
cells[r][c] = new Cell(r,c);
}
}
}
public void setCell(Mark mark, int row, int column) throws
IllegalArgumentException {
if (cells[row][column].getContent() == Mark.EMPTY)
cells[row][column].setContent(mark);
else throw new IllegalArgumentException("Player already there!");
}
public Cell getCell(int row, int column) {
return cells[row][column];
}
public String toString() {
StringBuilder str = new StringBuilder();
for( int r = 0; r < cells.length; r++ ) {
str.append("|");
for (int c = 0; c < cells[r].length; c++) {
switch(cells[r][c].getContent()) {
case NOUGHT:
str.append("O");
break;
case CROSS:
str.append("X");
break;
case YELLOW:
str.append("Y");
break;
case RED:
str.append("R");
break;
case BLUE:
str.append("B");
break;
case GREEN:
str.append("G");
break;
case MAGENTA:
str.append("M");
break;
case ORANGE:
str.append("M");
break;
default: //Empty
str.append("");
}
str.append("|");
}
str.append("\n");
}
return str.toString();
}
}
Here is a cell.java
package games.board;
public class Cell {
private Mark content;
private int row, column;
public Cell(int row, int column) {
this.row = row;
this.column = column;
content = Mark.EMPTY;
}
public Mark getContent() { return content; }
public void setContent(Mark content) { this.content = content; }
public int getRow() { return row; }
public int getColumn() { return column; }
}
Here is mark.java
package games.board;
public enum Mark {
EMPTY, NOUGHT, CROSS, YELLOW, RED, BLUE, GREEN, MAGENTA, ORANGE
}
Here is outcome.java
package games.board;
public enum Outcome {
PLAYER1_WIN, PLAYER2_WIN, CONTINUE, TIE
}
here is player.java
package games.board;
public enum Player {
FIRST,SECOND
}
you are not genereting any output
to print the board to the console try:
public static void main(String[] args) {
// TODO Auto-generated method stub
gb = new Board(3, 3);
System.out.println(gb);
}
it will invoke the gb.toString() methode
ps: it's maybe easier to read if you use str.append("\n") instead of str.append("|")
Try this :
public static void main(String[] args) {
// TODO Auto-generated method stub
gb = new Board(3, 3);
System.out.println(gb.toString());
}

Categories