├── requirements.txt
├── images
├── icon.png
├── title.png
├── display.png
├── paused.png
├── arrow_left.png
├── hamburger.png
├── human_blue.png
├── human_red.png
├── arrow_right.png
├── computer_blue.png
├── computer_red.png
├── human_green.png
├── human_orange.png
├── computer_green.png
├── computer_orange.png
└── wood_background.png
├── __pycache__
└── box.cpython-310.pyc
├── Package.json
├── LICENSE
├── box.py
├── LEARN.md
├── README.md
├── CODE_OF_CONDUCT.md
├── main.py
├── Contributing.md
└── player.py
/requirements.txt:
--------------------------------------------------------------------------------
1 | pygame
2 |
--------------------------------------------------------------------------------
/images/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/icon.png
--------------------------------------------------------------------------------
/images/title.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/title.png
--------------------------------------------------------------------------------
/images/display.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/display.png
--------------------------------------------------------------------------------
/images/paused.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/paused.png
--------------------------------------------------------------------------------
/images/arrow_left.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/arrow_left.png
--------------------------------------------------------------------------------
/images/hamburger.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/hamburger.png
--------------------------------------------------------------------------------
/images/human_blue.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/human_blue.png
--------------------------------------------------------------------------------
/images/human_red.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/human_red.png
--------------------------------------------------------------------------------
/images/arrow_right.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/arrow_right.png
--------------------------------------------------------------------------------
/images/computer_blue.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/computer_blue.png
--------------------------------------------------------------------------------
/images/computer_red.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/computer_red.png
--------------------------------------------------------------------------------
/images/human_green.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/human_green.png
--------------------------------------------------------------------------------
/images/human_orange.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/human_orange.png
--------------------------------------------------------------------------------
/images/computer_green.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/computer_green.png
--------------------------------------------------------------------------------
/images/computer_orange.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/computer_orange.png
--------------------------------------------------------------------------------
/images/wood_background.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/images/wood_background.png
--------------------------------------------------------------------------------
/__pycache__/box.cpython-310.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shrawani21/gamer_21/HEAD/__pycache__/box.cpython-310.pyc
--------------------------------------------------------------------------------
/Package.json:
--------------------------------------------------------------------------------
1 | const specs = {
2 | project: {
3 | name: "Dot and Boxes",
4 | defaultBranch: "main",
5 | repoUrl: "https://github.com/shrawani21/gamer_21.git",
6 | },
7 | contributing: {
8 | generate: true
9 | }
10 | };
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Shrawani
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/box.py:
--------------------------------------------------------------------------------
1 | from typing import List, Optional, Tuple
2 |
3 | class Box:
4 | ALL_BOXES: List["Box"] = []
5 | BOXES_DONE = 0
6 |
7 | def __init__(self, y: int, x: int):
8 | self.idx: Tuple[int, int] = (y, x)
9 | self._top: Optional[str] = None
10 | self._bottom: Optional[str] = None
11 | self._left: Optional[str] = None
12 | self._right: Optional[str] = None
13 | self.sides: int = 0
14 | self.color: Optional[str] = None
15 |
16 | Box.ALL_BOXES.append(self)
17 |
18 | def top_idx(self) -> Tuple[Tuple[int, int], Tuple[int, int]]:
19 | return self.idx, (self.idx[0], self.idx[1] + 1)
20 |
21 | def bottom_idx(self) -> Tuple[Tuple[int, int], Tuple[int, int]]:
22 | return (self.idx[0] + 1, self.idx[1]), (self.idx[0] + 1, self.idx[1] + 1)
23 |
24 | def left_idx(self) -> Tuple[Tuple[int, int], Tuple[int, int]]:
25 | return self.idx, (self.idx[0] + 1, self.idx[1])
26 |
27 | def right_idx(self) -> Tuple[Tuple[int, int], Tuple[int, int]]:
28 | return (self.idx[0], self.idx[1] + 1), (self.idx[0] + 1, self.idx[1] + 1)
29 |
30 | @property
31 | def top(self) -> Optional[str]:
32 | return self._top
33 |
34 | @top.setter
35 | def top(self, top: str):
36 | self._top = top
37 | self.sides += 1
38 | if self.sides == 4:
39 | self.color = top
40 | Box.BOXES_DONE += 1
41 |
42 | @property
43 | def bottom(self) -> Optional[str]:
44 | return self._bottom
45 |
46 | @bottom.setter
47 | def bottom(self, bottom: str):
48 | self._bottom = bottom
49 | self.sides += 1
50 | if self.sides == 4:
51 | self.color = bottom
52 | Box.BOXES_DONE += 1
53 |
54 | @property
55 | def left(self) -> Optional[str]:
56 | return self._left
57 |
58 | @left.setter
59 | def left(self, left: str):
60 | self._left = left
61 | self.sides += 1
62 | if self.sides == 4:
63 | self.color = left
64 | Box.BOXES_DONE += 1
65 |
66 | @property
67 | def right(self) -> Optional[str]:
68 | return self._right
69 |
70 | @right.setter
71 | def right(self, right: str):
72 | self._right = right
73 | self.sides += 1
74 | if self.sides == 4:
75 | self.color = right
76 | Box.BOXES_DONE += 1
77 |
--------------------------------------------------------------------------------
/LEARN.md:
--------------------------------------------------------------------------------
1 | # Dot and Boxes Game
2 |
3 | Welcome to Dot and Boxes , it is a classic pen-and-paper game where two players take turns connecting dots to form lines. When a player completes a box by forming the fourth side, they score a point and get another turn. The player with the most boxes at the end of the game wins.
4 |
5 | 
6 |
7 | ## Background Blocks
8 | The game is built using Pygame:
9 | Pygame is a set of Python modules designed for writing video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language.
10 | Pygame is highly portable and runs on nearly every platform and operating system.
11 | Pygame itself has been downloaded millions of times.
12 | Pygame is free. Released under the LGPL licence, you can create open source, freeware, shareware, and commercial games with it. See the licence for full details.
13 | For a nice introduction to pygame, examine the line-by-line chimp tutorial, and the introduction for python programmers. buffer, and many other different backends... including an ASCII art backend! OpenGL is often broken on linux systems, and also on windows systems - which is why professional games use multiple backends.
14 | Multi core CPUs can be used easily. With dual core CPUs common, and 8 core CPUs cheaply available on desktop systems, making use of multi core CPUs allows you to do more in your game. Selected pygame functions release the dreaded python GIL, which is something you can do from C code.
15 | Uses optimized C and Assembly code for core functions. C code is often 10-20 times faster than python code, and assembly code can easily be 100x or more times faster than python code.
16 |
17 | ## Features
18 |
19 | - **Grid-based Gameplay**: The game consists of a grid where players take turns to draw lines between dots.
20 | - **Two Players**: The game supports two players, either two human players taking turns.
21 | - **Turn-based System**: The game alternates turns between the players unless a player completes a box, in which case they get an extra turn.
22 | - **Score Tracking**: Keep track of each player's score throughout the game.
23 |
24 | ## Instructions for Playing
25 |
26 | 1. **Player Representation**: Player 1 is represented by 'X' and Player 2 is represented by 'O'.
27 | 2. **Drawing Lines**:
28 | - Use the arrow keys to draw lines:
29 | - Up Arrow: Draw the top line of the selected cell.
30 | - Right Arrow: Draw the right line of the selected cell.
31 | - Down Arrow: Draw the bottom line of the selected cell.
32 | - Left Arrow: Draw the left line of the selected cell.
33 | - Alternatively, you can also use the mouse to select cells by clicking on them.
34 | 3. **Scoring**: When a player completes the fourth side of a box, they earn a point and get an additional turn.
35 | 4. **Game Over**: The game ends when all the boxes are completed. A "Game Over" message will be displayed.
36 | 5. **Restart and Quit**: Press the 'R' key to restart the game at any time. Press 'Q' or the 'Escape' key to quit the game.
37 |
38 | ## Additional Enhancements that can done/progress
39 |
40 | - **Sound Effects**: Introduce sound effects for actions like placing a line, winning, or game over to enhance the user experience.
41 | - **Animations**: Add animations for line drawing or winning sequences to make the gameplay more engaging.
42 | - **Customization Options**: Allow players to customize their experience by choosing colors, symbols, or grid sizes.
43 | - **AI Opponent**: Implement an AI opponent for single-player mode using algorithms like Minimax or Monte Carlo Tree Search.
44 | - **Network Multiplayer**: Add network multiplayer functionality so players can compete against each other online.
45 | - **Menu System**: Create a menu system for starting the game, adjusting settings, and quitting.
46 | - **Error Handling**: Implement error handling to gracefully handle unexpected user inputs or edge cases.
47 |
48 | ## Getting Started
49 | To run the game, kindly follow the steps given in [Readme.md](https://github.com/shrawani21/gamer_21/blob/main/README.md) & enjoy the Dots & Boxes Game by Pygame .
50 |
51 |
52 | ## Contibuting Guidelines
53 | We believe in the power of collaboration. If you have ideas to improve College.ai, feel free to contribute! Check out our [Contribution Guidelines]https://github.com/shrawani21/gamer_21/blob/main/Contributing.md to get started.
54 |
55 | # Message From PA
56 |
57 | Welcome to Dots & Boxes!!
58 |
59 | We're glad you're here and excited for you to explore our project. Whether you're checking out the code, contributing to the project, or providing feedback, your presence and input are invaluable.
60 |
61 | Feel free to dive in, get involved, and make gamer_21 even better!
62 | 🌟 **Enjoy exploring the world of games!**
63 |
64 | Happy coding!
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 🎮 Dot and Boxes Game 🎮
2 |
3 | ## 📜 Description
4 | Dot and Boxes is a classic pen-and-paper game where two players take turns connecting dots to form lines. When a player completes a box by forming the fourth side, they score a point and get another turn. The player with the most boxes at the end of the game wins.
5 |
6 |
7 | 
8 |
9 | ## ✨ Features
10 | - **Grid-based Gameplay:** The game consists of a grid where players take turns to draw lines between dots.
11 |
12 |
13 | - **Two Players:** The game supports two players, either two human players taking turns.
14 |
15 |
16 | - **Turn-based System:** The game alternates turns between the players unless a player completes a box, in which case they get an extra turn.
17 |
18 |
19 | - **Score Tracking:** Keep track of each player's score throughout the game.
20 |
21 |
22 |
23 | ## 🎲 Instructions for Playing
24 | 1. Player 1 is represented by 'X' and Player 2 is represented by 'O'.
25 |
26 | 2. Use the arrow keys to draw lines:
27 |
28 | 1. Up Arrow: Draw the top line of the selected cell.
29 |
30 | 2. Right Arrow: Draw the right line of the selected cell.
31 | 3. Down Arrow: Draw the bottom line of the selected cell.
32 | 4. Left Arrow: Draw the left line of the selected cell.
33 |
34 | or you can also use the mouse to select cells by clicking on them.
35 |
36 |
37 | 3. When a player completes the fourth side of a box, they earn a point and get an additional turn.
38 |
39 | 4. The game ends when all the boxes are completed. "Game Over" message will be displayed
40 |
41 | 5. Press the 'R' key to restart the game at any time.
42 |
43 | 6. Press 'Q' or the 'Escape' key to quit the game.
44 |
45 | ## 💻 Installation
46 | 1. Clone the repository to your local machine:
47 | ```bash
48 | git clone https://github.com/shrawani21/gamer_21.git
49 | ```
50 | 2. Navigate to the project directory:
51 | ```bash
52 | cd gamer_21
53 | ```
54 | 3. Install dependencies/requirements:
55 | ```bash
56 | pip install -r requirements.txt
57 | ```
58 | or
59 | ```bash
60 | pip install pygame
61 | ```
62 | 4. Run the Game:
63 | ```bash
64 | python main.py
65 | ```
66 | This will launch the game!
67 |
68 |
69 | ## 🤝 How to Contribute
70 |
71 | If you think that you can add a new feature or want to fix a bug, we invite you to contribute to gamer_21 and make this project better.
72 |
To start contributing, follow the below instructions:
73 |
74 | 1. Create a folder in your system where you want to save the files.
75 |
76 | 2. Open Git Bash there.
77 |
78 | 3. Create a Git repository.
79 | Run command `git init`
80 |
81 | 4. Fork the [repository](https://github.com/shrawani21/gamer_21.git).
82 |
83 | 5. Clone your forked repository of project.
84 | ```
85 | git clone https://github.com//gamer_21.git
86 | ```
87 |
88 | 6. Navigate to the project directory.
89 |
90 | ```
91 | cd gamer_21
92 | ```
93 | 7. Add a reference(remote) to the original repository.
94 |
95 | ```
96 | git remote add upstream https://github.com/shrawani21/gamer_21.git
97 | ```
98 | 8. Check the remotes for this repository.
99 |
100 | ```
101 | git remote -v
102 | ```
103 |
104 | 9. Always take a pull from the upstream repository to your main branch to keep it updated as per the main project repository.
105 |
106 | ```
107 | git pull upstream main
108 | ```
109 |
110 | 10. Create a new branch(prefer a branch name that relates to your assigned issue).
111 |
112 | ```
113 | git checkout -b
114 | ```
115 |
116 | 11. Perform your desired changes to the code base.
117 |
118 | 12. Check your changes.
119 |
120 |
121 | ```
122 | git status
123 | ```
124 |
125 | ```
126 | git diff
127 | ```
128 |
129 | 13. Stage your changes.
130 |
131 | ```
132 | git add . <\files_that_you_made_changes>
133 | ```
134 |
135 | 14. Commit your changes.
136 |
137 | ```
138 | git commit -m "relavant message"
139 | ```
140 |
141 | 15. Push the committed changes in your feature branch to your remote repository.
142 |
143 | ```
144 | git push -u origin
145 | ```
146 |
147 | 16. To create a pull request, click on `compare and pull requests`.
148 |
149 | 17. Add an appropriate title and description to your pull request explaining your changes.
150 |
151 | 18. Click on `Create pull request`.
152 |
153 |
154 | Congratulations🎉, you have made a pull request to the Gamer_21. Wait for your submission to be accepted and merged.
155 |
156 | ## Tech Stacks Used:
157 | -python
158 | -pygame
159 |
160 | ## 📜 Credits
161 | - This project is based on the classic Dot and Boxes game.
162 | - Developed using Python only.
163 |
164 |
165 | ## 📄 License
166 | - This project is licensed under the [MIT License](https://opensource.org/licenses/MIT).
167 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement.
63 |
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | import sys
3 |
4 | # Constants
5 | SCREEN_WIDTH, SCREEN_HEIGHT = 300, 300
6 | CELL_SIZE = 40
7 | PADDING = 20
8 | ROWS = COLS = (SCREEN_WIDTH - 4 * PADDING) // CELL_SIZE
9 |
10 | # Colors
11 | WHITE = (255, 255, 255)
12 | RED = (252, 91, 122)
13 | BLUE = (78, 193, 246)
14 | GREEN = (0, 255, 0)
15 | BLACK = (12, 12, 12)
16 | DARK_GRAY = (30, 30, 30)
17 | LIGHT_GRAY = (100, 100, 100)
18 |
19 |
20 | # Initialize Pygame
21 | pygame.init()
22 |
23 | screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
24 | pygame.display.set_caption("Pygame Game with Replay and Quit")
25 |
26 | win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
27 | font = pygame.font.SysFont('cursive', 25)
28 |
29 | #buttons
30 | button_width = 200
31 | button_height = 50
32 |
33 | # Define the Cell class to represent each cell in the grid
34 | class Cell:
35 | def __init__(self, row, col):
36 | self.row = row
37 | self.col = col
38 | self.index = self.row * ROWS + self.col
39 | self.rect = pygame.Rect((self.col * CELL_SIZE + 2 * PADDING,
40 | self.row * CELL_SIZE + 3 * PADDING,
41 | CELL_SIZE, CELL_SIZE))
42 | self.edges = [
43 | [(self.rect.left, self.rect.top), (self.rect.right, self.rect.top)],
44 | [(self.rect.right, self.rect.top), (self.rect.right, self.rect.bottom)],
45 | [(self.rect.right, self.rect.bottom), (self.rect.left, self.rect.bottom)],
46 | [(self.rect.left, self.rect.bottom), (self.rect.left, self.rect.top)]
47 | ]
48 | self.sides = [False] * 4
49 | self.winner = None
50 |
51 | def check_win(self, winner):
52 | if not self.winner and all(self.sides):
53 | self.winner = winner
54 | self.color = GREEN if winner == 'X' else RED
55 | self.text = font.render(self.winner, True, WHITE)
56 | return 1
57 | return 0
58 |
59 | def update(self, win):
60 | if self.winner:
61 | pygame.draw.rect(win, self.color, self.rect)
62 | win.blit(self.text, (self.rect.centerx - 5, self.rect.centery - 7))
63 |
64 | for index, side in enumerate(self.sides):
65 | if side:
66 | pygame.draw.line(win, WHITE, self.edges[index][0], self.edges[index][1], 2)
67 |
68 | def create_cells():
69 | cells = []
70 | for r in range(ROWS):
71 | for c in range(COLS):
72 | cell = Cell(r, c)
73 | cells.append(cell)
74 | return cells
75 |
76 | def reset_cells():
77 | return None, None, False, False, False, False
78 |
79 | def reset_score():
80 | return 0, 0, 0
81 |
82 | def reset_player():
83 | return 0, ['X', 'O'], 'X', False
84 |
85 | # Game variables initialization
86 | game_over = False
87 | cells = create_cells()
88 | pos, current_cell, up, right, bottom, left = reset_cells()
89 | fill_count, p1_score, p2_score = reset_score()
90 | turn, players, current_player, next_turn = reset_player()
91 |
92 | # Main game loop
93 | running = True
94 | while running:
95 |
96 | win.fill(DARK_GRAY)
97 |
98 | for event in pygame.event.get():
99 | if event.type == pygame.QUIT:
100 | running = False
101 | elif event.type == pygame.MOUSEBUTTONDOWN:
102 | pos = event.pos
103 | elif event.type == pygame.MOUSEBUTTONUP:
104 | pos = None
105 | elif event.type == pygame.KEYDOWN:
106 | if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
107 | running = False
108 | elif event.key == pygame.K_r:
109 | game_over = False
110 | cells = create_cells()
111 | pos, current_cell, up, right, bottom, left = reset_cells()
112 | fill_count, p1_score, p2_score = reset_score()
113 | turn, players, current_player, next_turn = reset_player()
114 | elif not game_over:
115 | if event.key == pygame.K_UP:
116 | up = True
117 | elif event.key == pygame.K_RIGHT:
118 | right = True
119 | elif event.key == pygame.K_DOWN:
120 | bottom = True
121 | elif event.key == pygame.K_LEFT:
122 | left = True
123 | elif event.type == pygame.KEYUP:
124 | if event.key == pygame.K_UP:
125 | up = False
126 | elif event.key == pygame.K_RIGHT:
127 | right = False
128 | elif event.key == pygame.K_DOWN:
129 | bottom = False
130 | elif event.key == pygame.K_LEFT:
131 | left = False
132 |
133 | # Drawing grid
134 | for r in range(ROWS + 1):
135 | for c in range(COLS + 1):
136 | pygame.draw.circle(win, WHITE, (c * CELL_SIZE + 2 * PADDING, r * CELL_SIZE + 3 * PADDING), 2)
137 |
138 | # Update and draw cells
139 | for cell in cells:
140 | cell.update(win)
141 | if pos and cell.rect.collidepoint(pos):
142 | current_cell = cell
143 |
144 | # Drawing current selection
145 | if current_cell:
146 | index = current_cell.index
147 | if not current_cell.winner:
148 | pygame.draw.circle(win, RED, current_cell.rect.center, 2)
149 |
150 | if up and not current_cell.sides[0]:
151 | current_cell.sides[0] = True
152 | if index - ROWS >= 0:
153 | cells[index - ROWS].sides[2] = True
154 | next_turn = True
155 | if right and not current_cell.sides[1]:
156 | current_cell.sides[1] = True
157 | if (index + 1) % COLS > 0:
158 | cells[index + 1].sides[3] = True
159 | next_turn = True
160 | if bottom and not current_cell.sides[2]:
161 | current_cell.sides[2] = True
162 | if index + ROWS < len(cells):
163 | cells[index + ROWS].sides[0] = True
164 | next_turn = True
165 | if left and not current_cell.sides[3]:
166 | current_cell.sides[3] = True
167 | if (index % COLS) > 0:
168 | cells[index - 1].sides[1] = True
169 | next_turn = True
170 |
171 | # Check for win condition
172 | res = current_cell.check_win(current_player)
173 | if res:
174 | fill_count += res
175 | if current_player == 'X':
176 | p1_score += 1
177 | else:
178 | p2_score += 1
179 | if fill_count == ROWS * COLS:
180 | game_over = True
181 |
182 | # Switch players
183 | if next_turn:
184 | turn = (turn + 1) % len(players)
185 | current_player = players[turn]
186 | next_turn = False
187 |
188 | # Display scores and current player
189 | p1_img = font.render(f'{p1_score}', True, BLUE)
190 | p2_img = font.render(f'{p2_score}', True, BLUE)
191 |
192 | # Render player texts with appropriate positions
193 | p1_text = font.render('Player 1:', True, BLUE)
194 | p2_text = font.render('Player 2:', True, BLUE)
195 |
196 | # Calculate positions for player texts and scores
197 | p1_text_pos = (2 * PADDING, 15)
198 | p1_img_pos = (p1_text_pos[0] + p1_text.get_width() + 5, 15)
199 | p2_img_pos = (SCREEN_WIDTH - 2 * PADDING - p2_img.get_width(), 15)
200 | p2_text_pos = (p2_img_pos[0] - p2_text.get_width() - 5, 15)
201 |
202 | # Blit the player texts and scores
203 | win.blit(p1_text, p1_text_pos)
204 | win.blit(p1_img, p1_img_pos)
205 | win.blit(p2_text, p2_text_pos)
206 | win.blit(p2_img, p2_img_pos)
207 |
208 | # Highlight current player's turn
209 | if not game_over:
210 | if turn == 0: # Player 1's turn
211 | pygame.draw.rect(win, BLUE, (p1_text_pos[0], p1_text_pos[1] + font.get_height() + 2, p1_text.get_width() + p1_img.get_width() + 5, 2), 0)
212 | else: # Player 2's turn
213 | pygame.draw.rect(win, BLUE, (p2_text_pos[0], p2_text_pos[1] + font.get_height() + 2, p2_text.get_width() + p2_img.get_width() + 5, 2), 0)
214 |
215 | if game_over:
216 | # Display game over message
217 | overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
218 | overlay.set_alpha(200)
219 | overlay.fill(BLACK)
220 | win.blit(overlay, (0, 0))
221 | over_img = font.render('Game Over', True,WHITE )
222 | winner_img = font.render(f'Player {1 if p1_score > p2_score else 2} Won', True, GREEN)
223 | msg_img = font.render('Press R to restart, Q or ESC to quit', True, RED)
224 | win.blit(over_img, ((SCREEN_WIDTH - over_img.get_width()) / 2, 100))
225 | win.blit(winner_img, ((SCREEN_WIDTH - winner_img.get_width()) / 2, 150))
226 | win.blit(msg_img, ((SCREEN_WIDTH - msg_img.get_width()) / 2, 200))
227 |
228 | # Draw border
229 | pygame.draw.rect(win, LIGHT_GRAY, (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), 2, border_radius=10)
230 |
231 | def draw_button(text, color, x, y, action=None):
232 | mouse = pygame.mouse.get_pos()
233 | click = pygame.mouse.get_pressed()
234 |
235 | if x + button_width > mouse[0] > x and y + button_height > mouse[1] > y:
236 | pygame.draw.rect(screen, color, (x, y, button_width, button_height))
237 | if click[0] == 1 and action:
238 | action()
239 | else:
240 | pygame.draw.rect(screen, color, (x, y, button_width, button_height))
241 |
242 | text_surf = font.render(text, True, WHITE)
243 | text_rect = text_surf.get_rect(center=(x + button_width / 2, y + button_height / 2))
244 | screen.blit(text_surf, text_rect)
245 |
246 | def replay_game():
247 | main()
248 |
249 | def quit_game():
250 | pygame.quit()
251 | sys.exit()
252 |
253 | def main():
254 | clock = pygame.time.Clock()
255 | running = True
256 |
257 | while running:
258 | for event in pygame.event.get():
259 | if event.type == pygame.QUIT:
260 | pygame.quit()
261 | sys.exit()
262 |
263 | screen.fill(WHITE)
264 |
265 | # Game logic and drawing go here
266 |
267 | # Draw buttons
268 | draw_button("Replay", BLUE, SCREEN_WIDTH // 4 - button_width // 2, SCREEN_HEIGHT // 2, replay_game)
269 | draw_button("Quit", RED, 3 * SCREEN_WIDTH // 4 - button_width // 2, SCREEN_HEIGHT // 2, quit_game)
270 |
271 |
272 | pygame.display.update()
273 |
274 | pygame.quit()
275 |
276 | pygame.display.flip()
277 | clock.tick(60)
278 |
279 | if __name__ == "__main__":
280 | main()
--------------------------------------------------------------------------------
/Contributing.md:
--------------------------------------------------------------------------------
1 |
2 | # Contributing to Dots and Boxes
3 |
4 | First off, thanks for taking the time to contribute! ❤️
5 |
6 | All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉
7 |
8 | > And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
9 | > - Star the project
10 | > - Tweet about it
11 | > - Refer this project in your project's readme
12 | > - Mention the project at local meetups and tell your friends/colleagues
13 |
14 |
15 | ## Table of Contents
16 |
17 | - [I Have a Question](#i-have-a-question)
18 | - [I Want To Contribute](#i-want-to-contribute)
19 | - [Reporting Bugs](#reporting-bugs)
20 | - [Suggesting Enhancements](#suggesting-enhancements)
21 | - [Your First Code Contribution](#your-first-code-contribution)
22 | - [Improving The Documentation](#improving-the-documentation)
23 | - [Styleguides](#styleguides)
24 | - [Commit Messages](#commit-messages)
25 | - [Join The Project Team](#join-the-project-team)
26 |
27 |
28 |
29 | ## I Have a Question
30 |
31 | > If you want to ask a question, we assume that you have read the available [Documentation]().
32 |
33 | Before you ask a question, it is best to search for existing [Issues](https://github.com/shrawani21/gamer_21.git/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first.
34 |
35 | If you then still feel the need to ask a question and need clarification, we recommend the following:
36 |
37 | - Open an [Issue](https://github.com/shrawani21/gamer_21.git/issues/new).
38 | - Provide as much context as you can about what you're running into.
39 | - Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant.
40 |
41 | We will then take care of the issue as soon as possible.
42 |
43 |
57 |
58 | ## I Want To Contribute
59 |
60 | > ### Legal Notice
61 | > When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license.
62 |
63 | ### Reporting Bugs
64 |
65 |
66 | #### Before Submitting a Bug Report
67 |
68 | A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible.
69 |
70 | - Make sure that you are using the latest version.
71 | - Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](). If you are looking for support, you might want to check [this section](#i-have-a-question)).
72 | - To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/shrawani21/gamer_21.gitissues?q=label%3Abug).
73 | - Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue.
74 | - Collect information about the bug:
75 | - Stack trace (Traceback)
76 | - OS, Platform and Version (Windows, Linux, macOS, x86, ARM)
77 | - Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant.
78 | - Possibly your input and the output
79 | - Can you reliably reproduce the issue? And can you also reproduce it with older versions?
80 |
81 |
82 | #### How Do I Submit a Good Bug Report?
83 |
84 | > You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to <>.
85 |
86 |
87 | We use GitHub issues to track bugs and errors. If you run into an issue with the project:
88 |
89 | - Open an [Issue](https://github.com/shrawani21/gamer_21.git/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.)
90 | - Explain the behavior you would expect and the actual behavior.
91 | - Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case.
92 | - Provide the information you collected in the previous section.
93 |
94 | Once it's filed:
95 |
96 | - The project team will label the issue accordingly.
97 | - A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced.
98 | - If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution).
99 |
100 |
101 |
102 |
103 | ### Suggesting Enhancements
104 |
105 | This section guides you through submitting an enhancement suggestion for Dots and Boxes, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions.
106 |
107 |
108 | #### Before Submitting an Enhancement
109 |
110 | - Make sure that you are using the latest version.
111 | - Read the [documentation]() carefully and find out if the functionality is already covered, maybe by an individual configuration.
112 | - Perform a [search](https://github.com/shrawani21/gamer_21.git/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
113 | - Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library.
114 |
115 |
116 | #### How Do I Submit a Good Enhancement Suggestion?
117 |
118 | Enhancement suggestions are tracked as [GitHub issues](https://github.com/shrawani21/gamer_21.git/issues).
119 |
120 | - Use a **clear and descriptive title** for the issue to identify the suggestion.
121 | - Provide a **step-by-step description of the suggested enhancement** in as many details as possible.
122 | - **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you.
123 | - You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux.
124 | - **Explain why this enhancement would be useful** to most Dots and Boxes users. You may also want to point out the other projects that solved it better and which could serve as inspiration.
125 |
126 |
127 |
128 | ### Your First Code Contribution
129 |
133 | To get started with your first code contribution, follow these steps:
134 |
135 | 1. **Fork the Repository:** Go to the GitHub page of the project and fork the repository to your account.
136 | 2. **Clone the Repository:** Clone your forked repository to your local machine using:
137 | ```
138 | git clone https://github.com/shrawani21/gamer_21.git
139 | ```
140 | 3. **Navigate to the Project Directory:**
141 | ```
142 | cd gamer_21
143 | ```
144 | 4. **Install Dependencies:** Make sure you have node and npm installed. Install the required dependencies by running:
145 | ```
146 | npm install
147 | ```
148 | 5. **Create a Branch:** Create a new branch to work on your contribution:
149 | ```
150 | git checkout -b my-contribution
151 | ```
152 |
153 | ### Make Your Changes
154 | Now you're ready to make your changes to the codebase. Make sure to follow any relevant styleguides and coding conventions.
155 | ### Test Your Changes
156 | Before submitting your contribution, make sure to test your changes thoroughly. Ensure that they work as expected and haven't introduced any errors.
157 | ### Commit Your Changes
158 | Once you're satisfied with your changes, commit them to your branch:
159 | ```
160 | git add .
161 | git commit -m "Add your commit message here"
162 | ```
163 | ### Push Your Changes
164 | Push your changes to your forked repository:
165 | ```
166 | git push origin my-contribution
167 | ```
168 | ### Open A Pull Request
169 | Finally, open a pull request from your forked repository to the main repository. Provide a clear description of your changes and why they're necessary. The project admins review your contribution and merge it if everything looks good!
170 | ### Improving The Documentation
171 | Improving documentation is a valuable contribution to any project. To improve the documentation for Dots and Boxes, follow these steps:
172 |
173 | 1. **Identify Areas for Improvement:** Look for sections of the documentation that are unclear, outdated, or missing important information.
174 | 2. **Make Your Changes:** Make the necessary changes to the documentation files. Ensure that your changes are clear, concise, and follow any existing styleguides.
175 | 3. **Test Your Changes:** After making your changes, test them to ensure that they accurately reflect the project and are helpful to users.
176 | 4. **Commit Your Changes:** Commit your changes with a clear and descriptive commit message:
177 | ```
178 | git add .
179 | git commit -m "Improve documentation: [brief description of changes]"
180 | ```
181 | 5. **Push Your Changes:** Push your changes to your forked repository:
182 | ```
183 | git push origin my-documentation-improvements
184 | ```
185 | 6.**Open a Pull Request:** Open a pull request from your forked repository to the main repository. Provide a clear description of your changes and why they're necessary. The project admins will review your contribution and merge it if everything looks good!
186 |
190 |
191 | ## Styleguides
192 | ### Commit Messages
193 |
196 |
197 | ## Join The Project Team
198 |
199 |
200 |
--------------------------------------------------------------------------------
/player.py:
--------------------------------------------------------------------------------
1 | import random
2 | from typing import List, Dict, Optional
3 | from box import Box
4 |
5 | def get_line_boxes(matrix: List[List[Box]], line: List[tuple[int, int]]) -> List[Box]:
6 | """Returns the boxes adjacent to a given line."""
7 | p1, p2 = line
8 | boxes = []
9 | if p1[0] == p2[0]: # horizontal
10 | pos1 = min(p1, p2, key=lambda x: x[1])
11 | if pos1[0] > 0:
12 | box_top = matrix[pos1[0] - 1][pos1[1]]
13 | boxes.append(box_top)
14 | if pos1[0] < len(matrix):
15 | box_bottom = matrix[pos1[0]][pos1[1]]
16 | boxes.append(box_bottom)
17 | else: # vertical
18 | pos1 = min(p1, p2, key=lambda x: x[0])
19 | if pos1[1] > 0:
20 | box_left = matrix[pos1[0]][pos1[1] - 1]
21 | boxes.append(box_left)
22 | if pos1[1] < len(matrix[0]):
23 | box_right = matrix[pos1[0]][pos1[1]]
24 | boxes.append(box_right)
25 | return boxes
26 |
27 | def get_adjacent_boxes(matrix: List[List[Box]], box: Box) -> Dict[str, Optional[Box]]:
28 | """Returns the boxes adjacent to a given box."""
29 | boxes = {'top': None, 'bottom': None, 'left': None, 'right': None}
30 | if box.idx[0] > 0:
31 | boxes['top'] = matrix[box.idx[0] - 1][box.idx[1]]
32 | if box.idx[0] < len(matrix) - 1:
33 | boxes['bottom'] = matrix[box.idx[0] + 1][box.idx[1]]
34 | if box.idx[1] > 0:
35 | boxes['left'] = matrix[box.idx[0]][box.idx[1] - 1]
36 | if box.idx[1] < len(matrix[0]) - 1:
37 | boxes['right'] = matrix[box.idx[0]][box.idx[1] + 1]
38 | return boxes
39 |
40 | def count_adjacent_boxes(matrix: List[List[Box]], box: Box) -> int:
41 | """Returns the number of adjacent boxes around a given box."""
42 | count = 0
43 | if box.idx[0] > 0:
44 | count += 1
45 | if box.idx[0] < len(matrix) - 1:
46 | count += 1
47 | if box.idx[1] > 0:
48 | count += 1
49 | if box.idx[1] < len(matrix[0]) - 1:
50 | count += 1
51 | return count
52 |
53 | def get_random_empty_side(box: Box, exclude: Optional[tuple[int, int]] = None) -> Optional[tuple[int, int]]:
54 | """Returns a random empty side of a given box."""
55 | choices = []
56 | if box.top is None and (exclude is None or box.top_idx() != exclude):
57 | choices.append(box.top_idx())
58 | if box.bottom is None and (exclude is None or box.bottom_idx() != exclude):
59 | choices.append(box.bottom_idx())
60 | if box.left is None and (exclude is None or box.left_idx() != exclude):
61 | choices.append(box.left_idx())
62 | if box.right is None and (exclude is None or box.right_idx() != exclude):
63 | choices.append(box.right_idx())
64 | return random.choice(choices) if choices else None
65 |
66 | def get_side_counts(matrix: List[List[Box]], box: Box) -> Dict[str, Optional[int]]:
67 | """Returns the number of sides occupied around a given box."""
68 | sides = {'top': None, 'bottom': None, 'left': None, 'right': None}
69 | if box.idx[0] > 0:
70 | sides['top'] = matrix[box.idx[0] - 1][box.idx[1]].sides
71 | if box.idx[0] < len(matrix) - 1:
72 | sides['bottom'] = matrix[box.idx[0] + 1][box.idx[1]].sides
73 | if box.idx[1] > 0:
74 | sides['left'] = matrix[box.idx[0]][box.idx[1] - 1].sides
75 | if box.idx[1] < len(matrix[0]) - 1:
76 | sides['right'] = matrix[box.idx[0]][box.idx[1] + 1].sides
77 | return sides
78 |
79 | def is_side_less_than(matrix: List[List[Box]], box: Box, side: str, num: int) -> bool:
80 | """Checks if the sides around a given box are less than a specified number."""
81 | sides = get_side_counts(matrix, box)[side]
82 | return sides is None or sides < num
83 |
84 | def is_facing_outside(matrix: List[List[Box]], box: Box) -> bool:
85 | """Checks if a given box is facing the outside of the matrix."""
86 | if box.idx[0] == 0 and box.top is None:
87 | return True
88 | if box.idx[0] == len(matrix) - 1 and box.bottom is None:
89 | return True
90 | if box.idx[1] == 0 and box.left is None:
91 | return True
92 | if box.idx[1] == len(matrix[0]) - 1 and box.right is None:
93 | return True
94 | return False
95 |
96 | def easy_strategy(matrix: List[List[Box]], prev_line: Optional[List[tuple[int, int]]]) -> Optional[tuple[int, int]]:
97 | """Returns a move for easy difficulty."""
98 | if prev_line:
99 | for prev_box in get_line_boxes(matrix, prev_line):
100 | if prev_box.sides == 3:
101 | return get_random_empty_side(prev_box)
102 |
103 | boxes = Box.ALL_BOXES
104 | box0 = [box for box in boxes if box.sides == 0]
105 | box1 = [box for box in boxes if box.sides == 1]
106 | box2 = [box for box in boxes if box.sides == 2]
107 | box3 = [box for box in boxes if box.sides == 3]
108 |
109 | if box3:
110 | return get_random_empty_side(random.choice(box3))
111 | if box0:
112 | return get_random_empty_side(random.choice(box0))
113 | if box1:
114 | return get_random_empty_side(random.choice(box1))
115 | if box2:
116 | return get_random_empty_side(random.choice(box2))
117 |
118 | def medium_strategy(matrix: List[List[Box]], prev_line: Optional[List[tuple[int, int]]]) -> Optional[tuple[int, int]]:
119 | """Returns a move for medium difficulty."""
120 | if prev_line:
121 | for prev_box in get_line_boxes(matrix, prev_line):
122 | if prev_box.sides == 3:
123 | return get_random_empty_side(prev_box)
124 |
125 | boxes = Box.ALL_BOXES
126 | box0 = [box for box in boxes if box.sides == 0]
127 | box1 = [box for box in boxes if box.sides == 1]
128 | box2 = [box for box in boxes if box.sides == 2]
129 | box3 = [box for box in boxes if box.sides == 3]
130 |
131 | box_less2 = box0 + box1
132 |
133 | if box3:
134 | return get_random_empty_side(random.choice(box3))
135 |
136 | sides_to_check = ['top', 'bottom', 'left', 'right']
137 | choices = []
138 | for side in sides_to_check:
139 | choices.extend([
140 | getattr(box, f"{side}_idx")()
141 | for box in box_less2 if is_side_less_than(matrix, box, side, 2)
142 | ])
143 | if choices:
144 | return random.choice(choices)
145 |
146 | if box0:
147 | return get_random_empty_side(random.choice(box0))
148 | if box1:
149 | return get_random_empty_side(random.choice(box1))
150 | if box2:
151 | return get_random_empty_side(random.choice(box2))
152 |
153 | def hard_strategy(matrix: List[List[Box]], prev_line: Optional[List[tuple[int, int]]]) -> Optional[tuple[int, int]]:
154 | """Returns a move for hard difficulty."""
155 | if prev_line:
156 | for prev_box in get_line_boxes(matrix, prev_line):
157 | if prev_box.sides == 3:
158 | return get_random_empty_side(prev_box)
159 |
160 | boxes = Box.ALL_BOXES
161 | box0 = [box for box in boxes if box.sides == 0]
162 | box1 = [box for box in boxes if box.sides == 1]
163 | box3 = [box for box in boxes if box.sides == 3]
164 |
165 | if box3:
166 | return get_random_empty_side(random.choice(box3))
167 |
168 | box_less2 = box0 + box1
169 |
170 | sides_to_check = ['top', 'bottom', 'left', 'right']
171 | choices = []
172 | for side in sides_to_check:
173 | choices.extend([
174 | getattr(box, f"{side}_idx")()
175 | for box in box_less2 if is_side_less_than(matrix, box, side, 2)
176 | ])
177 | if choices:
178 | return random.choice(choices)
179 |
180 | chains = []
181 | checked = []
182 | crosses = []
183 | options = boxes.copy()
184 | while len(checked) < len(boxes):
185 | current = [options[0]]
186 | if current[0].color is not None:
187 | checked.append(current[0])
188 | options.remove(current[0])
189 | continue
190 | if current[0].sides < 2:
191 | crosses.append(current[0])
192 | checked.append(current[0])
193 | options.remove(current[0])
194 | continue
195 | new_chain = []
196 | chain = []
197 | while current:
198 | for box in current:
199 | checked.append(box)
200 | chain.append(box)
201 | options.remove(box)
202 | for direction in ['top', 'bottom', 'left', 'right']:
203 | adj_box = get_adjacent_boxes(matrix, box)[direction]
204 | if getattr(box, direction) is None and adj_box and adj_box not in new_chain and adj_box not in chain:
205 | if adj_box.sides >= 2:
206 | new_chain.append(adj_box)
207 | current = new_chain
208 | new_chain = []
209 | chains.append(chain)
210 |
211 | sorted_chains = sorted(chains, key=len)
212 | if sorted_chains:
213 | return get_random_empty_side(random.choice(sorted_chains[0]))
214 |
215 | return get_random_empty_side(random.choice(crosses))
216 |
217 | def extreme_strategy(matrix: List[List[Box]], prev_line: Optional[List[tuple[int, int]]]) -> Optional[tuple[int, int]]:
218 | """Returns a move for extreme difficulty."""
219 | boxes = Box.ALL_BOXES
220 | box0 = [box for box in boxes if box.sides == 0]
221 | box1 = [box for box in boxes if box.sides == 1]
222 | box3 = [box for box in boxes if box.sides == 3]
223 |
224 | box_less2 = box0 + box1
225 |
226 | sides_to_check = ['top', 'bottom', 'left', 'right']
227 | choices = []
228 | for side in sides_to_check:
229 | choices.extend([
230 | getattr(box, f"{side}_idx")()
231 | for box in box_less2 if is_side_less_than(matrix, box, side, 2)
232 | ])
233 |
234 | chains = []
235 | checked = []
236 | crosses = []
237 | options = boxes.copy()
238 | while len(checked) < len(boxes):
239 | current = [options[0]]
240 | if current[0].color is not None:
241 | checked.append(current[0])
242 | options.remove(current[0])
243 | continue
244 | if current[0].sides < 2:
245 | crosses.append(current[0])
246 | checked.append(current[0])
247 | options.remove(current[0])
248 | continue
249 | new_chain = []
250 | chain = []
251 | while current:
252 | for box in current:
253 | checked.append(box)
254 | chain.append(box)
255 | options.remove(box)
256 | for direction in ['top', 'bottom', 'left', 'right']:
257 | adj_box = get_adjacent_boxes(matrix, box)[direction]
258 | if getattr(box, direction) is None and adj_box and adj_box not in new_chain and adj_box not in chain:
259 | if adj_box.sides >= 2:
260 | new_chain.append(adj_box)
261 | current = new_chain
262 | new_chain = []
263 | chains.append(chain)
264 |
265 | sorted_chains = sorted(chains, key=len)
266 |
267 | if prev_line:
268 | for prev_box in get_line_boxes(matrix, prev_line):
269 | if prev_box.sides == 3:
270 | side = get_random_empty_side(prev_box)
271 | if not choices and len(sorted_chains) > 1:
272 | if len(sorted_chains[1]) > 2 and len(box3) < 2:
273 | side_boxes = get_line_boxes(matrix, side)
274 | for box in side_boxes:
275 | if box != prev_box and count_adjacent_boxes(matrix, box) < 4 and is_facing_outside(matrix, box):
276 | return get_random_empty_side(box, exclude=side)
277 | return side
278 |
279 | if box3:
280 | selected_box = random.choice(box3)
281 | side = get_random_empty_side(selected_box)
282 | if not choices and len(sorted_chains) > 1:
283 | if len(sorted_chains[1]) > 2 and len(box3) < 2:
284 | side_boxes = get_line_boxes(matrix, side)
285 | for box in side_boxes:
286 | if box != selected_box and count_adjacent_boxes(matrix, box) < 4 and is_facing_outside(matrix, box):
287 | return get_random_empty_side(box, exclude=side)
288 | return side
289 |
290 | if choices:
291 | return random.choice(choices)
292 |
293 | if sorted_chains:
294 | return get_random_empty_side(random.choice(sorted_chains[0]))
295 |
296 | return get_random_empty_side(random.choice(crosses))
297 |
298 | def expert_strategy(matrix: List[List[Box]], prev_line: Optional[List[tuple[int, int]]]) -> Optional[tuple[int, int]]:
299 | """Returns a move for expert difficulty. (To be implemented)"""
300 | pass
301 |
302 | class Player:
303 | def __init__(self, player_type: str, color: str, difficulty: int = 1):
304 | self.player_type = player_type
305 | self.score = 0
306 | self.color = color
307 | self.move = None
308 | self.difficulty = difficulty
309 |
310 | def get_move(self, matrix: List[List[Box]], prev_line: Optional[List[tuple[int, int]]]) -> Optional[tuple[int, int]]:
311 | if self.player_type == 'human':
312 | move = self.move
313 | self.move = None
314 | return move
315 |
316 | strategy_funcs = {
317 | 1: easy_strategy,
318 | 2: medium_strategy,
319 | 3: hard_strategy,
320 | 4: extreme_strategy,
321 | 5: expert_strategy # Placeholder for future implementation
322 | }
323 | return strategy_funcs[self.difficulty](matrix, prev_line)
324 |
--------------------------------------------------------------------------------