|
| 1 | +# tictactoe_tests.py |
| 2 | +# From Classic Computer Science Problems in Python Chapter 8 |
| 3 | +# Copyright 2018 David Kopec |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +import unittest |
| 17 | +from minimax import find_best_move |
| 18 | +from tictactoe import TTTPiece, TTTBoard |
| 19 | +from board import Move |
| 20 | + |
| 21 | + |
| 22 | +class TTTMinimaxTestCase(unittest.TestCase): |
| 23 | + def test_easy_position(self): |
| 24 | + # win in 1 move |
| 25 | + to_win_easy_position: List[TTTPiece] = [TTTPiece.X, TTTPiece.O, TTTPiece.X, |
| 26 | + TTTPiece.X, TTTPiece.E, TTTPiece.O, |
| 27 | + TTTPiece.E, TTTPiece.E, TTTPiece.O] |
| 28 | + test_board1: TTTBoard = TTTBoard(to_win_easy_position, TTTPiece.X) |
| 29 | + answer1: Move = find_best_move(test_board1) |
| 30 | + self.assertEqual(answer1, 6) |
| 31 | + |
| 32 | + def test_block_position(self): |
| 33 | + # must block O's win |
| 34 | + to_block_position: List[TTTPiece] = [TTTPiece.X, TTTPiece.E, TTTPiece.E, |
| 35 | + TTTPiece.E, TTTPiece.E, TTTPiece.O, |
| 36 | + TTTPiece.E, TTTPiece.X, TTTPiece.O] |
| 37 | + test_board2: TTTBoard = TTTBoard(to_block_position, TTTPiece.X) |
| 38 | + answer2: Move = find_best_move(test_board2) |
| 39 | + self.assertEqual(answer2, 2) |
| 40 | + |
| 41 | + def test_hard_position(self): |
| 42 | + # find the best move to win 2 moves |
| 43 | + to_win_hard_position: List[TTTPiece] = [TTTPiece.X, TTTPiece.E, TTTPiece.E, |
| 44 | + TTTPiece.E, TTTPiece.E, TTTPiece.O, |
| 45 | + TTTPiece.O, TTTPiece.X, TTTPiece.E] |
| 46 | + test_board3: TTTBoard = TTTBoard(to_win_hard_position, TTTPiece.X) |
| 47 | + answer3: Move = find_best_move(test_board3) |
| 48 | + self.assertEqual(answer3, 1) |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == '__main__': |
| 52 | + unittest.main() |
| 53 | + |
| 54 | + |
0 commit comments