Here I am Trying to find the status of node but unable to resolve what error every node is just printing void - unetstack

Here i first find all the neighbours of node and then find depth of all neighbours and then send a rangereq to sink(node-1) if node directly connected to sink then node is normal or if not connected then its status is void.if its void the the node which are below to current node then they are void.i unable to figure what wrong i have done.
import org.arl.unet.*
import org.arl.unet.localization.RangeNtf
import org.arl.unet.localization.RangeReq
import org.arl.unet.net.RouteDiscoveryProtocol
import org.arl.unet.net.RouteDiscoveryReq
import org.arl.unet.net.RouteDiscoveryNtf
import org.arl.unet.UnetAgent
class status extends UnetAgent{
def router,ranging,rdp,addr,z1;
def neighbour=[];
def dep=[];
def locat=new double[3];
def status=1;
void neigh()
{
neighbour.clear();
def ntf;
int attempts = 1;
int phantom =130 ;
int timeout = 10000;
rdp << new RouteDiscoveryReq(to: phantom, count: attempts);
while (ntf = receive(RouteDiscoveryNtf, timeout)) {
neighbour << ntf.nextHop ;
}
neighbour = neighbour.unique();
log.info("Discovered Neighbours: ${neighbour} for Node-{$addr}}");
}
void Finddepth()
{
dep.clear();
def n=neighbour.size(),i=0,k;
while(i<n)
{
k=neighbour[i];
i++;
ranging << new RangeReq(to:k,requestLocation:true);
}
}
void NodefuncVoid()
{
def i=0,n=neighbour.size(),k;
while(i<n)
{
k=neighbour[i];
def z2 = dep[i];
i++;
if(z2<=z1)
{
router << new DatagramNtf(to:k,from:addr);
}
}
}
void NodefuncNormal()
{
def i=0,n=neighbour.size(),k;
while(i<n)
{
k=neighbour[i];
def z2 = dep[i];
i++;
if(z2<=z1)
{
router << new DatagramReq(to:k);
}
}
}
public void startup()
{
rdp = agentForService Services.ROUTE_MAINTENANCE;
subscribe topic(rdp);
router = agentForService Services.ROUTING;
subscribe topic(router);
ranging = agentForService Services.RANGING;
subscribe topic(ranging);
def nodeInfo = agentForService Services.NODE_INFO;
subscribe topic(nodeInfo);
addr = nodeInfo.address;
z1 = nodeInfo.location[2]
neigh();
Finddepth();
ranging << new RangeReq(to:1);
}
public void processMessage(Message msg) {
if (msg instanceof RangeNtf){
double z2;
locat = msg.getPeerLocation();
z2=locat[2];
dep << z2;
}
if (msg instanceof RangeNtf && msg.from==1 || msg instanceof DatagramReq)
{
//status is Normal
log.info("Node-{$addr} is Normal");
//send below nodes noraml
NodefuncNormal();
}
else if(msg instanceof DatagramNtf)
{
//trap node
log.info("Node-{$addr} is Trap node if it chooses Node-{$msg.from}");
}
else
{
log.info("Node-{$addr} is Void Node");
NodefuncVoid();
}
}
}

Related

Error #1009: Cannot access a property or method of a null object for loop()

I have a problem: I have tested the single pong game, and then I found an error when the game live reached 0 and moved to a Game Over screen for a single pong game.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at BlowfishPong_fla::MainTimeline/loop()
Can you check this code?
Here is my code for the single pong game:
import flash.events.MouseEvent;
import flash.utils.Dictionary;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.display.MovieClip;
import flash.text.TextField;
import flash.net.SharedObject;
import flash.events.Event;
stop();
var sound: Sound
var sound_channel: SoundChannel;
var gameMiss: Miss = new Miss();
var gameBounce: BounceWall = new BounceWall();
var gameHit: Hit = new Hit();
var ballSpeedX: int = -3;
var ballSpeedY: int = -2;
var gameScore = 0;
var gameLives = 3;
var plzStop: Boolean = false;
helpContent.visible = false;
reset_btn.addEventListener(MouseEvent.CLICK, scoreReset);
function scoreReset(event: MouseEvent): void {
gameScore = 0;
gameLives = 3;
updateTextFields();
}
pause_btn.addEventListener(MouseEvent.CLICK, goPause);
function goPause(event: MouseEvent): void {
if (plzStop == true) {
plzStop = false;
} else {
plzStop = true;
}
}
home_btn.addEventListener(MouseEvent.CLICK, goHome);
function goHome(event: MouseEvent): void {
plzStop = true;
gotoAndStop("startScreen");
}
help_btn2.addEventListener(MouseEvent.CLICK, goHelp2);
function goHelp2(event: MouseEvent): void {
if (plzStop == true) {
helpContent.visible = false;
plzStop = false;
} else {
helpContent.visible = true;
plzStop = true;
}
}
function init(): void {
score_txt.text = gameScore;
lives_txt.text = gameLives;
stage.addEventListener(Event.ENTER_FRAME, loop);
}
function updateTextFields(): void {
score_txt.text = gameScore;
lives_txt.text = gameLives;
}
function calculateBallAngle(paddleY: Number, ballY: Number): Number {
var ySpeed: Number = 5 * ((ballY - paddleY) / 25);
return ySpeed;
}
function loop(e: Event): void {
if (plzStop == false) {
characterPaddle.y = mouseY;
blowfishPong.x += ballSpeedX;
blowfishPong.y += ballSpeedY;
if (blowfishPong.x <= blowfishPong.width / 2) {
blowfishPong.x = blowfishPong.width / 2;
ballSpeedX *= -1;
gameBounce.play();
}
else if (blowfishPong.x >= stage.stageWidth - blowfishPong.width / 2) {
blowfishPong.x = stage.stageWidth - blowfishPong.width / 2;
ballSpeedX *= -1;
gameMiss.play();
gameLives--;
lives_txt.text = gameLives;
if(gameLives == 0){
stage.removeEventListener(Event.ENTER_FRAME,loop);
gotoAndStop("gameover_Single");
SoundMixer.stopAll();
}
}
if (blowfishPong.y <= blowfishPong.height / 2) {
blowfishPong.y = blowfishPong.height / 2;
ballSpeedY *= -1;
gameBounce.play();
}
else if (blowfishPong.y >= stage.stageHeight - blowfishPong.height / 2) {
blowfishPong.y = stage.stageHeight - blowfishPong.height / 2;
ballSpeedY *= -1;
gameBounce.play();
}
if (characterPaddle.y - characterPaddle.height / 3 < 0) {
characterPaddle.y = characterPaddle.height / 3;
}
else if (characterPaddle.y + characterPaddle.height / 3 > stage.stageHeight) {
characterPaddle.y = stage.stageHeight - characterPaddle.height / 3;
}
if (characterPaddle.hitTestObject(blowfishPong) == true) {
if (ballSpeedX > 0) {
ballSpeedX *= -1;
ballSpeedY = calculateBallAngle(characterPaddle.y, blowfishPong.y);
gameScore++;
updateTextFields();
gameHit.play();
}
}
}
}
init();
Then, for the PlayerSkin function, there are some errors to fix:
character.addEventListener(Event.ENTER_FRAME, playerSkin);
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at BlowfishPong_fla::MainTimeline/goHome3()[BlowfishPong_fla.MainTimeline::frame28:55]
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at BlowfishPong_fla::MainTimeline/playerSkin()[BlowfishPong_fla.MainTimeline::frame28:268]

Rubberband effect for scrolling containers

I'd like to have a rubberband effect on scrolling containers for which I feel the "tensile scrolling" that is build into the Component base class is no sufficient replacement.
Is there a reasonably feasible way like disabling the default overscroll behavior in order to control the property scrollY in a way like in this example - How to create the rubberband effect?
Since there was no answer to my question I answer it myself. Beware that I am not an expert and therefore this might not fit Your purpose!
The default overscroll behaviour can be overridden by extending the Container class and overriding the pointer methods without calling their super methods.
Here is an example:
import com.codename1.ui.Component;
import com.codename1.ui.Container;
import com.codename1.ui.Form;
import com.codename1.ui.Graphics;
import com.codename1.ui.Label;
import com.codename1.ui.animations.Motion;
import com.codename1.ui.geom.Point;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
public class FormOverscroll extends Form {
FormOverscroll() {
super("FormOverscroll");
setScrollable(false);
setLayout(new BorderLayout());
Container container = new Container(BoxLayout.y()) {
boolean bounce = false;
Motion motion = null;
Point pointPressed = null;
long millisPoint = 0;
int scrollYPressed = 0, scrollYPrevious = 0;
{
// setTensileDragEnabled(false);
setScrollableY(true);
}
#Override
protected boolean isStickyDrag() {
return true;
}
#Override
public void pointerPressed(int x, int y) {
pointPressed = new Point(x, y);
scrollYPressed = scrollYPrevious = getScrollY();
millisPoint = System.currentTimeMillis();
motion = null;
bounce = false;
}
#Override
public void pointerDragged(int x, int y) {
if (null == pointPressed) {
return;
}
int yDist = y - pointPressed.getY();
int scrollY = scrollYPressed - yDist;
if (scrollY < 0) {
Motion motionRubberband = Motion.createCubicBezierMotion(0, scrollY, getHeight(), 0f, 1.2f, 0.5f, 0.6f);
motionRubberband.setStartTime(0);
motionRubberband.setCurrentMotionTime(Math.abs(scrollY));
scrollY = motionRubberband.getValue();
}
setScrollY(scrollY);
}
float getVelocity(int scrollY) {
long millisNow = System.currentTimeMillis();
long timediff = millisNow - millisPoint;
float diff = scrollYPrevious - scrollY;
float velocity = (diff / timediff) * -1f;
scrollYPrevious = scrollY;
millisPoint = millisNow;
return velocity;
}
#Override
public void pointerReleased(int x, int y) {
if (null == pointPressed) {
return;
}
int yDist = y - pointPressed.getY();
int scrollY = scrollYPressed - yDist;
float velocity = getVelocity(scrollY);
motion = Motion.createFrictionMotion(scrollY, Integer.MIN_VALUE, velocity, 0.0007f);
motion.start();
getComponentForm().registerAnimated(this);
pointPressed = null;
}
#Override
public boolean animate() {
boolean animate = super.animate();
if (null != motion) {
int scrollY = motion.getValue();
setScrollY(scrollY);
int target = 0;
if (scrollY < target && !bounce) {
createRubberbandMotion(scrollY, target);
bounce = true;
motion.start();
}
int maxScrollY = Math.max(target, getScrollDimension().getHeight() - getHeight());
if (scrollY > maxScrollY && !bounce) {
createRubberbandMotion(scrollY, maxScrollY);
bounce = true;
motion.start();
}
scrollYPrevious = scrollY;
if (motion.isFinished()) {
motion = null;
}
return true;
}
return animate;
}
private void createRubberbandMotion(int source, int target) {
motion = Motion.createCubicBezierMotion(source, target, 500, 0.0f, 1.0f, 1.2f, 1.0f);
}
#Override
public Component getComponentAt(int x, int y) {
return this;
}
#Override
public void paint(Graphics aGraphics) {
super.paint(aGraphics);
}
};
for (int index = 0; index < 100; index++) {
container.add(new Label("Zeile " + index));
}
add(BorderLayout.CENTER, container);
}
}

Extracting text inside body of mail using javamail API stopping after first iteration

I've searched for hours and tried everything to fix this code. I've been working with the example below and after updating appropriate variables this works fine through till the end of processing the first email. It seems to pause indefinitely. I had to alter code at (//check if the content is an inline image) as variables appear to need declaration before they were used but have not changed anything apart from that. Any help before I loose my mind will be much appreciated.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Original code at https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
My code below... (output below that)
package com.mail.coder;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
public class FetchingEmail2 {
public static void fetch(String pop3Host, String storeType, String user,
String password) {
try {
// create properties field
Properties properties = new Properties();
properties.put("mail.store.protocol", "pop3");
properties.put("mail.pop3.host", pop3Host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
// emailSession.setDebug(true);
// create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect("mail.DOMAIN.com", "USERNAME#DOMAIN.com", "PASS");
// create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
writePart(message);
String line = reader.readLine();
if ("YES".equals(line)) {
message.writeTo(System.out);
} else if ("QUIT".equals(line)) {
break;
}
}
// close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username =
"abc#gmail.com";// change accordingly
String password = "*****";// change accordingly
//Call method fetch
fetch(host, mailStoreType, username, password);
}
/*
* This method checks for content-type
* based on which, it processes and
* fetches the content of the message
*/
public static void writePart(Part p) throws Exception {
if (p instanceof Message)
//Call method writeEnvelope
writeEnvelope((Message) p);
System.out.println("----------------------------");
System.out.println("CONTENT-TYPE: " + p.getContentType());
//check if the content is plain text
if (p.isMimeType("text/plain")) {
System.out.println("This is plain text");
System.out.println("---------------------------");
System.out.println((String) p.getContent());
}
//check if the content has attachment
else if (p.isMimeType("multipart/*")) {
System.out.println("This is a Multipart");
System.out.println("---------------------------");
Multipart mp = (Multipart) p.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++)
writePart(mp.getBodyPart(i));
}
//check if the content is a nested message
else if (p.isMimeType("message/rfc822")) {
System.out.println("This is a Nested Message");
System.out.println("---------------------------");
writePart((Part) p.getContent());
}
//check if the content is an inline image
else if (p.isMimeType("image/jpeg")) {
System.out.println("--------> image/jpeg");
Object o = p.getContent();
InputStream x = (InputStream) o;
// Construct the required byte array
System.out.println("x.length = " + x.available());
**int i;
byte[] bArray = new byte[x.available()];**
while ((i = (int) ((InputStream) x).available()) > 0) {
int result = (int) (((InputStream) x).read(bArray));
if (result == -1)
i = 0;
break;
}
FileOutputStream f2 = new FileOutputStream("/tmp/image.jpg");
f2.write(bArray);
}
else if (p.getContentType().contains("image/")) {
System.out.println("content type" + p.getContentType());
File f = new File("image" + new Date().getTime() + ".jpg");
DataOutputStream output = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(f)));
com.sun.mail.util.BASE64DecoderStream test =
(com.sun.mail.util.BASE64DecoderStream) p
.getContent();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = test.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
else {
Object o = p.getContent();
if (o instanceof String) {
System.out.println("This is a string");
System.out.println("---------------------------");
System.out.println((String) o);
}
else if (o instanceof InputStream) {
System.out.println("This is just an input stream");
System.out.println("---------------------------");
InputStream is = (InputStream) o;
is = (InputStream) o;
int c;
while ((c = is.read()) != -1)
System.out.write(c);
}
else {
System.out.println("This is an unknown type");
System.out.println("---------------------------");
System.out.println(o.toString());
}
}
}
/*
* This method would print FROM,TO and SUBJECT of the message
*/
public static void writeEnvelope(Message m) throws Exception {
System.out.println("This is the message envelope");
System.out.println("---------------------------");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("FROM: " + a[j].toString());
}
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("TO: " + a[j].toString());
}
// SUBJECT
if (m.getSubject() != null)
System.out.println("SUBJECT: " + m.getSubject());
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Output
messages.length---5
---------------------------------
This is the message envelope
---------------------------
FROM: Jack Frost <sender#gmail.com>
TO: recipient#domain.com
SUBJECT: another email
----------------------------
CONTENT-TYPE: multipart/alternative; boundary="000000000000096c73056991868c"
This is a Multipart
---------------------------
----------------------------
CONTENT-TYPE: text/plain; charset="UTF-8"
This is plain text
---------------------------
testing
----------------------------
CONTENT-TYPE: text/html; charset="UTF-8"
This is a string
---------------------------
<div dir="ltr">testing</div>

getSelectedIndex JComboBox

I have a school assignment to change a GUI Calculator from RadioButton to JComboBox. I have made the change but I have some issue.
The first is for some reason when I choose to calculate, it does not work
and I need it to be calculated directly after choosing option from the JComboBox.
I must use selected Index method as a part of the assignment.
Here is my code:
<code>
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
public class TaschenrechnerGUIV2 extends JFrame{
private static final long serialVersionUID = 3006212012028893840L;
private JTextField eingabe1, eingabe2;
double x, y, ergebnis = 0;
String [] option = {"addition", "subtraktion", "multiplikation", "division"};//array JList
private JComboBox <String> optionComboBox = new JComboBox <String>(option);//need to import the JComboBox
private JButton schaltflaecheBerechnen, schaltflaecheBeenden;
private JLabel ausgabe;
class MeinListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ende"))
System.exit(0);
if (e.getActionCommand().equals("rechnen"))
ausgabe.setText(berechnen());
if (e.getSource() instanceof JComboBox){
ausgabe.setText(berechnen());
}
}
}
public TaschenrechnerGUIV2(String titel) {
super(titel);
JPanel panelEinAus, panelBerechnung, panelButtons, gross;
panelEinAus = panelEinAusErzeugen();
panelBerechnung = panelBerechnungErzeugen();
panelButtons = panelButtonErzeugen();
gross = new JPanel();
gross.add(panelEinAus);
gross.add(panelBerechnung);
add(gross,BorderLayout.CENTER);
add(panelButtons, BorderLayout.EAST);
optionComboBox.setEnabled(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
private JPanel panelEinAusErzeugen() {
JPanel tempPanel = new JPanel();
eingabe1 = new JTextField(10);
eingabe2 = new JTextField(10);
ausgabe = new JLabel("");
tempPanel.setLayout(new GridLayout(0,2,10,10));
tempPanel.add(new JLabel("Zahl 1:"));
tempPanel.add(eingabe1);
tempPanel.add(new JLabel("Zahl 2: "));
tempPanel.add(eingabe2);
tempPanel.add(new JLabel("Ergebnis: "));
tempPanel.add(ausgabe);
tempPanel.setBorder(new TitledBorder("Ein- und Ausgabe"));
return tempPanel;
}
private JPanel panelBerechnungErzeugen() {
JPanel tempPanel = new JPanel();
tempPanel.add(optionComboBox);//add the JComboBox to the panel
tempPanel.setLayout(new GridLayout(0,1));
tempPanel.setBorder(new TitledBorder("Operation: "));
return tempPanel;
}
private JPanel panelButtonErzeugen() {
JPanel tempPanel = new JPanel();
schaltflaecheBeenden = new JButton(" Beenden ");
schaltflaecheBeenden.setActionCommand("ende");
schaltflaecheBerechnen = new JButton("Berechnen");
schaltflaecheBerechnen.setActionCommand("rechnen");
tempPanel.setLayout(new GridLayout(0,1));
tempPanel.add(schaltflaecheBerechnen);
tempPanel.add(new JLabel());
tempPanel.add(schaltflaecheBeenden);
MeinListener listener = new MeinListener();
schaltflaecheBeenden.addActionListener(listener);
schaltflaecheBerechnen.addActionListener(listener);
optionComboBox.addActionListener(listener);//adding a listener to the JComboBox
return tempPanel;
}
private String berechnen() {
double x, y, ergebnis = 0;
boolean fehlerFlag = false;
try {
x = Double.parseDouble(eingabe1.getText());
}
catch (Exception NumberFormatException) {
fehlermeldung(eingabe1);
return ("Nicht definiert");
}
try {
y = Double.parseDouble(eingabe2.getText());
}
catch (Exception NumberFormatException) {
fehlermeldung(eingabe2);
return ("Nicht definiert");
}
if (optionComboBox.getSelectedIndex() ==0){
ergebnis = x + y;
}
if (optionComboBox.getSelectedIndex() ==1){
ergebnis = x - y;
}
if (optionComboBox.getSelectedIndex() ==2){
ergebnis = x * y;
}
if (optionComboBox.getSelectedIndex() ==3){
if(y !=0)
ergebnis = x / y;
}
else
fehlerFlag = true;
if (fehlerFlag == false) {
DecimalFormat formatFolge = new DecimalFormat("0.##");
return (formatFolge.format(ergebnis));
}
else return ("Nicht definiert"); }
private void fehlermeldung(JTextField eingabefeld) {
JOptionPane.showMessageDialog(this, "Ihre Eingabe ist nicht gültig","Eingabefehler", JOptionPane.ERROR_MESSAGE);
eingabefeld.requestFocus();
}
public static void main (String [] arg){
new TaschenrechnerGUIV2("Taschenrechner V2"); }}
</code>
You forgot to include what the ActionListener should listen to.
zB.
object set = e.getSorce();
if(set instanceof JComboBox){
if (optionComboBox.getSelectedIndex() ==0){
ergebnis = x + y;
}
if (optionComboBox.getSelectedIndex() ==1){
ergebnis = x - y;
}
if (optionComboBox.getSelectedIndex() ==2){
ergebnis = x * y;
}
if (optionComboBox.getSelectedIndex() ==3){
if(y !=0)
ergebnis = x / y;
}
}

How do i remove the milliseconds from my timer

I am making this game for school and I am trying to add a timer to levels. I have the timer working but not the way I want it to. It refreshes and it has milliseconds. I have searched every website for an answer but I can only find with dates and times or how do display them. I need the exact opposite.
package GameState;
import Main.GamePanel;
import TileMap.*;
import Entity.*;
import Entity.Enemies.*;
import Audio.AudioPlayer;
//timer imports
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
public class Level1State extends GameState {
private TileMap tileMap;
private Background bg;
private static int cnt;
private Player player;
private ArrayList<Enemy> enemies;
private ArrayList<Explosion> explosions;
private HUD hud;
private AudioPlayer bgMusic;
public Level1State(GameStateManager gsm) {
this.gsm = gsm;
init();
}
public void init() {
tileMap = new TileMap(30);
tileMap.loadTiles("/Tilesets/grasstileset.gif");
tileMap.loadMap("/Maps/level1-1.map");
tileMap.setPosition(0, 0);
tileMap.setTween(1);
bg = new Background("/Backgrounds/grassbg1.2.jpg", 0.1);
player = new Player(tileMap);
player.setPosition(100, 100);
populateEnemies();
explosions = new ArrayList<Explosion>();
hud = new HUD(player);
bgMusic = new AudioPlayer("/Music/level1-1.mp3");
bgMusic.play();
}
private void populateEnemies() {
enemies = new ArrayList<Enemy>();
Slugger s;
Point[] points = new Point[] {
new Point(200, 100),
new Point(860, 200),
new Point(1525, 200),
new Point(1680, 200),
new Point(1800, 200)
};
for(int i = 0; i < points.length; i++) {
s = new Slugger(tileMap);
s.setPosition(points[i].x, points[i].y);
enemies.add(s);
}
}
public void update() {
// update player
player.update();
tileMap.setPosition(
GamePanel.WIDTH / 2 - player.getx(),
GamePanel.HEIGHT / 2 - player.gety()
);
// set background
bg.setPosition(tileMap.getx(), tileMap.gety());
// attack enemies
player.checkAttack(enemies);
// update all enemies
for(int i = 0; i < enemies.size(); i++) {
Enemy e = enemies.get(i);
e.update();
if(e.isDead()) {
enemies.remove(i);
i--;
explosions.add(
new Explosion(e.getx(), e.gety()));
}
}
// update explosions
for(int i = 0; i < explosions.size(); i++) {
explosions.get(i).update();
if(explosions.get(i).shouldRemove()) {
explosions.remove(i);
i--;
}
}
}
public void draw(final Graphics2D g) {
// draw bg
bg.draw(g);
// draw tilemap
tileMap.draw(g);
// draw player
player.draw(g);
// draw enemies
for(int i = 0; i < enemies.size(); i++) {
enemies.get(i).draw(g);
}
// draw explosions
for(int i = 0; i < explosions.size(); i++) {
explosions.get(i).setMapPosition(
(int)tileMap.getx(), (int)tileMap.gety());
explosions.get(i).draw(g);
}
// draw hud
hud.draw(g);
ActionListener actListner = new ActionListener() {
public void actionPerformed(ActionEvent event) {
cnt += 1;
g.drawString("Counter = "+cnt, 120, 120);
}
};
Timer timer = new Timer(1000, actListner);
timer.start();
}
public void keyPressed(int k) {
if(k == KeyEvent.VK_LEFT) player.setLeft(true);
if(k == KeyEvent.VK_RIGHT) player.setRight(true);
if(k == KeyEvent.VK_UP) player.setUp(true);
if(k == KeyEvent.VK_DOWN) player.setDown(true);
if(k == KeyEvent.VK_W) player.setJumping(true);
if(k == KeyEvent.VK_E) player.setGliding(true);
if(k == KeyEvent.VK_R) player.setScratching();
if(k == KeyEvent.VK_F) player.setFiring();
}
public void keyReleased(int k) {
if(k == KeyEvent.VK_LEFT) player.setLeft(false);
if(k == KeyEvent.VK_RIGHT) player.setRight(false);
if(k == KeyEvent.VK_UP) player.setUp(false);
if(k == KeyEvent.VK_DOWN) player.setDown(false);
if(k == KeyEvent.VK_W) player.setJumping(false);
if(k == KeyEvent.VK_E) player.setGliding(false);
}
}
this is the part i need help with:
ActionListener actListner = new ActionListener() {
public void actionPerformed(ActionEvent event) {
cnt += 1;
g.drawString("Counter = "+cnt, 120, 120);
}
};
Timer timer = new Timer(1000, actListner);
timer.start();
Can anyone help me? I just can't get it to stop refreshing and it won't remove the milliseconds either.
Thank you in advance
P.S.
I have a feeling the first second runs way slower than the others.
P.P.S.: i have looked at "how to implement timers" but none of those worked and I found this one on a website that doesn't return an error.

Resources