Event listener/ Scanner in Gridworld - java

I'm trying to control Bugs in GridWorld. I have tried two ways of doing this, neither of which have actually moved or turned the bug. They both compile but nothing happens.
Here is the Bug that will be controlled:
package info.gridworld.actor;
import info.gridworld.grid.*;
import info.gridworld.grid.Location;
import java.awt.Color;
public class MazeBug extends Bug {
public MazeBug() {
super(Color.blue);
}
public void forward(){
Grid<Actor> gr = getGrid();
if (gr == null)
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
public void turnRight(){
setDirection(getDirection() + Location.RIGHT);
}
public void turnLeft(){
setDirection(getDirection() + Location.LEFT);
}
}
Here is the first way that I tried controlling the bugs with the keys W,A, and D using Scanner (not sure if I used scanner correctly)
package info.gridworld.actor;
import java.util.Scanner;
import info.gridworld.grid.*;
public class KeyTests extends Actor
{
public static ActorWorld world = new ActorWorld(new BoundedGrid<Actor>(20, 20));
public static MazeBug currentBug;
public static void main(String[] args) {
world.show();
world.add(new Location(1,11),new MazeBug());
while(true){
Scanner k = new Scanner(System.in);
String buttonpress = k.nextLine();
if (buttonpress.equals("w"))
currentBug.forward();
if (buttonpress.equals("d"))
currentBug.turnRight();
if (buttonpress.equals("a"))
currentBug.turnLeft();
}
}
}
Here is the 2nd way I tried to control the bug
package info.gridworld.actor;
import info.gridworld.grid.*;
public class KeyTests extends Actor
{
public static ActorWorld world = new ActorWorld(new BoundedGrid<Actor>(20, 20));
public static MazeBug currentBug;
public static void main(String[] args) {
world.add(new Location(1,11),new MazeBug());
java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new java.awt.KeyEventDispatcher() {
public boolean dispatchKeyEvent(java.awt.event.KeyEvent event) {
String key = javax.swing.KeyStroke.getKeyStrokeForEvent(event).toString();
if (key.equals("w"))
currentBug.forward();
if (key.equals("d"))
currentBug.turnRight();
if (key.equals("a"))
currentBug.turnLeft();
world.show();
return true;
}
});
world.show();
}
}
Thanks for any help in advanced

I am almost positive that your problem is that you put your controlling code in the Runner instead of your Bug's act method.
When GridWorld steps all it does is call each Actor's act method, so if your Actor has an unpopulated method it will just call the parent, or do nothing. Your runner, since it is not an 'Actor' has no act method, and after the first run is never looked at again.
Try this in your MazeBug:
public void act()
{
java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new java.awt.KeyEventDispatcher() {
public boolean dispatchKeyEvent(java.awt.event.KeyEvent event) {
String key = javax.swing.KeyStroke.getKeyStrokeForEvent(event).toString();
if (key.equals("w"))
forward();
if (key.equals("d"))
turnRight();
if (key.equals("a"))
turnLeft();
return true;
}
});
}
Note: I have never used EventListeners so can't help with that code.

Related

problem regarding my discord bot coded through jda

My bot is stuck printing the output. I check and there was no problem with the logical part as I used the sane logic to make a normal java program. Please help as it is stuck printing the output in discord and I do not know how to solve it.
I also added some unnecessary print functions to find out where the error was. To my surprise, it was just in printing the message which is unusual as I have made bots before and none of them had any errors to just "print" messages.
import javax.security.auth.login.LoginException;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
public class rpsidnfp {
public static JDA jda;
public static void main(String args[]) throws LoginException {
jda = JDABuilder.createDefault("(my token here)").build();
core2 core2obj = new core2();
jda.addEventListener(core2obj);
}
}
The former was my main class.
And below is the core class as it contains all the functions.
package pack.rpsidnfp;
import java.util.Random;
//import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class core2 extends ListenerAdapter {
public static String prefix = "!";
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
String input = event.getMessage().getContentRaw();
String[] options = {"rock", "paper", "scissors"};
Random robj = new Random();
int rnum = robj.nextInt(options.length);
System.out.println(rnum);
String conf = options[rnum];
event.getChannel().sendMessage(conf);
System.out.println(conf);
String same = prefix + conf;
String win = "congrats, you won!";
String lose = "lmao, you lost";
if(input.equals(same)) {
event.getChannel().sendMessage("we both kept the same thing");
}
else if(input.equals(prefix + options[0])) {
if(conf.equals(options[1])) {
event.getChannel().sendMessage(lose);
}
else if(conf.equals(prefix + options[2])) {
event.getChannel().sendMessage(win);
}
}
else if(input.equals(prefix + options[1])) {
if(conf.equals(options[0])) {
event.getChannel().sendMessage(win);
}
else if(conf.equals(options[2])) {
event.getChannel().sendMessage(lose);
}
}
else if(input.equals(prefix + options[2])) {
if(conf.equals(options[0])) {
event.getChannel().sendMessage(lose);
}
else if(conf.equals(options[2])) {
event.getChannel().sendMessage(win);
}
}
}
}
The sendMessage method returns a MessageAction. You need to call queue() on that RestAction instance.
Additionally, keep in mind that your bot receives its own messages so you should make sure it ignores those. You can add a if (event.getAuthor().isBot()) return; to the start of your listener method.
See Also:
Troubleshooting Guide: Nothing happens when using X
RestAction Guide
MessageListenerExample
JDA README

Java - Use main method of a package in another class

Let's say I have a package called com.Gazzali and inside this package I've 3 another classes.
package com.Gazzali;
//Driver class
public class Main {
public static void main(String[] args) {
System.out.println("Hey There !");
FireCall target = new FireCall(); // calls 2nd class (named: Firecall)
target.callfired();
}
}
2nd class:
package com.Gazzali;
public class FireCall {
public void callfired()
{
System.out.println("Calling function Triggered.");
Execute Fire = new Execute(); //calls 3rd class (named : Execution).
if(Fire.click() == 1)
System.out.println("You're Dead, Boy !!!");
else
System.out.println("Whoooss Saved !!!");
}
}
3rd class:
package com.Gazzali;
import java.util.Scanner;
public class Execute {
int choice;
Scanner query = new Scanner(System.in);
public int click()
{
System.out.println("Enter a choice : ");
choice = query.nextInt();
if(choice % 2 == 0)
{
return 1;
}
else
return 0;
}
}
these 3 comprises my com.Gazzali package. Now in another file (RunPackTest.java) I want to call the main method of Main class (Driver class). So I tried importing like below:
import com.Gazzali.Main;
public class RunPackTest {
public static void main(String[] args) {
Main run = new Main(); //calling Main method of Driver class of the package
System.out.println(run); //Doesn't seem to work,IDE only return 0
}
}
How to do this? beacuse the main method of Main class starts the program and calls another classess of the package accordingly.
I believe this would do it:
import com.Gazzali.Main;
public class RunPackTest {
public static void main(String[] args) {
Main.main(null);
}
}
You can call main just like any other method, although it's not good practice in general.

Coding Issue with Java game

I'm writing some code for a text based game for my Computer Science class, but I'm having some problems with this code
(java code).
The all the code works until I put in the if/else statements, so I want to know where I should be putting the statements at.
(Error Message)
Code:
import java.util.Scanner;
import java.util.ArrayList;
class Progress {
public String udc;
public String u = "up";
public String d = "down";
public void start() {
System.out.println("Hello.");
}
public void c1() {
Scanner name=new Scanner(System.in);
System.out.println("What's your name?");
System.out.println("Hello "+name.nextLine()+".");
}
public void uod() {
Scanner ud = new Scanner(System.in);
System.out.println("Up or down?");
udc = ud.nextLine();
}
public void uodc() {
System.out.println("going "+udc+".");
}
public void end() {
System.out.println("Press any key to exit");
}
}
public class APGame {
public static void main(String[] args) {
Progress p =new Progress();
p.start();
p.c1();
p.uod();
if (u.equals(udc)) {p.uodc();}
else {p.oud();}
p.end();
}}
u and udc variables are defined inside another class, that is Progress, and should be accessed (as they are public), by p.u and p.udc.
if (p.u.equals(p.udc)) ...
udc and u are instance variables of the class Progress. So the problem with the if-else statement is that you are not referencing udc from any object of the Progress class. To fix it do:
if(p.u.equals(p.udc) {
p.uodc();
}else{
p.uod();
}

How to set a value on a class using another class that is called/set in main class

I have 3 classes, say: ShareType, ShareTypesTrue and Main.
public class ShareType {
public String shareTypeName = "";
public String noOfShare = "";
public String parValue = "";
public void setShareTypeName(String shareTypeName) {
this.shareTypeName = shareTypeName;
}
public void setNoOfShare(String noOfShare) {
this.noOfShare = noOfShare;
}
public void setParValue(String parValue) {
this.parValue = parValue;
}
}
public class ShareTypesTrue {
public List<ShareType> shareType;
public void setShareType(List<ShareType> shareType) {
this.shareType = shareType;
}
}
public class Main {
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
sharetypetrue.add(shareTypeName);
}
Now my problem is i need to set shareTypeName to a value under the class ShareTypesTrue. Meaning i have to use ShareTypesTrue to call on the Sharetype class and set the shareTypeName.
Anyone has an idea?
NOTE: I cant change/add code in the first 2 classes except in main. i just need to find a way to get around this.
Thanks Alot
Please check below code for Main class.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String args[]){
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
//Create object
ShareType shareType = new ShareType();
shareType.setShareTypeName("Original Name");
//Create list
List<ShareType> shareTypes=new ArrayList<ShareType>();
shareTypes.add(shareType);
//Attach it to share
sharetypetrue.setShareType(shareTypes);
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
//Editing it.
for(ShareType shareTypesMember:sharetypetrue.shareType){
shareTypesMember.shareTypeName = "Updated Name";
}
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
}
}
Use Sharetype class to set the shareTypeName
ShareType share = new ShareType();
share.setShareTypeName("name");
share.setNoOfShare("no");
share.setParValue("val");
List<ShareType> shareType = new ArrayList<ShareType>();
shareType.add(share);
use ShareTypesTrue to set Sharetype
ShareTypesTrue sharetrue = new ShareTypesTrue();
sharetrue.setShareType(shareType);//pass ShareType as list
If you want to set the 'name' in ShareType, what prevents you from doing the below:
class ShareTypeTrue_Extended extends ShareTypeTrue{
protected shareTypeName;
public ShareTypeTrue_Extended(String shareTypeName){this.shareTypeName=shareTypeName;}
public void setShareType(List<ShareType> shareType) {
for(ShareType s: shareType)s.setShareTypeName(this.shareTypeName);
super.setShareType(shareType);
}
}

Using an external class for handling bar code scanner input?

I'm building a basic Point of Sale application and I've been looking for ways of having my main POS JFrame listen for bar code input. I found this code (slightly modified) posted by Cyrusmith, which looks like what I want but I don't know how to implement it in my JFrame. It looks like its intended to be a separate class, which is how I have it in my project currently. I asked my coworker and he doesn't know either.
Thanks for your help.
package barcode;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Listens for bar code input and puts it into a String Buffer.
*
*/
public class BarcodeReader {
private static final long THRESHOLD = 100;
private static final int MIN_BARCODE_LENGTH = 8;
public interface BarcodeListener {
void onBarcodeRead(String barcode);
}
private final StringBuffer barcode = new StringBuffer();
private final List<BarcodeListener> listeners = new CopyOnWriteArrayList<>();
private long lastEventTimeStamp = 0L;
public BarcodeReader() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
#Override
public boolean dispatchKeyEvent(KeyEvent e) {
try {
if (e.getID() != KeyEvent.KEY_RELEASED) {
return false;
}
if (e.getWhen() - lastEventTimeStamp > THRESHOLD) {
barcode.delete(0, barcode.length());
}
lastEventTimeStamp = e.getWhen();
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if (barcode.length() >= MIN_BARCODE_LENGTH) {
fireBarcode(barcode.toString());
}
barcode.delete(0, barcode.length());
} else {
barcode.append(e.getKeyChar());
}
return false;
} catch (UnsupportedOperationException err) {
throw new UnsupportedOperationException(err); //To change body of generated methods, choose Tools | Templates.
}
}
});
}
protected void fireBarcode(String barcode) {
for (BarcodeListener listener : listeners) {
listener.onBarcodeRead(barcode);
}
}
public void addBarcodeListener(BarcodeListener listener) {
listeners.add(listener);
}
public void removeBarcodeListener(BarcodeListener listener) {
listeners.remove(listener);
}
}
Most bar code readers basically inject the codes directly into the keyboard buffer. So if you had a JTextField which had keyboard focus, the resulting text would be "entered" directly into it...no magic involved.
If you "want" to use this reader, then you will need to create an instance...
BarcodeReader reader = new BarcodeReader();
Register a BarcodeListener to it...
reader.addBarcodeListener(new BarcodeListener() {
public void onBarcodeRead(String barcode) {
// Respond to the event, like, I don't know,
// set the text of text field :P
}
});
But to me, this just seems like a lot of extra work - but that's just me...
So, yes, it's suppose to be a separate class. Depending on what you want to achieve, you could dump somewhere in your current code base, import the class into your source code and use it like any other. Equally, you could create a separate library for it, but this just means you need to include it within the classpath for compiling and runtime execution as well...

Categories