Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added reflection with factory class, bwz2 + sw258 #21

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/roulette/Factory.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package roulette;

import util.ConsoleReader;

public class Factory {

private String[] betTypes = {
"RedBlack",
"OddEven",
"ThreeConsecutive"
};

private String[] betDescriptions = {
"Red or Black",
"Odd or Even",
"Three in a Row"
};

private int[] betOdds = {
1,
1,
11
};

public Bet promptForBet() {
System.out.println("You can make one of the following types of bets:");
for (int k = 0; k < betTypes.length; k++) {
System.out.println(String.format("%d) %s", (k + 1), betDescriptions[k]));
}
int response = ConsoleReader.promptRange("Please make a choice", 1, betTypes.length);
Bet bet = null;
try {
bet = (Bet) Class.forName("roulette." + betTypes[response - 1])
.getConstructor(String.class, int.class).newInstance(betDescriptions[response - 1],
betOdds[response - 1]);
}
catch (Exception e) {
e.printStackTrace();
}
return bet;
}
}
12 changes: 1 addition & 11 deletions src/roulette/Game.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,6 @@ public class Game {
// name of the game
private static final String DEFAULT_NAME = "Roulette";
// add new bet subclasses here
private Bet[] myPossibleBets = {
new RedBlack("Red or Black", 1),
new OddEven("Odd or Even", 1),
new ThreeConsecutive("Three in a Row", 11),
};
private Wheel myWheel;

/**
Expand Down Expand Up @@ -65,11 +60,6 @@ public void play (Gambler player) {
* Prompt the user to make a bet from a menu of choices.
*/
private Bet promptForBet () {
System.out.println("You can make one of the following types of bets:");
for (int k = 0; k < myPossibleBets.length; k++) {
System.out.println(String.format("%d) %s", (k + 1), myPossibleBets[k].getDescription()));
}
int response = ConsoleReader.promptRange("Please make a choice", 1, myPossibleBets.length);
return myPossibleBets[response - 1];
return (new Factory()).promptForBet();
}
}