"Сделка или нет" игровая приставка


Может кто-нибудь проверить этот код шахты для улучшения? Это было написана на Java с концепциями ООП.

Игра Класс

import java.util.Random;

public class Game {

    Player player = new Player();

    Banker banker = new Banker();

    private int a = 0;

    private int b = 6;

    private double myAmount = 0;

    private double offer = 0;

    private int turn = 1;

    private int cases = 26;

    private double amounts[] = { 23, 1, 5, 10, 25, 50, 75, 100,
            200, 300, 400, 500, 750, 1000, 5000, 10000, 25000, 50000, 75000,
            100000, 300000, 400000, 500000, 750000, 1000000, 250000, 800 };

    private String models[] = { "Nayer", "Michelle", "Obama", "Rosey", "Miney",
            "Ashley", "Maria", "Ozawa", "Audrey", "Kristen", "Kim",
            "Kardashian", "Kourtney", "Ann", "Macy", "Tori", "Sam", "Monica",
            "Jin", "Koi", "jill", "Usher", "Justin Bieber", "Lindsay Lohan",
            "Hazell", "Buttercup", "Don Amalia", "Kojic!" };

    Briefcase briefcase[] = new Briefcase[27];

    Model lady[] = new Model[27];

    public void setladies() {
        for (int i = 0; i < lady.length; i++) {
            lady[i] = new Model();
            String name = models[i];
            lady[i].setName(name);
        }
    }

    public void Shuffle() {

        Random rgen = new Random();
        for (int i = 0; i < amounts.length - 1; i++) {
            int Position = rgen.nextInt(amounts.length);
            double temp = amounts[i];
            amounts[i] = amounts[Position];
            amounts[Position] = temp;
        }
    }

    public void casesSetup() {
        Shuffle();
        for (int i = 0; i < briefcase.length; i++) {
            if (i == 0) {
            } else {
            }
            briefcase[i] = new Briefcase();
            double value = amounts[i];
            briefcase[i].setAmount(value);
            briefcase[i].setFace(i);
        }
    }

    public void showCases() {
        for (int a = 0; a < briefcase.length; a++) {
            if (a == 0) {
            } else if (briefcase[a] == null) {
                System.out.print("\t[X]");
            } else {
                System.out.print("\t[" + briefcase[a].getFace() + "]");
            }
            if (a % 5 == 0) {
                System.out.println();
            }
        }

        System.out.println();
    }

    public void Welcome() {
        System.out.println("\t~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*");
        System.out.println("\t~*               Welcome !          ~*");
        System.out.println("\t~*~*~*~*~* Hosted by Kyel David ~*~*~*~*~*~*");
        System.out.println("\t~* Please Select from the Following Cases!~*");
        System.out.println("\t~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*");
    }

    public void starGame() {

        boolean gamestatus = true;
        casesSetup();
        Welcome();
        showCases();
        setladies();

        int choice = player.nUser();
        myAmount = briefcase[choice].getAmount();
        briefcase[choice] = null;
        cases--;

        while (gamestatus == true) {
            showCases();
            if (cases == 25 || cases == 19 || cases == 14 || cases == 10
                    || cases == 7) {
                for (a = b; a > 0; a--) {
                    int r = player.Remove(a, briefcase, models);
                    briefcase[r] = null;
                    cases--;
                }
                b--;
                turn++;
                banker.setOffer(turn,briefcase,myAmount);
                offer = banker.getOffer(turn, briefcase, myAmount);
                gamestatus = player.gamestatus();
            } else if (cases == 1) {
                int r = player.Remove(1, briefcase, models);
                briefcase[r] = null;
                gamestatus = false;
            } else {
                int r = player.Remove(1, briefcase, models);
                briefcase[r] = null;
                cases--;
                banker.setOffer(turn,briefcase,myAmount);
                offer = banker.getOffer(turn, briefcase, myAmount);
                gamestatus = player.gamestatus();
            }
        }
        finishgame();
    }

    public void finishgame() {
        if (cases == 1) {
            System.out.println("\tYou Rejected the Offer of Banker");
            System.out
            .printf("\tYour case contains $%.2f and the bankers offer is $%.2f\n",
                    myAmount, offer);
            System.out.printf("\tYou've won your case with an amount of: %.2f",
                    myAmount);
        } else {
            System.out.println("\tYou Accepted the offer of Banker");
            System.out
            .printf("\tYour case contains $%.2f and the bankers offer is $%.2f\n",
                    myAmount, offer);
            System.out.printf("\tYou've won the offer of Banker: $%.2f", offer);
        }
    }
}

Плеер Класс

import java.util.Scanner;

public class Player {

    Scanner input = new Scanner(System.in);
    Banker banker = new Banker();

    public boolean gamestatus() {
        System.out.print("\tAccept or Reject! [1]Accept [2]reject: ");
        int temp = input.nextInt();
        System.out.println();
        if (temp == 1) {
            return false;
        } else {
            return true;
        }
    }

    public int nUser() {

        boolean isOkay = false;
        int nUser = 0;
        while (isOkay == false) {
            System.out.print("\n\tPlease Select Your Case!: ");
            nUser = input.nextInt();
            if (nUser < 0 || nUser >= 27) {
                System.out.println("\tInvalid input Try again");
            } else {
                isOkay = true;
            }
        }
        return nUser;
    }

    public int Remove(int i, Briefcase c[], String[] m) {

        int nChoice = 0;
        boolean inputisok = false;

        while (inputisok == false) {
            System.out.print("\tPlease remove " + i + " case/s: "); 
            nChoice = input.nextInt();
            if (nChoice < 0 || nChoice >= c.length || c[nChoice] == null) {
                System.out.println();
                System.out.println("\tInvalid Input please Try again\n");
            } else {
                System.out.println("\tI'm " + m[nChoice]
                        + " You just removed case # " + nChoice);
                System.out.println("\t|" + nChoice + "| contains $"
                        + c[nChoice].getAmount() + "\n");
                inputisok = true;
            }

        }
        return nChoice;
    }
}

Банкир Класса

public class Banker {

    private double total = 0;
    private int a = 0;
    private double amount =0;
    double Average = 0;

    public void setOffer(int turn, Briefcase[] cases, double myAmount) {

        for (int i = 0; i < cases.length; i++) {
            if (cases[i] == null) {
            } else {
                total = total + cases[i].getAmount();
                a++;
            }
        }
        Average = myAmount+total / a;
        amount = Average*turn/ 10;
    }

    public double getOffer(int turn, Briefcase[] cases, double myAmount) {
        setOffer(turn, cases, myAmount);
        System.out.printf("\tThe Bankers Offer is: %.2f \n\n", amount);
        return amount;
    }
}

Модель Класс

public class Model {

    private String mName;

    public void setName(String mName) {

        this.mName = mName;
    }

    public String getName() {
        return mName;
    }

}

Портфель Класса

public class Briefcase {

    private double amount;
    private int face;

    public void setAmount(double amount) {
        this.amount = amount;
    }

    public double getAmount() {

        return this.amount;
    }

    public void setFace(int face) {
        this.face = face;
    }

    public int getFace() {
        return face;
    }

}

Основной класс

public class Play {

    public static void main(String[] args) {
        Game dnd = new Game();
        dnd.starGame();
    }
}


2623
5
задан 10 сентября 2011 в 08:09 Источник Поделиться
Комментарии
1 ответ

Есть несколько вещей, я об этом со временем. Во-первых, всегда пишут способ и имена переменных в lowerCamelCase. Все, начиная с прописной буквы будет считать классом или постоянного другими программистами.

Затем, не механически использовать геттеры и сеттеры. Е. Г. рассмотрим

public class Model {

private String mName;

public void setName(String mName) {

this.mName = mName;
}

public String getName() {
return mName;
}

}

Вы когда-нибудь изменить название модели после? Нет? Это нормально, иметь модель без имени? Нет? Тогда является правильной реализации:

public class Model {

private final String mName;

public Model(String mName) {
this.mName = mName;
}

public String getName() {
return mName;
}

}

Вы можете выбрать для реализации метода toString , а не в getname, или даже сделать переменную-член Общественной (потому что это финал, и строка является неизменным).

[Некоторые Случайные Мысли]

Постарайтесь максимально упростить логические выражения:

if (temp == 1) {
return false;
} else {
return true;
}

это же так просто вернуться Temp != 1;.

Использовать функции API, где это возможно. Е. Г. есть Ява.утиль.Коллекции.перемешать в списокС.

Что с пустой {} в casesSetup и витрины?

[Предложение]

public class Banker {

private double total = 0;
private int a = 0;
private double amount =0;
double average = 0;

public void setOffer(int turn, Briefcase[] cases, double myAmount) {

for (int i = 0; i < cases.length; i++) {
if (! cases[i].isRemoved()) {
total += cases[i].getAmount();
a++;
}
}
average = myAmount + total / a;
amount = average*turn/ 10;
}

public double getOffer(int turn, Briefcase[] cases, double myAmount) {
setOffer(turn, cases, myAmount);
System.out.printf("\tThe Bankers Offer is: %.2f \n\n", amount);
return amount;
}
}

.

public class Briefcase {
private final double amount;
private final String model;
private boolean removed = false;
private String face;

public Briefcase(double amount, int face, String model) {
this.face = Integer.toString(face);
this.amount = amount;
this.model = model;
}

public double getAmount() {
return amount;
}

@Override
public String toString() {
return face;
}

public String getModel() {
return model;
}

public void remove() {
removed = true;
face = "X";
}

public boolean isRemoved() {
return removed;
}
}

.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Game {
private Player player = new Player();
private Banker banker = new Banker();
private int a = 0;
private int b = 6;
private double myAmount = 0;
private double offer = 0;
private int turn = 1;
private int cases = 26;
private Briefcase briefcases[];

public void casesSetup() {
String[] modelNames = {"Michelle", "Obama", "Rosey", "Miney",
"Ashley", "Maria", "Ozawa", "Audrey", "Kristen", "Kim",
"Kardashian", "Kourtney", "Ann", "Macy", "Tori", "Sam", "Monica",
"Jin", "Koi", "jill", "Usher", "Justin Bieber", "Lindsay Lohan",
"Hazell", "Buttercup", "Don Amalia", "Kojic!"};

List<Integer> amounts = Arrays.asList(1, 5, 10, 25, 50, 75, 100,
200, 300, 400, 500, 750, 1000, 5000, 10000, 25000, 50000, 75000,
100000, 300000, 400000, 500000, 750000, 1000000, 250000, 800);

Collections.shuffle(amounts);

briefcases = new Briefcase[amounts.size()];

for (int i = 0; i < briefcases.length; i++) {
double value = amounts.get(i);
briefcases[i] = new Briefcase(value, i + 1, modelNames[i]);
}
}

public void showCases() {
for (int i = 0; i < briefcases.length; i++) {
System.out.print("\t[" + briefcases[i] + "]");
if (i % 5 == 4) {
System.out.println();
}
}
System.out.println();
}

public void welcomeMessage() {
System.out.println("\t~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*");
System.out.println("\t~* Welcome ! ~*");
System.out.println("\t~*~*~*~*~* Hosted by Kyel David ~*~*~*~*~*~*");
System.out.println("\t~* Please Select from the Following Cases!~*");
System.out.println("\t~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*");
}

public void startGame() {

boolean gamestatus = true;
casesSetup();
welcomeMessage();
showCases();

int choice = player.nUser();
myAmount = briefcases[choice].getAmount();
briefcases[choice].remove();
cases--;

while (gamestatus == true) {
showCases();
if (cases == 25 || cases == 19 || cases == 14 || cases == 10
|| cases == 7) {
for (a = b; a > 0; a--) {
player.remove(a, briefcases);
cases--;
}
b--;
turn++;
banker.setOffer(turn, briefcases, myAmount);
offer = banker.getOffer(turn, briefcases, myAmount);
gamestatus = player.gamestatus();
} else if (cases == 1) {
player.remove(1, briefcases);
gamestatus = false;
} else {
player.remove(1, briefcases);
cases--;
banker.setOffer(turn, briefcases, myAmount);
offer = banker.getOffer(turn, briefcases, myAmount);
gamestatus = player.gamestatus();
}
}
finishgame();
}

public void finishgame() {
if (cases == 1) {
System.out.println("\tYou Rejected the Offer of Banker");
System.out.printf("\tYour case contains $%.2f and the bankers offer is $%.2f\n",
myAmount, offer);
System.out.printf("\tYou've won your case with an amount of: %.2f",
myAmount);
} else {
System.out.println("\tYou Accepted the offer of Banker");
System.out.printf("\tYour case contains $%.2f and the bankers offer is $%.2f\n",
myAmount, offer);
System.out.printf("\tYou've won the offer of Banker: $%.2f", offer);
}
}
}

.

public class Play {

public static void main(String[] args) {
Game dnd = new Game();
dnd.startGame();
}
}

.

import java.util.Scanner;

public class Player {

Scanner input = new Scanner(System.in);
Banker banker = new Banker();

public boolean gamestatus() {
System.out.print("\tAccept or Reject! [1]Accept [2]Reject: ");
int temp = input.nextInt();
System.out.println();
return temp != 1;
}

public int nUser() {
while (true) {
System.out.print("\n\tPlease Select Your Case!: ");
int nUser = input.nextInt() - 1;
if (nUser < 0 || nUser >= 26) {
System.out.println("\tInvalid input Try again");
} else {
return nUser;
}
}
}

public int remove(int index, Briefcase[] briefCases) {
while (true) {
System.out.print("\tPlease remove " + index + " case/s: ");
int nChoice = input.nextInt() - 1;
if (nChoice < 0 || nChoice >= briefCases.length || briefCases[nChoice].isRemoved()) {
System.out.println();
System.out.println("\tInvalid Input please Try again\n");
} else {
System.out.println("\tI'm " + briefCases[nChoice].getModel()
+ ". You just removed case # " + (nChoice+1));
System.out.println("\t|" + nChoice + "| contains $"
+ briefCases[nChoice].getAmount() + "\n");
briefCases[nChoice].remove();
return nChoice;
}
}
}
}

Модель ушла. Портфель является более полезным, особенно вы не должны использовать NULL значений для кодирования удален портфель. Я поменяла расклад портфель, поэтому нет более фиктивное значение. Затем я попытался упростить все немного.

Это далеко от совершенства, есть еще возможности для улучшения.

11
ответ дан 10 сентября 2011 в 10:09 Источник Поделиться