feat: round queue

This commit is contained in:
korzepadawid 2022-04-04 21:07:40 +02:00
parent 37c58763f8
commit bef17bccd1
4 changed files with 79 additions and 0 deletions

View File

View File

@ -0,0 +1,54 @@
import unittest
from logic.knights_queue import KnightsQueue
from models.knight import Knight
class KnightsQueueTest(unittest.TestCase):
def test_should_raise_when_team_has_dead_knights(self):
with self.assertRaises(Exception):
knight1 = Knight(None)
knight1.health = 0
knight2 = Knight(None)
knight2.health = -1
knight3 = Knight(None)
knight3.health = -2
knight4 = Knight(None)
knight4.health = 20
knights_queue = KnightsQueue([knight1, knight2, knight3], [knight4])
knights_queue.dequeue_knight()
knights_queue.dequeue_knight()
def test_should_return_knight_from_any_team_and_add_to_queue_again(self):
knight1 = Knight(None)
knight1.health = 10
knight2 = Knight(None)
knight2.health = 20
knights_queue = KnightsQueue([knight1], [knight2])
result1 = knights_queue.dequeue_knight()
result2 = knights_queue.dequeue_knight()
result3 = knights_queue.dequeue_knight()
self.assertIsNotNone(result1)
self.assertIsNotNone(result2)
self.assertIsNotNone(result3)
self.assertTrue(result1.health == result3.health)
def test_should_raise_when_only_one_team_alive(self):
with self.assertRaises(Exception):
knight = Knight(None)
knight.health = 21
knights_queue = KnightsQueue([knight], [])
knights_queue.dequeue_knight()
def test_should_raise_when_no_team_alive(self):
with self.assertRaises(Exception):
knights_queue = KnightsQueue([], [])
knights_queue.dequeue_knight()
if __name__ == '__main__':
unittest.main()

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

25
logic/knights_queue.py Normal file
View File

@ -0,0 +1,25 @@
import random
from collections import deque
class KnightsQueue:
def __init__(self, blue_team, red_team):
self.queues = deque(blue_team), deque(red_team)
self.team_idx_turn = random.randint(0, 1)
def dequeue_knight(self):
if self.both_teams_alive():
knight = self.queues[self.team_idx_turn].popleft()
if knight.health <= 0:
self.dequeue_knight()
else:
self.queues[self.team_idx_turn].append(knight)
self.next_round()
return knight
raise Exception('Game has just ended')
def both_teams_alive(self):
return len(self.queues[0]) > 0 and len(self.queues[1]) > 0
def next_round(self):
self.team_idx_turn = (self.team_idx_turn + 1) % 2