Added creation help and listing functions started play

This commit is contained in:
sloumdrone 2018-12-29 14:54:13 -08:00
parent 4268d7125a
commit 7706647f9a
1 changed files with 130 additions and 11 deletions

View File

@ -6,34 +6,131 @@ import os
import subprocess
import json
version = '0.2.0'
version = '0.2.2'
home_folder = os.path.expanduser('~')
username = os.path.split(home_folder)[-1]
database = '/var/lib/oberon/oberon.sqlite'
def print_header():
print('\nO B E R O N v{}\n'.format(version))
def create_game(enemy):
enemies = get_user_list()
enemies = ['test', 'sloum'] #delete this test data
# create guard clause to prevent play against self and refer to single player game
if not enemy in enemies:
print('There is no avialable player with the name {}.\nGame not created.'.format(enemy))
return False
game_board = [[' · ' for y in range(15)] for x in range(15)]
q = "INSERT INTO games VALUES (?, ?, ?, ?, ?, ?, ?)"
v = (username, enemy, 'gomoku', 'playing', json.dumps(game_board), 1, None)
res = db_do(q, v, True)
if res:
print('Game between {} and {} created!'.format(username, enemy))
return True
return False
def update_board():
pass
def play_game(gid):
pass
q = "SELECT rowid, p1, p2, game_board, turn FROM games WHERE rowid = ?"
v = (gid,)
res = db_do(q,v)
if not res:
print('Invalid game id')
return False
board = json.loads(res[0][3])
pturn = res[0][2] if res[0][4] % 2 == 0 else res[0][1]
print_header()
print('{} vs. {}: {}\'s turn'.format(res[0][1], res[0][2], pturn))
print_board(board)
if not pturn == username:
print('\nIt is your opponents turn.\n')
return True
print('Enter your move as row-column.\nFor example: 4-10\nType "q" to cancel and play another time.\nType "f" to forfeit.')
while True:
move = input('> ')
if move in ['q', 'quit', 'exit']:
return True
elif move == 'f':
while True:
verify = input('Are you sure (y/n)? ')
if verify in ['y', 'yes']:
# Change game to over
# make opponent the winner
return True
elif verify in ['n', 'no']:
continue
else:
move = move.split('-')
if not len(move) == 2:
print('Invalid entry!')
continue
try:
row = int(move[0])
col = int(move[1])
except ValueError:
print('Invalid entry!')
continue
valid_move = update_board(row, col, board)
if not valid_move:
print('Invalid entry!')
continue
update_board(row, col, board)
if check_win_state(row, col):
print('You have won!')
break
print('Your move has been placed.')
return True
def print_board(gb):
print('\n\n 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15')
for i, x in enumerate(gb):
output_row = str(i + 1) + ''.join(x)
print('{}{}'.format(' ' if i + 1 < 10 else '', output_row))
print('')
def show_game_record():
pass
def list_games():
pass
q = "SELECT rowid, p1, p2, game_type, game_status FROM games WHERE winner is NULL and (p1 = ? or p2 = ?)"
v = (username, username)
res = db_do(q, v)
if res == False:
print('Database error. Contact the sysadmin or try another time.')
return False
print_header()
print('{:^8} {:^10} {:^10} {:^12}'.format('ID', 'Player 1', 'Player 2', 'Game Status'))
print('-------- ---------- ---------- ------------')
for x in res:
print("{:^8} {:^10} {:^10} {:^12}".format(x[0], x[1], x[2] or '-', x[4]))
if not len(res):
print('There are no open games')
print('')
return True
def display_help():
print('O B E R O N\nv{}'.format(version))
print_header()
print('syntax: oberon [command [option]]\n')
print('{:25} {}'.format('help','display this message'))
print('{:25} {}'.format('list', 'display your currently open games'))
print('{:25} {}'.format('history', 'display your win/loss record'))
print('{:25} {}'.format('create [user]', 'create a game against the user provided'))
print('{:25} {}'.format('play [game_id]', 'make a move or view the board for the game id provided'))
print('')
def parse_args():
@ -44,8 +141,10 @@ def parse_args():
sys.exit(1)
if arg_len == 2:
if args[1] == 'list':
list_games()
sys.exit(0)
l = list_games()
if l:
sys.exit(0)
sys.exit(1)
elif args[1] == 'history':
show_game_record()
sys.exit(0)
@ -63,12 +162,9 @@ def parse_args():
sys.exit(1)
elif arg_len == 3:
if args[1] == 'create':
if args[2] in get_user_list():
create_game(args[2])
if create_game(args[2]):
sys.exit(0)
else:
print('User "{}" does not exist.'.format(args[2]))
sys.exit(1)
sys.exit(1)
elif args[1] == 'play':
try:
game_id = int(args[2])
@ -105,6 +201,29 @@ def check_and_build_db(db_path):
conn.close()
def db_do(query, var=False, noresval=False):
global messages
db_path = database
if os.path.isfile(db_path):
conn = sql.connect(db_path)
c = conn.cursor()
if var:
c.execute(query, var)
else:
c.execute(query)
if noresval:
out = c.rowcount
else:
out = []
for row in c:
out.append(row)
conn.commit()
conn.close()
return out
else:
return False
if __name__ == '__main__':
check_and_build_db(database)
parse_args()