Skip to content

Instantly share code, notes, and snippets.

@mythmon
Created June 20, 2013 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mythmon/5825406 to your computer and use it in GitHub Desktop.
Save mythmon/5825406 to your computer and use it in GitHub Desktop.
import time
import random
import sys
from copy import deepcopy
from blessings import Terminal
WIDTH = 6
HEIGHT = 4
board = [[True for _ in range(WIDTH)] for _ in range(HEIGHT)]
term = Terminal()
def main():
while True:
draw_board()
if not board[0][0]:
print('You won!')
return
move = human_turn()
make_move(board, *move)
draw_board()
if move == (0, 0):
print('You lost.')
return
ai_turn(board)
def draw_board():
offset_x, offset_y = 5, 5
step_x, step_y = 2, 2
for y, row in enumerate(board):
for x, cell in enumerate(row):
# print(term.move(screen_y, screen_x))
if x == 0 and y == 0:
color = term.bold_red
else:
color = term.bold_white if cell else term.white
print(color('o' if cell else '.'), end='')
print()
def human_turn():
while True:
try:
coord = input('Your Move: ')
except (EOFError, KeyboardInterrupt):
# That's ok, the user hit ctrl+c
sys.exit()
x, y = map(int, coord.split(' '))
if x >= WIDTH or y >= HEIGHT or not board[y][x]:
print("That isn't valid")
else:
return x, y
def ai_turn(b, d=0):
move = (0, 0)
def ai_make_move(b, real=False):
make_move(b, *move)
if real:
print("I'm moving at {} {}".format(*move))
for x in range(WIDTH):
for y in range(HEIGHT):
# If there is a takeable bit here, and it is not poison
if b[y][x] and (x > 0 or y > 0):
move = (x, y)
board_copy = deepcopy(b)
ai_make_move(board_copy)
if ai_turn(board_copy, d + 1):
continue
if d == 0:
ai_make_move(b, True)
print("I'm going to win. :)")
return True
# No winning moves :(
if d == 0:
moves = set()
for x in range(WIDTH):
for y in range(HEIGHT):
if (x, y) > (0, 0) and b[y][x]:
moves.add((x, y))
move = random.choice(moves)
ai_make_move(b, True)
return False
def make_move(b, x, y):
for xp in range(x, WIDTH):
for yp in range(y, HEIGHT):
b[yp][xp] = False
if __name__ == '__main__':
main()
# with term.fullscreen():
# main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment