Как разрешить вводить только цифры от 1 до 3 в игре при выборе игрового персонажа?
Пишу игру по, где игрок должен выбрать игрового персонажа (1 - Маг, 2 - Воин, 3 - Разбойник), компьютер отвечает рандомно на атаку игрока, затем у игрока ход защиты. Проблема с тем, как ограничить выбор для игрока только цифрами 1,2,3. Ввод не ввод букв ограничил с помощью except ValueError и при вводе буквы выдает сообщение и неправильном вводе и игроку повторно предлагается выбрать персонажа, а вот с цифрами так не выходит. Немного о структуре. Есть основной файл Game, где непосредственно игровой цикл, файл Models с описанием класса Enemy and Player и атаками/защитами. Файл Settings с инфой о жизнях и уровнях, и файл Game Exception с исключениями.
file Game
import models
import settings
import re
def read_score():
pass
if __name__ == '__main__':
while True:
print("*------------Welcome to Game!----------*")
command = input('Type "start" or "help":')
if command == 'help':
print(settings.HELP_INFORMATION)
elif command == 'start':
break
elif command == 'show scores':
read_score()
elif command == 'exit':
raise KeyboardInterrupt
else:
print('Wrong command!\n'
'Try again')
if __name__ == '__main__':
flag_name = True
while flag_name:
flag_name = False
name = input('Please, enter your "name" : ')
try:
for i in name:
if i.isdigit():
raise ValueError("The name must not numbers!")
except Exception:
print("The name must not numbers!!")
flag_name = True
while True:
print("----------------------------------------")
print("May the Force be with you!")
print("----------------------------------------"'\n')
print("****************************************")
def main():
input_player = True
while input_player:
input_player = False
player.attack = int(input('Select Attack to Use: 1 - WIZARD, 2 - WARRIOR, 3 - ROGUE : '))
try:
for i in player.attack:
if i.isdigit() is not True:
raise ValueError("Возраст должен быть из цифр!")
elif i not in range(3):
raise ValueError
except Exception:
print('\n'"Ввод должен быть из цифр и в диапазоне от 1 до 3!")
player = models.Player(settings.PLAYER_LIVES)
level = settings.LEVEL
enemy = models.Enemy(level, settings.LEVEL)
while True:
try:
player.attack(enemy.select_attack())
player.defence(enemy.select_attack())
except ValueError:
print("Incorrect input\n"
"Try again!")
except game_exceptions.EnemyDown:
player.score += 5
print("Enemy Down")
print(f'scores: {settings.SCORE}')
settings.LEVEL += 1
lives = settings.LEVEL
name = re.sub(r'[^\w\s]+|[\d]+', r'', name).strip()
file Models
import settings
from game_exceptions import EnemyDown, GameOver
class Enemy:
def __init__(self, level, lives):
self.level = level
self.lives = settings.LEVEL
@staticmethod
def select_attack():
return random.randrange(1, 3)
def decrease_lives(self):
if not self.lives == 0:
self.lives -= 1
else:
raise EnemyDown
class Player:
def __init__(self, name, lives=settings.PLAYER_LIVES, allowed_attacks=None):
self.name = name
self.lives_player = lives
self.Score = 0
self.allowed_attacks = allowed_attacks
self.level = settings.LEVEL
@staticmethod
def fight(attack, defence):
if attack == defence:
return 0
if attack > defence:
return 1
if attack < defence:
return -1
def attack(self, enemy_obj):
attack = int(input('Select Attack to Use: 1 - WIZARD, 2 - WARRIOR, 3 - ROGUE : '))
attack_res = self.fight(attack, enemy_obj)
if attack_res == 0:
print(f'It`s a draw!\n Your lives: {decrease_lives}')
print("--------------------------------------------------------------")
elif attack_res == 1:
print(f'You attacked successfully!\n Your lives:{Player.decrease_lives}')
print("--------------------------------------------------------------")
self.decrease_lives()
elif attack_res == -1:
print(f'You missed!\n Your lives:{Player.decrease_lives}')
print("--------------------------------------------------------------")
return False
def defence(self, enemy_obj):
defence = int(input('Select Defence to Use: 1 - WIZARD, 2 - WARRIOR, 3 - ROGUE : '))
defence_res = self.fight(enemy_obj, defence)
if defence_res == 0:
print(f'It`s a draw!\nYour lives:{Player.decrease_lives}')
print("-------------------------------------------------------------")
return True
elif defence_res == 1:
print(f'You defended successfully!\n Your lives:{Player.decrease_lives}')
print("-------------------------------------------------------------")
self.decrease_lives()
if self.lives_player <= 0:
return False
elif defence_res == -1:
print(f'Enemy missed!\n Your lives:{Player.decrease_lives}')
print("-------------------------------------------------------------")
return False
def decrease_lives(self):
try:
if not self.lives_player == 0:
self.lives_player -= 1
except GameOver:
print("Game over")
file Settings
LEVEL = 1
SCORE = 0
def Scores():
global SCORE
SCORE += 10
SCORE.config(text = "Score: " + str(SCORE))
Show_scores()
def Show_scores():
global SHOW_SCORES, SCORE
if SCORE > SHOW_SCORES:
SHOW_SCORES = SCORE
SHOW_SCORES.config(text = "Show scores: " + str(SHOW_SCORES))
HELP_INFORMATION = """Ход начинается с игрока"""
file Game_Exception
def __init__(self, score, lines=None):
self.score = score
with open(r"scores.txt", "w") as file:
for line in lines:
file.write(line + '\n')
print('Game Over')
class EnemyDown(Exception):
pass
class KeyboardInterrupt(Exception):
pass
class ValueError(Exception):
pass
class Validate(Exception):
pass
Ответы (2 шт):
Просто добавьте условие if
Например:
if player.attack not in [1, 2, 3]:
...
Если вам нужно чтобы атаки не проходили, то сделайте в цикле while:
while player.attack not in [1, 2, 3]:
...
Не совсем понял проблематику вопроса, но возможно похожая структура сможет помочь:
correct_numbers = [1, 2, 3]
user_number = input("Выбор 1-3: ")
if int(user_number) in correct_numbers:
print('Подходящее число.')
else:
print('Не подходит.')
В список добавляем все подходящие числа, делаем проверку на любое из них. Если не подходит, то оповещаем.
Если подходит, то можно туда добавить ещё разветвление, что именно происходит в зависимости от числа.
Думаю, с такой задачей Вы бы справились и сами, скорее всего лучшим способом, поэтому уточните проблему, пожалуйста.
