Skip to content

Commit ceff566

Browse files
Bug/dots boxes (#759)
* docs: update contributor gallery [skip ci] * docs: update contributor gallery [skip ci] * Fix Game crashes with index out of range error for invalid row/column input --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
1 parent 4a5a4cc commit ceff566

1 file changed

Lines changed: 24 additions & 23 deletions

File tree

games/Dots-Boxes-AI/Dots-Boxes-AI.py

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
# Title
1515
print(BOLD + CYAN)
1616
print("=" * 70)
17-
print("🔲 DOTS & BOXES AI - ADVANCED VERSION 🔲")
17+
print("🔲 DOTS & BOXES AI - ADVANCED VERSION 🔲")
1818
print("=" * 70)
1919
print(RESET)
2020

@@ -266,32 +266,33 @@ def ai_move():
266266
print(RED + "❌ Invalid direction!" + RESET)
267267
continue
268268

269-
row = input("📍 Enter row: ")
270-
col = input("📍 Enter column: ")
269+
row_in = input("📍 Enter row: ")
270+
col_in = input("📍 Enter column: ")
271271

272-
if not row.isdigit() or not col.isdigit():
273-
print(RED + "❌ Invalid position!" + RESET)
272+
# Check if empty, or starts with a negative sign, or isn't numeric
273+
if not row_in.strip() or not col_in.strip() or '-' in row_in or '-' in col_in or not row_in.isdigit() or not col_in.isdigit():
274+
print(RED + "❌ Invalid input! Rows and columns must be positive numbers." + RESET)
274275
continue
275276

276-
row, col = int(row), int(col)
277+
row, col = int(row_in), int(col_in)
277278

278-
try:
279-
if direction == 'h':
280-
if horizontal_lines[row][col]:
281-
print(YELLOW + "⚠️ Line already taken!" + RESET)
282-
continue
283-
horizontal_lines[row][col] = True
284-
else:
285-
if vertical_lines[row][col]:
286-
print(YELLOW + "⚠️ Line already taken!" + RESET)
287-
continue
288-
vertical_lines[row][col] = True
289-
except IndexError:
290-
print(RED + "❌ Position out of range!" + RESET)
291-
continue
292-
except ValueError:
293-
print(RED + "❌ Invalid input!" + RESET)
294-
continue
279+
# Explicit Boundaries Check Before Modifying Array
280+
if direction == 'h':
281+
if row < 0 or row >= (size + 1) or col < 0 or col >= size:
282+
print(RED + f"❌ Position out of range! For 'h', Row must be 0-{size} and Col must be 0-{size-1}." + RESET)
283+
continue
284+
if horizontal_lines[row][col]:
285+
print(YELLOW + "⚠️ Line already taken!" + RESET)
286+
continue
287+
horizontal_lines[row][col] = True
288+
else:
289+
if row < 0 or row >= size or col < 0 or col >= (size + 1):
290+
print(RED + f"❌ Position out of range! For 'v', Row must be 0-{size-1} and Col must be 0-{size}." + RESET)
291+
continue
292+
if vertical_lines[row][col]:
293+
print(YELLOW + "⚠️ Line already taken!" + RESET)
294+
continue
295+
vertical_lines[row][col] = True
295296

296297
symbol = 'P' if current_player == 1 else 'A'
297298
got_box = check_boxes(symbol)

0 commit comments

Comments
 (0)