Ejemplo n.º 1
0
def test_guess(inputs):
    game = Game()
    assert game.guess() == 11
    assert game.guess() == 12
    # as bob is a string
    with pytest.raises(ValueError):
        game.guess()
    # as 12 was already tried
    with pytest.raises(ValueError):
        game.guess()
    assert game.guess() == 5
    # -1 is not valid
    with pytest.raises(ValueError):
        game.guess()
Ejemplo n.º 2
0
def test_is_command_validated():
    map = Map(11, 7)
    map.load_from_file("resources/map3.txt")

    commands = [
        Command("id1", "DISH-BLUEBERRIES-ICE_CREAM", 10),
        Command("id2", "DISH-ICE_CREAM-CHOPPED_STRAWBERRIES", 20),
        Command("id3", "DISH-CROISSANT-ICE_CREAM-CHOPPED_STRAWBERRIES", 100),
        Command("id4", "DISH-BLUEBERRIES-CROISSANT", 30),
        Command("id5", "DISH-CROISSANT-CHOPPED_STRAWBERRIES", 50),
        Command("id6", "DISH-TART-CHOPPED_STRAWBERRIES", 300)
    ]
    game = Game(map, 6, commands)
    game.current_commands = [
        Command("id1", "DISH-BLUEBERRIES-ICE_CREAM", 10),
        Command("id3", "DISH-CROISSANT-ICE_CREAM-CHOPPED_STRAWBERRIES", 100),
        Command("id5", "DISH-CROISSANT-CHOPPED_STRAWBERRIES", 50)
    ]

    game.get_better_command()
    assert not game.is_command_validated()

    game.current_commands = [
        Command("id1", "DISH-BLUEBERRIES-ICE_CREAM", 10),
        Command("id5", "DISH-CROISSANT-CHOPPED_STRAWBERRIES", 50)
    ]

    assert game.is_command_validated()
Ejemplo n.º 3
0
def test_make():
    map = Map(11, 7)
    map.load_from_file("resources/map3.txt")

    commands = [
        Command("id1", "DISH-BLUEBERRIES-ICE_CREAM", 10)
    ]
    game = Game(map, 1, commands)

    orders = game.make(Dessert("CROISSANT"))
    assert len(orders) == 5

    orders = game.make(Dessert("CHOPPED_STRAWBERRIES"))
    assert len(orders) == 3
Ejemplo n.º 4
0
def test_get_better_command():
    commands = [
        Command("id1", "DISH-BLUEBERRIES-ICE_CREAM", 10),
        Command("id2", "DISH-BLUEBERRIES-ICE_CREAM", 5),
        Command("id3", "DISH-BLUEBERRIES-ICE_CREAM", 20),
        Command("id4", "DISH-BLUEBERRIES-ICE_CREAM", 3),
        Command("id5", "DISH-BLUEBERRIES-ICE_CREAM", 15),
    ]
    game = Game(None, 5, commands)
    game.current_commands = commands[0:3]

    better_command = game.get_better_command()

    assert better_command.id == "id3"
Ejemplo n.º 5
0
	def setUp(self):
		self.WP = WikiPage()
		self.User = User(usersDB) ##not testing user yet
		self.Game = Game(self.WP, self.User)


		"""Tests for WikiPage Class"""
Ejemplo n.º 6
0
def display_page(pathname):
    if pathname == '/app.py':
        return Game()
    elif pathname == '/finish.py':
        return Finish()
    else:
        return Home()
Ejemplo n.º 7
0
def addGame():
    if request.method == 'POST':
        title = request.form['title']
        publisher = request.form['publisher']
        developer = request.form['developer']
        description = request.form['description']

        error = None

        if not title:
            error = "Title is required"
        elif not publisher:
            error = "Publisher is required"
        elif not developer:
            error = "Developer is required"
        elif not description:
            error = "Description is required"

        if error is None:
            game = Game(title=title,
                        publisher=publisher,
                        developer=developer,
                        description=description)
            db.session.add(game)
            db.session.commit()
            return redirect(url_for('admin.viewGames'))

    return render_template('admin/game_form.html')
Ejemplo n.º 8
0
def game_info():
    print "Getting game info"
    try:
        game_id = request.args.get('game_id')
        return jsonify({
            'data': Game.get_by_key(game_id).serialize_objectives(),
            'status': 200
        })
    except:
        return getErrorJson(sys.exc_info())
Ejemplo n.º 9
0
def disconnect():
    player = Player.get_by_id(request.sid)
    if player:
        print player.name, "disconnected.", request.sid
        if player.active:
            game = Game.get_by_key(player.game_key)
            print "Deactivating player"
            game.deactivate_player(player)
    else:
        print "Someone disconnected", request.sid
Ejemplo n.º 10
0
def test_game_win(input, capfd):
    game = Game()
    game._answer = 6

    game()

    # it ran the game with every input item and afterwards checked if win had been set to true
    assert game._win is True

    out = capfd.readouterr()[0]
    expected = [
        '4 is too low', 'Number not in range', '9 is too high',
        'Already guessed', '6 is correct!', 'It took you 3 guesses'
    ]
    # remove any new lines or blank outputs
    output = [line.strip() for line in out.split('\n') if line.strip()]

    # zip will allow code to iterate through both lists at once so can compare both first items, second items etc with each other
    for line, expected_output in zip(output, expected):
        assert line == expected_output
Ejemplo n.º 11
0
def rank():
    player = Player.get_by_id(request.sid)
    print player.name, "requested its rank."

    game = Game.get_by_key(player.game_key)
    rank = game.get_player_rank(player)

    emit('rank',
         {'data': {
             'rank': rank,
             'num players': len(game.player_list())
         }})
Ejemplo n.º 12
0
def start_game():
    print 'Starting game'

    try:
        data = json.loads(request.data)
        print data
        name = data['game_id']
        game = Game.get_by_key(game_id)
        game.start()

        return jsonify({'status': 200})

    except:
        return getErrorJson(sys.exc_info())
Ejemplo n.º 13
0
def create_game():
    print 'Creating game'

    try:
        data = json.loads(request.data)
        print data
        name = data['name']
        description = data['description'] if 'description' in data else ''

        game = Game(name, description)

        return jsonify({'status': 200, 'game_key': game.key})
    except:
        return getErrorJson(sys.exc_info())
Ejemplo n.º 14
0
def end_game():
    print "Ending game"

    try:
        data = json.loads(request.data)
        print data
        name = data['game_id']
        game = Game.get_by_key(game_id)
        game.end()

        return jsonify({'status': 200})

    except:
        return getErrorJson(sys.exc_info())
Ejemplo n.º 15
0
def delete_objective():
    print "Deleting objective"

    try:
        data = json.loads(request.data)
        print data
        game_id = data['game_id']
        game = Game.get_by_key(game_id)

        game.delete_objective(data['objective_id'])

        return jsonify({'status': 200})

    except:
        return getErrorJson(sys.exc_info())
Ejemplo n.º 16
0
def test_find_or_make():
    map = Map(11, 7)
    map.load_from_file("resources/map3.txt")

    commands = [
        Command("id1", "DISH-BLUEBERRIES-ICE_CREAM-CROISSANT", 10),
        Command("id5", "DISH-CROISSANT-CHOPPED_STRAWBERRIES", 50)
    ]
    game = Game(map, 1, commands)
    game.oven = Oven(12, "NONE")
    game.current_commands = [
        Command("id5", "DISH-CROISSANT-CHOPPED_STRAWBERRIES", 50)
    ]
    game.get_better_command()

    orders = game.find_or_make(Dessert("CROISSANT"))
    assert len(orders) == 5

    game.oven = Oven(12, "CROISSANT")

    orders = game.find_or_make(Dessert("CROISSANT"))
    assert len(orders) == 0
    assert game.current_command.desserts_state["CROISSANT"]
Ejemplo n.º 17
0
def add_objective():
    print 'Adding objective'

    try:
        data = json.loads(request.data)
        print data
        game_id = data['game_id']
        game = Game.get_by_key(game_id)

        name = data['objective']['name']
        description = data['objective']['description']
        location = data['objective']['location']
        objective = game.add_objective(location, name, description)

        return jsonify({'status': 200, 'id': objective.id})

    except:
        return getErrorJson(sys.exc_info())
Ejemplo n.º 18
0
def rank(message):
    player = Player.get_by_id(request.sid)
    print player.name, "completed an objective: ", message

    game = Game.get_by_key(player.game_key)
    print "game:", game.name
    objective = Objective.get_by_id(message['data']['objectiveId'])
    print "completing: ", objective.name

    if player.id in objective.players_completed:
        print "Player ", player.name, "is trying to complete objective", objective.name, "twice!"
        return

    time = message['data']['time']
    pic_url = message['data']['url']

    game.player_complete_objective(player, objective, time, pic_url)
    print "Process completed objective"
Ejemplo n.º 19
0
def test_validate_guess(capfd):
    game = Game()
    game._answer = 2

    assert not game._validate_guess(1)
    # unpacks capfd return
    out, _ = capfd.readouterr()
    assert out == '1 is too low\n'

    assert not game._validate_guess(3)
    out, _ = capfd.readouterr()
    assert out == '3 is too high\n'

    assert game._validate_guess(2)
    out, _ = capfd.readouterr()
    assert out == '2 is correct!\n'
Ejemplo n.º 20
0
def game_stats():
    print "Getting game stats"

    try:
        data = json.loads(request.data)
        print data
        game_id = data['game_id']
        game = Game.get_by_key(game_id)

        objective_stats = []
        for objective in game.objective_list():
            players_complete = [{
                'id': player_id,
                'name': Player.get_by_id(player_id).name
            } for player_id in objective.players_completed]

            objective_stats.append({
                'id': objective.id,
                'name': objective.name,
                'players_complete': players_complete
            })

        player_stats = []
        for player in game.player_list():
            player_info = player.serialize()
            player_info['rank'] = game.get_player_rank(player)
            player_stats.append(player_info)

        return jsonify({
            'data': {
                'objective_stats': objective_stats,
                'player_stats': player_stats
            },
            'status': 200
        })

    except:
        return getErrorJson(sys.exc_info())
Ejemplo n.º 21
0
def test_game_lose(input, capfd):
    game = Game()
    game._answer = 12

    game()
    assert game._win is False
Ejemplo n.º 22
0
class TestWikiGolf(unittest.TestCase):

	def setUp(self):
		self.WP = WikiPage()
		self.User = User(usersDB) ##not testing user yet
		self.Game = Game(self.WP, self.User)


		"""Tests for WikiPage Class"""

	def testRandomWiki(self):
		"""Tests that a Wikipedia page is succesfully loaded"""
		randomPage = self.WP.loadRandWikiPage()
		self.assertTrue(randomPage)

	def testGivenPagePass(self):
		"""Tests that a specific Wikipedia page is succesfully loaded"""
		givenPage = self.WP.loadGivenWikiPage('Vegetarian_bacon')
		self.assertEqual(givenPage[1], 'Vegetarian bacon')

		self.assertEqual(self.WP.pageCon, baconHTML)

	def testGivenPageFail(self):
		"""Tests that an ambiguos page returns the proper HTML informing
		the user that something has gone wrong"""
		givenPage = self.WP.loadGivenWikiPage('Italian')
		self.assertEqual(givenPage[1], "Unavailable")
		self.assertEqual(self.WP.pageCon, unavailable)

	def testContentWithLinks(self):
		"""Tests to make sure that the html is having all the href's changed for backbone
		and having the right tags left out."""
		pageContent = self.WP.contentWithLinks('Vegetarian_bacon')
		self.assertTrue(pageContent)

	"""Tests for Game class"""
	
	def testStartGameRandom(self):
		"""Ensures that the HTML for a random course is added to the courseHTML list
		when method is called"""
		self.Game.startGame(Random = True)
		self.assertTrue(self.Game.courseHTML[0])
		self.assertTrue(self.Game.startPage)
		self.assertTrue(self.Game.endPage)

	def testStartGamenotRandom(self):
		"""Ensures that the HTML for a course loaded from Mongo is added to the courseHTML list
		when method is called"""
		self.Game.startGame(Random = False, par = 3)
		self.assertTrue(self.Game.courseHTML[0])
		self.assertTrue(self.Game.startPage)
		self.assertTrue(self.Game.endPage)

	def testCheckWinnerTrue(self):
		"""Tests if the current path is the same as the end path. If so, return True"""
		self.Game.title = 'Vegetarian bacon'
		self.Game.endPage = 'Vegetarian bacon'
		gameState = self.Game.checkWinner()
		self.assertTrue(gameState)

	def testMakeWikiObjectsRandom(self):
		"""Test that the wikiObject for a Random page that is sent to the client is created and formatted properly"""
		self.Game.startPage = 'Vegetarian_bacon'
		self.Game.startLinks = ["homestarrunner.com"]
		objects = self.Game.makeWikiObjects(random=True)
		self.assertEqual(objects[0]['id'], 1)
		self.assertEqual(objects[0]['startPage'], 'Vegetarian_bacon')
		self.assertEqual(objects[0]['endPage'], None)
		self.assertEqual(objects[0]['gameOver'], False)
		self.assertEqual(objects[0]['coursePath'], [])
		self.assertTrue(objects[0]['courseContent'])

	def testMakeWikiObjectsNotRandom(self):
		"""Test that the wikiObject for a given page that is sent to the client is created and formatted properly"""
		self.Game.courseHTML = ['Vegetarian_bacon']
		self.Game.startPage = 'Vegetarian_bacon'
		objects = self.Game.makeWikiObjects(random=True)
		self.assertEqual(objects[0]['id'], 1)
		self.assertEqual(objects[0]['startPage'], 'Vegetarian_bacon')
		self.assertEqual(objects[0]['endPage'], None)
		self.assertEqual(objects[0]['gameOver'], False)
		self.assertEqual(objects[0]['coursePath'], ['Vegetarian_bacon'])
		self.assertTrue(objects[0]['courseContent'])

	def testClearGame(self):
		"""Makes sure that the function clears the strokes, coursePath and courseHtml"""
		self.User.strokes = 10
		self.Game.coursePath = ['oh', 'hai', 'there']
		self.Game.courseHtml = '<html> My awesome website </html>'
		self.Game.clearGame()
		self.assertEqual(self.User.strokes, 0)
		self.assertEqual(self.Game.coursePath, None)
		self.assertEqual(self.Game.courseHTML, [])
Ejemplo n.º 23
0
import datetime
import json
from flask import request
from flask_socketio import emit
from app import app, socketio, Game, Objective, Player

# Fake data
game1 = Game('game1')
print game1.key

game1.add_player('Yan', '')
game1.add_player('Sas', '')

game1.add_objective({
    "lat": 40.633388,
    "long": -73.931379
}, "TEST_OBJECTIVE_1", "description1")
game1.add_objective({
    "lat": 40.632397,
    "long": -73.931349
}, "TEST_OBJECTIVE_2", "description2")
game1.add_objective({
    "lat": 40.632377,
    "long": -73.931364
}, "TEST_OBJECTIVE_3", "description3")

for o in game1.objective_list():
    print o.id


@socketio.on('connect')
Ejemplo n.º 24
0
def gameFunctions(fs):
    returnObj = {}
    if 'id' in fs:
        # id tells what sub function to perform
        if fs['id'] in ['random', 'All', 'CategoryOnly', 'RandomQuestion']:
            # counter = 0 indicates first time submitting params
            if fs['counter'] == '0':
                returnObj = Game(fs).addToQueue()
            else:
                # counter > 0 indicates checking for game
                # get players from queue
                data = Game(fs).getGame()
                # send return data
                returnObj = data

                if data['game_id']:
                    # if queue properly populated
                    returnObj['status'] = 'complete'
                else:
                    # if queue not properly populated
                    returnObj['status'] = 'pending'
        elif fs['id'] == 'commentPoll':
            # get comments from players from game
            data = Game(fs).getComments()
            totPlayers = Game(fs).getTotalPlayers()

            # send return data
            returnObj['users'] = data
            returnObj['pending'] = totPlayers - len(data)
            if not data or len(data) < totPlayers:  # if no data returned
                # if queue not properly populated
                returnObj['status'] = 'pending'
            else:
                # if queue properly populated
                returnObj['status'] = 'complete'
        elif fs['id'] == 'votePoll':
            # total number of players in the game
            totPlayers = Game(fs).getTotalPlayers()

            # get votes from players from game
            data = Game(fs).getVotes()

            # send return data
            returnObj['users'] = data
            returnObj['pending'] = totPlayers - len(data)
            if not data or len(data) < totPlayers:  # if no data returned
                # if queue not properly populated
                returnObj['status'] = 'pending'
            else:
                # if queue properly populated
                returnObj['status'] = 'complete'
                # end game
                Game(fs).endGame()

        elif fs['id'] == 'debateVote':
            # submit vote
            returnObj = Game(fs).submitVote()
        elif fs['id'] in ['getMetaData']:
            returnObj = Game(fs).getMetaData()
        elif fs['id'] in ['cancelGame']:
            # cancel game search
            returnObj = Game(fs).removeFromQueue()
        elif fs['id'] in ['gameUI']:
            # submit game
            returnObj = Game(fs).submitThoughts()

    returnJson(returnObj)
Ejemplo n.º 25
0
from app import Game
from app import Board
if __name__ == "__main__":
    game = Game("hudson","tyler")
    game.run_game()
Ejemplo n.º 26
0
def serve_layout():
    if flask.has_request_context():
        return layout1
    return html.Div([layout1, Home(), Game()])
Ejemplo n.º 27
0
        TIMELIMIT = int(TIMELIMIT)
        if not 100 <= TIMELIMIT <= 30000:
            TIMELIMIT = DEFAULT_TIMELIMIT
    except:
        TIMELIMIT = DEFAULT_TIMELIMIT

    try:
        ISRED = ISRED.lower()[0] == "t"
    except:
        ISRED = DEFAULT_ISRED

    if (MODE not in ["PvP", "Min", "Loc", "EvE"]):
        MODE = DEFAULT_MODE

    with open("settings.json", "w") as settings:
        # settings.write(json.dumps({'BOARD_SIZE' : BOARD_SIZE, 'TIMELIMIT' : TIMELIMIT, 'ISRED' : ISRED, 'TARGETS' : None}))
        settings.write(
            json.dumps({
                'BOARD_SIZE': BOARD_SIZE,
                'TIMELIMIT': TIMELIMIT,
                'ISRED': ISRED
            }))
        atexit.register(remove_temporary_settings)

    from app import Game
    game = Game(board_size=BOARD_SIZE,
                timelimit=TIMELIMIT,
                is_red=ISRED,
                mode=MODE)
    game.run()
Ejemplo n.º 28
0
 def setUp(self):
     self.WP = WikiPage()
     self.User = User(usersDB)  ##not testing user yet
     self.Game = Game(self.WP, self.User)
     """Tests for WikiPage Class"""
Ejemplo n.º 29
0
class TestWikiGolf(unittest.TestCase):
    def setUp(self):
        self.WP = WikiPage()
        self.User = User(usersDB)  ##not testing user yet
        self.Game = Game(self.WP, self.User)
        """Tests for WikiPage Class"""

    def testRandomWiki(self):
        """Tests that a Wikipedia page is succesfully loaded"""
        randomPage = self.WP.loadRandWikiPage()
        self.assertTrue(randomPage)

    def testGivenPagePass(self):
        """Tests that a specific Wikipedia page is succesfully loaded"""
        givenPage = self.WP.loadGivenWikiPage('Vegetarian_bacon')
        self.assertEqual(givenPage[1], 'Vegetarian bacon')

        self.assertEqual(self.WP.pageCon, baconHTML)

    def testGivenPageFail(self):
        """Tests that an ambiguos page returns the proper HTML informing
		the user that something has gone wrong"""
        givenPage = self.WP.loadGivenWikiPage('Italian')
        self.assertEqual(givenPage[1], "Unavailable")
        self.assertEqual(self.WP.pageCon, unavailable)

    def testContentWithLinks(self):
        """Tests to make sure that the html is having all the href's changed for backbone
		and having the right tags left out."""
        pageContent = self.WP.contentWithLinks('Vegetarian_bacon')
        self.assertTrue(pageContent)

    """Tests for Game class"""

    def testStartGameRandom(self):
        """Ensures that the HTML for a random course is added to the courseHTML list
		when method is called"""
        self.Game.startGame(Random=True)
        self.assertTrue(self.Game.courseHTML[0])
        self.assertTrue(self.Game.startPage)
        self.assertTrue(self.Game.endPage)

    def testStartGamenotRandom(self):
        """Ensures that the HTML for a course loaded from Mongo is added to the courseHTML list
		when method is called"""
        self.Game.startGame(Random=False, par=3)
        self.assertTrue(self.Game.courseHTML[0])
        self.assertTrue(self.Game.startPage)
        self.assertTrue(self.Game.endPage)

    def testCheckWinnerTrue(self):
        """Tests if the current path is the same as the end path. If so, return True"""
        self.Game.title = 'Vegetarian bacon'
        self.Game.endPage = 'Vegetarian bacon'
        gameState = self.Game.checkWinner()
        self.assertTrue(gameState)

    def testMakeWikiObjectsRandom(self):
        """Test that the wikiObject for a Random page that is sent to the client is created and formatted properly"""
        self.Game.startPage = 'Vegetarian_bacon'
        self.Game.startLinks = ["homestarrunner.com"]
        objects = self.Game.makeWikiObjects(random=True)
        self.assertEqual(objects[0]['id'], 1)
        self.assertEqual(objects[0]['startPage'], 'Vegetarian_bacon')
        self.assertEqual(objects[0]['endPage'], None)
        self.assertEqual(objects[0]['gameOver'], False)
        self.assertEqual(objects[0]['coursePath'], [])
        self.assertTrue(objects[0]['courseContent'])

    def testMakeWikiObjectsNotRandom(self):
        """Test that the wikiObject for a given page that is sent to the client is created and formatted properly"""
        self.Game.courseHTML = ['Vegetarian_bacon']
        self.Game.startPage = 'Vegetarian_bacon'
        objects = self.Game.makeWikiObjects(random=True)
        self.assertEqual(objects[0]['id'], 1)
        self.assertEqual(objects[0]['startPage'], 'Vegetarian_bacon')
        self.assertEqual(objects[0]['endPage'], None)
        self.assertEqual(objects[0]['gameOver'], False)
        self.assertEqual(objects[0]['coursePath'], ['Vegetarian_bacon'])
        self.assertTrue(objects[0]['courseContent'])

    def testClearGame(self):
        """Makes sure that the function clears the strokes, coursePath and courseHtml"""
        self.User.strokes = 10
        self.Game.coursePath = ['oh', 'hai', 'there']
        self.Game.courseHtml = '<html> My awesome website </html>'
        self.Game.clearGame()
        self.assertEqual(self.User.strokes, 0)
        self.assertEqual(self.Game.coursePath, None)
        self.assertEqual(self.Game.courseHTML, [])
Ejemplo n.º 30
0
        "name": "Tennis",
        "score_type": 1  # 1 stands for more is better
    },
    {
        "name": "Golf",
        "score_type": 2  # 1 stands for less is better
    },
    {
        "name": "Running",
        "score_type": 2  # 1 stands for more is better
    },
]

for game in games:
    x = Game(
        name=game["name"],
        score_type=game["score_type"],
    )
    db.session.add(x)
    db.session.commit()

matches = [
    {
        "game": 1,
        "player1_id": 1,
        "player2_id": 2,
        "player1_score": 10,
        "player2_score": 20,
    },
    {
        "game": 2,
        "player1_id": 3,
Ejemplo n.º 31
0
def error(message):
    print pcol.bold(pcol.red(message))
    exit(1)


def query(question):
    return raw_input(pcol.bold(pcol.yellow(question)))

info("Welcome to SlackJack!")
name = query("What's your name?")
play = True
while play:
    bet = query("How much would you like to bet?")
    if not bet.isdigit():
        error("{} is an invalid bet amount.".format(bet))

    player = Player(name, bet, info)

    game = Game.create([player])

    while not game.can_make_move(player):
        sleep(0.1)

    while game.can_make_move(player):
        move_raw = query("What would you like to do? [H = Hit, S = Stand]")
        move = Move.from_raw(move_raw, player, game)
        Game.move(move)

    play = str(query("Play again? [Y/N]")).lower() == 'y'

Ejemplo n.º 32
0
 def get_game_instance(cls):
     game_data = cls.game.get("data")
     if not game_data:
         return game_data
     return Game.from_json(game_data)