Last active
May 9, 2025 02:19
-
-
Save skrungly/0c33c46a0dc041617ed3d60484e8dcd8 to your computer and use it in GitHub Desktop.
code to generate a simple tic-tac-toe script :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
INTRO_SEGMENT = """\ | |
print('| welcome to my simple tic-tac-toe game!') | |
print('| take your turn by choosing a tile [1-9].')\n | |
""" | |
GRID_SEGMENT = """\ | |
print('\\n| {0} | {1} | {2} |') | |
print('| {3} | {4} | {5} |') | |
print('| {6} | {7} | {8} |\\n') | |
""" | |
INPUT_SEGMENT = """ | |
choice = None | |
while choice not in {choices}: | |
choice = input('| {player} to play: ') | |
""" | |
# here are all triplets of indices to check for a won game. | |
# for any given triplet, if all three tiles match a | |
# player (either X or O) then that player has won. | |
WINNING_ARRANGEMENTS = ( | |
# horizontal lines | |
(0, 1, 2), | |
(3, 4, 5), | |
(6, 7, 8), | |
# vertical lines | |
(0, 3, 6), | |
(1, 4, 7), | |
(2, 5, 8), | |
# diagonal lines | |
(0, 4, 8), | |
(2, 4, 6), | |
) | |
def check_for_winner(tiles): | |
for (i, j, k) in WINNING_ARRANGEMENTS: | |
if tiles[i] == tiles[j] == tiles[k]: | |
return tiles[i] | |
def write_segment(segment, depth, file): | |
indent = " " * depth | |
for line in segment.splitlines(): | |
if line.strip(): | |
file.write(indent) | |
file.write(line) | |
file.write("\n") | |
def generate_turn(depth, tiles, choices, file): | |
write_segment(GRID_SEGMENT.format(*tiles), depth, file) | |
winner = check_for_winner(tiles) | |
if winner in ("X", "O"): | |
write_segment(f"\nprint('| {winner} wins!')", depth, file) | |
return | |
if not choices: | |
write_segment("\nprint('| we have a draw!')", depth, file) | |
return | |
player = "XO"[depth % 2] | |
segment = INPUT_SEGMENT.format( | |
choices=str(choices), | |
player=player | |
) | |
write_segment(segment, depth, file) | |
for index, choice in enumerate(choices): | |
expr = "if" if index == 0 else "elif" | |
write_segment(f"\n{expr} choice == '{choice}':", depth, file) | |
new_tiles = tiles.copy() | |
new_tiles[int(choice) - 1] = player | |
new_choices = tuple(c for c in choices if c != choice) | |
generate_turn(depth + 1, new_tiles, new_choices, file) | |
def generate_code(script_name): | |
tiles = list("_" * 9) | |
choices = tuple("123456789") | |
with open(script_name, "w") as script: | |
write_segment(INTRO_SEGMENT, depth=0, file=script) | |
generate_turn(0, tiles, choices, script) | |
if __name__ == "__main__": | |
generate_code("tictactoe.py") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment