Это скорее ответ на python, чем ответ Flask / werkzeug; но это просто и работает.
Если, как и я, вы хотите, чтобы настройки вашего приложения (загруженные из файла .ini
) также содержали префикс вашего приложения Flask (таким образом, чтобы не устанавливать значение во время развертывания, но во время выполнения) вы можете выбрать следующее:
def prefix_route(route_function, prefix='', mask='{0}{1}'):
'''
Defines a new route function with a prefix.
The mask argument is a `format string` formatted with, in that order:
prefix, route
'''
def newroute(route, *args, **kwargs):
'''New function to prefix the route'''
return route_function(mask.format(prefix, route), *args, **kwargs)
return newroute
Возможно, это несколько хакерское и полагается на то, что функция маршрута колбы требует a route
в качестве первого позиционного аргумента.
Вы можете использовать его следующим образом:
app = Flask(__name__)
app.route = prefix_route(app.route, '/your_prefix')
NB: ничего не стоит, что можно использовать переменную в префиксе (например, установив его на /<prefix>
), а затем обработайте этот префикс в тех функциях, которые вы украшаете своим @app.route(...)
. Если вы это сделаете, вам, очевидно, нужно объявить параметр prefix
в вашей украшенной функции. Кроме того, вы можете проверить представленный префикс на некоторые правила и вернуть 404, если проверка завершилась неудачно. Чтобы избежать 404 пользовательской повторной реализации, пожалуйста, from werkzeug.exceptions import NotFound
, а затем raise NotFound()
, если проверка завершилась неудачно.
Вы не получили ответ при вводе пользователя.
Я думаю, что вы можете изменить свой метод askUser, как показано ниже.
public String askUser(boolean firstTime) {
if (firstTime == true)
System.out.println("Start Playing?");
else {
System.out.println("Keep playing?");
}
String response = scan.next();
return response;
}
затем измените метод воспроизведения следующим образом:
public void play() {
boolean gameOver = false;
startGame();
String response = askUser(true);
;
;
}
Я сделал небольшие изменения в вашем коде. Попробуйте это:
package stack;
import java.util.*;
public class Blackjack{
private int points;
private int limit;
private Scanner scan;
private boolean firstime = true; //new
boolean gameOver; //new
private String answer;//new
public Blackjack(){
scan = new Scanner(System.in);
}
/*Purpose: To print the current points and the limit.
Input: Points and Limit
Output: Points and Limit
*/
public void displayPoints(){
System.out.println("Your points:" + points+"/"+limit);
}
/*Purpose: To ask the user for the game limit.
Input: Game limit
Output: Entered limit
*/
public void startGame(){//Changes
if(firstime == true) {
System.out.println("Start Playing?");
answer = scan.next();
}
switch(answer) {
case "yes":
System.out.println("Enter point limit:");
limit = scan.nextInt();
int roll = getRoll();
points = points + roll;
displayResult();
break;
case "no":
goodBye();
}
}
//New method
public void goodBye() {
System.out.println("Goodbye!");
scan.close();
}
/*Purpose: To get the roll value from rolling a dice
Input: Nothing
Output: Random dice number
*/
public int getRoll(){
Random r = new Random();
int roll = r.nextInt(6)+1;
System.out.println("You rolled:" + roll);
return roll;
}
/* Purpose: to display the result of points in the game.
Input: No input.
Output: amount of points in the game.
*/
public void displayResult(){//Changes
if(points == limit) {
gameOver = true;
System.out.println("BlackJack!");
displayPoints();
System.out.println("Keep playing?");
answer = scan.next();
}
else if (points > limit) {
gameOver = true;
System.out.println("Bust!");
displayPoints();
System.out.println("Keep playing?");
answer = scan.next();
}
else if (points < limit) {
gameOver = false;
System.out.println("Stand at " + points + " points!");
}
}
/*Purpose: to play all methods
Input: none.
Output: Game results.
*/
public void play(){//Changes
startGame();
ENDWHILE:while(gameOver == true || gameOver == false) {
if(answer.equals("yes")) {
firstime = false;
while(gameOver == true) {
points = 0;
startGame();
}
while(gameOver == false) {
startGame();
}
}else {
break ENDWHILE;
}
}
goodBye();
}
public static void main(String [] args){
Blackjack practice = new Blackjack();
practice.play();
}
}
это работает .. вы допустили две небольшие ошибки, которые я прокомментировал внутри кода нужно обернуть содержимое цикла внутри {}. и пользовательский ввод должен быть возвращен в виде строки в функции askUser. следующий код работает так, как вы хотели.
package javaapplication1;
import java.util.*;
public class JavaApplication1 {
private int points;
private int limit;
private Scanner scan;
public JavaApplication1(){
scan = new Scanner(System.in);
}
public void displayPoints(){
System.out.println("Your points:" + points+"/"+limit);
}
/*Purpose: To ask the user for the game limit.
Input: Game limit
Output: Entered limit
*/
public void startGame(){
System.out.println("Enter point limit:");
limit = scan.nextInt();
displayPoints();
}
public int getRoll(){
Random r = new Random();
int roll = r.nextInt(6)+1;
System.out.println("You rolled:" + roll);
return roll;
}
public String askUser(boolean firstTime){
if(firstTime == true)
System.out.println("Start Playing?");
else {
System.out.println("Keep playing?");
}
return scan.next();
}
public void displayResult(){
if(points == limit)
System.out.println("BlackJack!");
else if (points > limit)
System.out.println("Bust!");
else if (points < limit)
System.out.println("Stand at " + points + " points!");
}
public void play(){
boolean gameOver = false;
startGame();
String resUser = askUser(true); // add a variable to catch the input //exp-"yes"
String response = "";
int roll = getRoll();
while(resUser.equals("yes")&& gameOver == false){ // you forget the { and use //the variable to check if it is yess or not
getRoll();
points = points + roll;
displayPoints();
if(points >= limit)
gameOver =true;
else{
resUser = askUser(false);//catching the new user input
}
}// you forget the }. if you are not wrapping the loop with {}, it will only //execute one line after the loop
displayResult();
}
public static void main(String [] args){
JavaApplication1 practice = new JavaApplication1();
practice.play();
}
}