So I'm a little confused about how to implement this interface the right way:
A MasterMind computer player must, at a minimum, return a valid Guess:
public interface MasterMindAI
{
public Guess nextGuess();
}
MasterMindAIRandom
The simplest way to implement the interface is to populate the List of
color ids with four random integers from 1 to 7 and to return the
associated Guess. This is actually a useful class as it allows you to
find bugs related to incorporating the AI into the MasterMind game
rather than bugs in the AI itself.
So I understand everything about the list and how to populate it. I'm just confused about how to implement the interface the right way. So my MasterMindAIRandom class has to have a method called Guess nextGuess that creates a List of random numbers, yes? But the return type is of type Guess and the List is a list of ints. How exactly am I suppose to return the Guess?
From your description, we can only guess :) :
import java.util.Random;
public class MasterMindAIRandom implements MasterMindAI
{
public Guess nextGuess();
{
Random r = new Random ();
List <Integer> li = new ArrayList <> ();
for (int i = 0; i < 4; ++i)
{
li.add (r.nextInt (7) + 1);
}
return new Guess (li);
}
}
Related
I have a class called Creature and an array of Creature objects called creatures. The class Creature has an integer field called distance. I would like to sort the array creatures by their individual distance fields. I've tried several different ways but haven't gotten very far. Can someone explain to me how this works so I can figure out how to do it?
Creature [] creatures;
int [] distancearray; //I made a seperate array to try and order the
//creatures array based on this array
distancearray = new int [numcreatures];
for (int i = 0; i < numcreatures; i++) {
distancearray[i] = creatures[i].distance;
}
distancearray = sort(distancearray); //sorting this array was easy but idk how to
//sort creatures based on it
...
class Creature /*implements Comparable*/{//First attempt at Comparable
...
/*
int compareTo(Object otherObject){ //First try with Comparable
Creature otherCreature = (Creature)otherObject;
if (distance < otherCreature.distance) {
return -1;
}
if (distance > otherCreature.distance) {
return 1;
} else {
return 0;
}
}
int compare(Creature C2){ //Second try with Comparable
if (distance < C2.distance) {
return -1;
}
if (distance > C2.distance) {
return 1;
} else {
return 0;
}
}
*/
}
I sometimes get a static error, sometimes not. Am I setting the comparable up correctly? If so how do I then use it? I don't care how I get the array sorted but the easiest way would be nice. I am using Processing by the way.
These are some of the sources I've tried to use so far:
Making a generic comparator class
Java Sorting: sort an array of objects by property, object not allowed to use Comparable
How to sort an array of objects in Java?
Thanks!
The easiest way would be to use a Comparator. Assuming there is a getDistance method in your Creature class
import java.util.Arrays;
import java.util.Comparator;
//may be more of your Processing code
Creature [] creatures = //your array;
void setup() {
//sort your array here or in whatever method you want
Arrays.sort(creatures, Comparator.comparingInt(Creature::getDistance));
}
class Creature {
// your class code
}
//may be more of your Processing code
I'm having a bit of trouble in my head trying to solve this:
I'm working on a "rankList", an arrayList made of "Score". Score it's the object that has the following atributes: name,wins,loses,draws. My class Ranking has an ArrayList of Score objects. To create a new Score object I just use the name (and set the rest to 0 since it's new). However I'm trying to check if the player's name it's already in rankList I don't have to create new but sum a win or lose or draw.
I have been reading arround that I have to override equals then others say I have to override contains... It's getting a big mess in my head. My fastest solution would be to write an "for" that goes arround the arrayList and use the getName().equals("name"); however this is getting too messi in my code. I have checkPlayer (if the palyer is in the list):
public boolean checkPlayer(String playerName) {
for (int i = 0; i < this.rankList.size(); i++) {
if (this.rankList.get(i).getName().equals(playerName)) {
return true;
}
}
return false;
}
then if I want to incrase the wins i have this :
public void incraseWins(String playerName) {
if (checkPlayer(playerName)) {
for (int i = 0; i < this.rankList.size(); i++) {
if (this.rankList.get(i).getName().equals(playerName)) {
this.rankList.get(i).setWins(this.rankList.get(i).getWins() + 1);
break;
}
}
} else {
createPlayer(playerName);
//more for to get to the player i'm looking for...
for (int i = 0; i < this.rankList.size(); i++) {
if (this.rankList.get(i).getName().equals(playerName)) {
this.rankList.get(i).setWins(this.rankList.get(i).getWins() + 1);
break;
}
}
}
So i guess there is a better way to do this... :/
ArrayList is not the right data structure here. To check if an element exists in the array you are searching the entire arraylist. Which means it's O(N).
To keep an array list is sorted order and do a binary search on it would definitely be faster as suggested in the comments. But that wouldn't solve all your problems either because insert into the middle would be slow. Please see this Q&A: When to use LinkedList over ArrayList?
One suggestion is to use a Map. You would then be storing player name, player object pairs. This would give you very quick look ups. Worst case is O(log N) i believe.
It's also worth mentioning that you would probably need to make a permanent record of these scores eventually. If so an indexed RDBMS would give you much better performance and make your code a lot simpler.
Try using a hashtable with a key, it would be much more efficient!
e..Why not using map<>.
a binary search is good idea if you must use List,code like this
List<Method> a= new ArrayList<>();
//some method data add...
int index = Collections.binarySearch(a, m);
Method f = a.get(index);
and class method is impl of Comparable,then override compareTo() method
public class Method implements Comparable<Method>{
........
#Override
public int compareTo(Method o) {
return this.methodName.compareTo(o.getMethodName());
}
if you don't want use binsearch,CollectionUtils in commons can help you
CollectionUtils.find(a, new Predicate() {
#Override
public boolean evaluate(Object object) {
return ((Method)object).getMethodName().equals("aaa");
}
});
in fact CollectionUtils.find is also a 'for'
for (Iterator iter = collection.iterator(); iter.hasNext();) {
Object item = iter.next();
if (predicate.evaluate(item)) {
return item;
}
}
I'm building a Java based game in Swing, which is essentially a grid of Jbuttons
I have an Object called Cell, which is a custom JButton with additional parameters for storing objects. The game grid is represented by Cell[][]
I have an arraylist of type Cell[][] to allow me to store the state of the gamegrid after each move. If I want to undo the move, I need to copy the last element of the ArrayList to the game grid to allow it to be displayed on the UI.
My gamegrid is panelHolder and my arraylist is moveHolder.
So far I've tried Collections.copy(panelHolder, moveHolder.get(moveHolder.size())); which will not compile due to the "arguments not being applicable for the type Cell[][]"
I've also tried System.arraycopy(moveHolder.get(moveHolder.size()-1), 0, panelHolder, 0, panelHolder.length);, which throws and out of bounds exception. Initially I thought this was due to the moveHolder.size()-1, but even just as moveHolder.size() it has the same problem.
I've found numerous questions on StackOverflow and others that both show these two ways of doing it, but I can't seem to get it to work. Is there something more obvious I'm missing? Full class method below:
public class UndoClass implements MoveCommand{
public ArrayList<Cell[][]> moveHolder = new ArrayList<Cell[][]>();
public Cell[][] execute(Cell[][] panelHolder) {
if (moveHolder.size() > 0){
Collections.copy(panelHolder, moveHolder.get(moveHolder.size()));
if (moveHolder.size() > 0){
moveHolder.remove(moveHolder.size());
}
}
System.out.println("Move Undone. Undos available:" + moveHolder.size());
return panelHolder;
}
public void addMove(Cell[][] panelHolder){
moveHolder.add(panelHolder);
}
public ArrayList<Cell[][]> getMoves(){
return moveHolder;
}
}
Cell Class
public class Cell extends JButton {
int co_x = 0;
int co_y = 0;
ArrayList<Players> current = new ArrayList <Players>();
}
Just wanted to point our your execute(...) method accepts the Cell[][] both as a parameter and the return argument. That approach is going to force all of your commands to keep copying your input param arrays to the return statement array. Notice if you don't need to keep the two in sync and you just use the return arg, you don't have to worry about copying at all:
Cell[][] lastState = moveHolder.get(moveHolder.size()-1);
moveHolder.remove(moveHolder.size()-1);
return lastState; // Not updating the panelHolder array, just returning
But of course now the input parm and return are out of sync. Instead you might want to encapsulate that state into a single object to make your life easier. Something like this (note that the execute now returns a void):
public ArrayList<GameState> previousStates = new ArrayList<GameState>();
public void execute(GameState currentState) {
if (previousStates .size() > 0) {
GameState lastState = previousStates.get(previousStates.size()-1);
currentState.restoreFrom(lastState);
previousStates .remove(moveHolder.size()-1);
}
}
Good luck on the game!
if (moveHolder.size() > 0) {
for (int i = 0; i < panelHolder.length; i++) {
panelHolder[i] = moveHolder.get(moveHolder.size()-1)[i].clone();
}
moveHolder.remove(moveHolder.size()-1);
}
Try this. You need to make copies of each internal array when copying 2D arrays.
Try a Linked List
LinkedList<Cell[][]> ll = new LinkedList();
ll.removeLast();
panelHolder = ll.clone();
I am just a little bit confused as of what to do. I have Two Weapons Classes. One for the M16 and another for the M4. I then have those Classes implementing an interface named Armory. But I am having issues with the Combat class. In the combat class I have a Random number Generator that will generate a random number and depending on what number it is, will either give the player a weapon or do nothing. I will post the Code Below:
Interface:
public interface Armory {
public Integer weaponAmmo(int wepAmmo);
public Integer weaponDamage(int wepDamage);
public String weaponName(String wepName);
}
M4 Class(M4 and M16 Classes are the same except for damage and ammo amounts):
public class M4 implements Armory {
public Integer weaponAmmo(int wepAmmo) {
wepAmmo = 10;
return wepAmmo;
}
public Integer weaponDamage(int wepDamage) {
wepDamage = 2;
return wepDamage;
}
public String weaponName(String wepName) {
wepName = "M4";
return wepName;
}
And Finally, the Combat Class(This is where I am having Issues):
public class Combat {
final int chanceOfDrop = 3;
Weapons[] wepArray = {new M4(), new M16()}; //Issues here.. Don't really know how to implement this.
static boolean[] hasWeapon = {false, true};
public static int ranNumberGen(int chanceOfDrop) {
return (int) (Math.random()*1);
}
private void enemyDead() {
boolean canDrop = false;
if(ranNumberGen(chanceOfDrop)==0){
canDrop = true;
}
if(canDrop == true){
givePlayerWeapon(wepArray[Combat.ranNumberGen(wepArray.length)] } //Issues here also.
private static void givePlayerWeapon(int w) {
hasWeapon[w] = true;
for (int i = 0; i < hasWeapon.length; ++i)
{
if (hasWeapon[i]) System.out.println(( wepArray[i]).weaponName()); //And, last but not least, I am having Issues here
}
}
}
NOTE: I have a Weapons Class, But nothing is in it. I don't really know what to put in it.
Any Suggestions?
Thanks in advance:
Shandan
Several issues -
A. To put m16 and m14 elements in the weapons array , these classes must either extend (if Weapons is a class) or implmeent (if weapons is interface) Weapons.
Another option is to have a method of
Weapons toWeapons() in both M16 and M14 classes.
B. Correct me if I'm wrong (Not native english speaker - but Armory is a place that provides Weapons, so your choice of name is not good.
M16 and M14 should implement an interface named "Weapon" and this (In my humble opinion) should be the type of the array.
C. If I understood, you want to provide in some cases no weapon to the user -
One way to have this done, and not get into ugly if (to check existence or not) is to have a NoWeapon class implements Weapon (in your current code - implements Armory).
Its methods will have an applicative meaning of "do nothing".
For example -
weaponAmmo will always return 0.
I am creating a text based game and I am having some issues.. This is what I have so far. So far I have a Combat Class, and two Classes for two different Weapons. I am trying to assign hit points to the weapons themselves. But my biggest issue is in the Combat class. I am trying to create it to were there will be random weapon drops at random times and also random Weapons. So far in the Combat class I have this:
public class Combat {
final int chanceOfDrop = 3;
static Weapons[] wepArray = {new M4(), new M16()}
static boolean[] hasWeapon = {false, true};
public static int ranNumberGen(int chanceOfDrop) {
return (int) (Math.random()*1);
}
private void enemyDead() {
boolean canDrop = false;
if(ranNumberGen(chanceOfDrop)==0){
canDrop = true;
}
if(canDrop == true){
givePlayerWeapon(Weapon[Combat.ranNumberGen(Weapons.length)]);
}
private static void givePlayerWeapon(int w) {
hasWeapon[w] = true;
for w <(Weapons.length-1) {
if has weapon[w] {
System.out.println(wepArray[w].getWeaponName);
}
}
}
}
}
}
I have issues when I am creating the new M4(), and the new M16() it says Type mismatch: cannot convert form M4 to Weapons. I do have a class named Weapons, could that be the problem?
And here is my M4 Class, both M4 and M16 Classes are identical
public abstract class M4 {
private Integer weaponDamage = 5;
private Integer weaponAmmo = 25;
private String weaponName = "M4";
public M4(String name, int ammo, int damage) {
name = weaponName;
ammo = weaponAmmo;
damage = weaponDamage;
}
public String getWeaponName() {
return weaponName;
}
public Integer getAmmo() {
return weaponAmmo;
}
public Integer getDamage() {
return weaponDamage;
}
}
I don't think I have any issues here. Maybe my problem lies within this though. Although, I have a Weapons class, but nothing in it. Do I need that?
A few things to fix at first sight:
Create a generic Weapon class that defines some properties that apply to each weapon, like name, damage, ammo, scope multiplier, etc... Then create subclasses for Weapon, like M4 and M16, that specify the properties and eventually add weapon-specific properties.
Add brackets to this line:
System.out.println(wepArray[w].getWeaponName); // Change to getWeaponName()
Remove the abstract keyword from M4.
Fix the ranNumberGen method because it will always return 0 right now. Math.random() returns a float in the range [0,1[. This means that casting it to an int will always result in 0. Multiply it by n to have a random int in the range of [0, n[. You probably want this:
public static int ranNumberGen(int max) {
return (int) (Math.random() * max);
}
Change this line:
givePlayerWeapon(Weapon[Combat.ranNumberGen(Weapons.length)]);
to:
givePlayerWeapon(wepArray[Combat.ranNumberGen(wepArray.length)]);
The syntax of a for-loop is like this:
for (variable-initialization; condition; increment)
So in your case, you want:
for (int i = 0; i < hasWeapon.length; ++i)
{
if (hasWeapon[i]) System.out.println(wepArray[i].getWeaponName());
}
You might want to revisit your decision to use an inheritance-style heirarchy for game objects before it is too late.
In practice, I've found a component-entity model and/or prototype model to be much more effective. You could take a look at the code in my old Java roguelike game Tyrant for inspiration:
Weapon definitions: mikera/tyrant/Weapon.java (Github is down right now so can't find the exact link, but should be easy enough to Google)
The idea is that you make your objects by setting properties / composing compoenents in a Map-like game object rather than using static inheritance.
When you want to create a random weapon in this model, you can just get a list of all the possible weapon prototypes, and clone one of them at random to make a new weapon.
the mean of abstract in "public abstract class M4" is that you cannot make a new object with this class.
So you can put all commons fields of your weapons in the weapon class and make m4 and m16 extends the weapon and you code would compile.