Random Board Game Selection Using Board Game Geek
Using Board Game Geek’s API I wanted to create a simple Python tool for randomly picking a game to play. Below is some quick Python code to achieve my goal:
from urllib2 import urlopen
from lxml import etree
from random import choice
def get_xml():
req = urlopen('http://www.boardgamegeek.com/xmlapi/collection/flip387')
return req
def get_items():
xml = etree.parse(get_xml())
return xml.xpath('//item')
def get_thumbnail(item):
t = item.xpath('thumbnail')
if len(t) == 1:
return t[0].text
def get_name(item):
t = item.xpath('name')
if len(t) == 1:
return t[0].text
def get_stats(item):
t = item.xpath('stats')
if len(t) == 1:
return dict(t[0].items())
def get_minplayers(item):
return get_stats(item).get('minplayers')
def get_maxplayers(item):
return get_stats(item).get('maxplayers')
def get_playingtime(item):
return get_stats(item).get('playingtime')
def get_as_dict(item):
return dict(
name=get_name(item),
thumbnail=get_thumbnail(item),
minplayers=get_minplayers(item),
maxplayers=get_maxplayers(item),
playingtime=get_playingtime(item)
)
def get_games():
items = get_items()
return [get_as_dict(i) for i in items]
def get_random_game():
games = get_games()
return choice(games)
And using this would work like so:
In [1]: get_random_game()
Out[1]:
{'maxplayers': '6',
'minplayers': '1',
'name': 'Castle Panic',
'playingtime': '60',
'thumbnail': 'http://cf.geekdo-images.com/images/pic496923_t.jpg'}
In [2]: get_random_game()
Out[2]:
{'maxplayers': '6',
'minplayers': '3',
'name': 'Munchkin Pathfinder',
'playingtime': '90',
'thumbnail': 'http://cf.geekdo-images.com/images/pic1641599_t.jpg'}