Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Empty file added challenge_rst/__init__.py
Empty file.
38 changes: 38 additions & 0 deletions challenge_rst/engine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""
Playing engine for WARRIORS, ROBBERS AND WIZARDS GAME
"""

from models import Player, Enemy
from exceptions import EnemyDown, GameOver
import settings


def get_player_name():
"""Getting player name from terminal"""
player_name = ""
while not player_name:
player_name = input("ENTER YOUR NAME: ").strip()
return player_name


def play():
"""Playing engine"""
player_name = get_player_name()
player = Player(player_name)
enemy = Enemy()

while True:
try:
player.attack(enemy)
player.defence(enemy)
except EnemyDown:
player.score_points += settings.EXTRA_SCORE_POINTS_ADD
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нормально.
Цей коментар більше для інформації - щоб не модифікувати стан обʼєкта напряму, краще зробити метод, що буде додавати гравцю бали. Якийсь add_score(points).

enemy = Enemy(enemy.level + 1)
except GameOver:
break
except KeyboardInterrupt:
raise GameOver(player, "KeyboardInterrupt")


if __name__ == '__main__':
play()
28 changes: 28 additions & 0 deletions challenge_rst/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""
Exceptions for WARRIORS, ROBBERS AND WIZARDS GAME
"""


class EnemyDown(Exception):
"""Raised when enemy is defeated"""

def __init__(self, level):
super().__init__()
self.level = level
print(f"Enemy level {self.level} is defeated")

def __dir__(self):
return "EnemyDown Exception"


class GameOver(Exception):
"""Raised when player is defeated"""

def __init__(self, player, *args):
super().__init__()
self.name = player.name
self.points = player.score_points
print(f"\n{self.name} is defeated \n"
f"SCORE POINTS: {self.points}")
if not args:
print("GOOD BYE!")
140 changes: 140 additions & 0 deletions challenge_rst/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"""
Behavior description for WARRIORS, ROBBERS AND WIZARDS GAME
"""

from random import randint

import settings
from exceptions import EnemyDown, GameOver


class Enemy:
"""Create game enemy"""

def __init__(self, level: int = 1):
self.health = level
self.level = level

@staticmethod
def fight_choice_select():
"""Select person choice for enemy"""
random_person = str(randint(1, 3))
return random_person

def decrease_health(self, score_down):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я б радив прибрати залежність від аргументу.
Ти все одно використовуєш константу - отже просто віднімай 1 у тілі методу.

"""Decrease enemy health"""
self.health -= score_down
if self.health > 0:
return self.health
else:
raise EnemyDown(self.level)

def select_attack(self):
"""Select person choice for attack"""
attack_choice = self.fight_choice_select()
return attack_choice

def select_defence(self):
"""Select person choice for defence"""
defence_choice = self.fight_choice_select()
return defence_choice


class Player:
"""Create game player"""

def __init__(self, name: str):
self.name = name
self.health_points = settings.INITIAL_PLAYER_HEALTH
self.score_points = 0

def __repr__(self):
return f"Player - {self.name}"

def write_to_file(self):
"""Write game results to the file"""
data = f"Name - {self.name}, score points: {self.score_points}\n"
with open("scores.txt", "a") as file:
file.write(data)

@staticmethod
def fight_choice_select():
"""Select person choice for player"""

fight_choice = ''
while fight_choice not in ["1", "2", "3"]:
fight_choice = input(
"MAKE A FIGHT CHOICE FROM (WARRIOR - 1, ROBBER - 2, WIZARD - 3): "
)
return fight_choice

def decrease_health(self, score_down):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я б радив прибрати залежність від аргументу.
Ти все одно використовуєш константу - отже просто віднімай 1 у тілі методу.

"""Decrease player health"""

self.health_points -= score_down
if self.health_points > 0:
return self.health_points
else:
self.write_to_file()
raise GameOver(self)

def select_attack(self):
"""Select person choice for attack manually"""

attack_choice = self.fight_choice_select()
return attack_choice

def select_defence(self):
"""Select person choice for defence manually"""

defence_choice = self.fight_choice_select()
return defence_choice

@staticmethod
def fight(attack_choice, defence_choice):
"""Fight results determination"""
if [attack_choice, defence_choice] in [
["1", "2"],
["2", "3"],
["3", "1"]
]:
return 'win'
elif attack_choice == defence_choice:
return 'draw'
else:
return 'loss'

def attack(self, enemy: Enemy):
"""Attack an enemy"""
attack_choice = self.select_attack()
defence_choice = enemy.select_defence()
fight_result = self.fight(attack_choice, defence_choice)
if fight_result == 'win':
try:
print('YOUR ATTACK IS SUCCESSFUL!')
self.score_points += settings.SCORE_PLAYER_ADD
enemy.decrease_health(settings.SCORE_ENEMY_DOWN)
except EnemyDown:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А який у цьому сенс? Ти відловив ексепшн і одразу ж його зарайзив.

raise
elif fight_result == 'loss':
print('YOUR ATTACK IS FAILED!')
elif fight_result == 'draw':
print("IT'S A DRAW!")

def defence(self, enemy: Enemy):
"""Defence from an enemy"""

defence_choice = self.select_attack()
attack_choice = enemy.select_defence()
fight_result = self.fight(attack_choice, defence_choice)
if fight_result == 'win':
try:
print('YOUR DEFENCE IS FAILED!')
self.decrease_health(settings.SCORE_PLAYER_DOWN)
except GameOver:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А який у цьому сенс? Ти відловив ексепшн і одразу ж його зарайзив.

raise
elif fight_result == 'loss':
print('YOUR DEFENCE IS SUCCESSFUL!')

elif fight_result == 'draw':
print("IT'S A DRAW!")
9 changes: 9 additions & 0 deletions challenge_rst/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""
Constants for WARRIORS, ROBBERS AND WIZARDS GAME
"""

INITIAL_PLAYER_HEALTH = 5
SCORE_PLAYER_ADD = 1
SCORE_PLAYER_DOWN = 1
EXTRA_SCORE_POINTS_ADD = 2
SCORE_ENEMY_DOWN = 1