Beispiel #1
0
def betweenPlayRunoff(game, play, offenseHomeAway, timeOption):
	timeOffClock = 0
	if game.status.timeRunoff:
		if game.status.state(offenseHomeAway).requestedTimeout == TimeoutOption.REQUESTED:
			log.debug("Using offensive timeout")
			game.status.state(offenseHomeAway).requestedTimeout = TimeoutOption.USED
			game.status.state(offenseHomeAway).timeouts -= 1
		elif game.status.state(offenseHomeAway.negate()).requestedTimeout == TimeoutOption.REQUESTED:
			log.debug("Using defensive timeout")
			game.status.state(offenseHomeAway.negate()).requestedTimeout = TimeoutOption.USED
			game.status.state(offenseHomeAway.negate()).timeouts -= 1
		else:
			if play == Play.KNEEL:
				timeOffClock = 39
			elif timeOption == TimeOption.CHEW:
				timeOffClock = 35
			elif timeOption == TimeOption.HURRY:
				timeOffClock = 5
			else:
				timeOffClock = getTimeAfterForOffense(game, offenseHomeAway)

	log.debug("Between play runoff: {} : {} : {}".format(game.status.clock, timeOffClock, game.status.timeRunoff))

	game.status.clock -= timeOffClock
	game.status.timeRunoff = False

	runStatus, timeOffClock, timeMessage = checkQuarterStatus(game, timeOffClock)
	utils.addStat(game, 'posTime', timeOffClock, offenseHomeAway)

	if runStatus == RunStatus.CONTINUE_QUARTER:
		timeMessage = "That's the {}".format(timeMessage)
	elif runStatus == RunStatus.STOP_QUARTER:
		timeMessage = "The clock ran out before the play was run. That's the {}".format(timeMessage)

	return runStatus, timeMessage, timeOffClock
Beispiel #2
0
def setBlock(game,turnover):
	current = game['status']['possession']
	utils.addStat(game,'blocks', 1, utils.reverseHomeAway(current))
	shotType = utils.coinToss()
	if shotType:
		sub2Pt(game, False, False)
	else:
		sub3Pt(game, False, False)
Beispiel #3
0
def sub2Pt(game, made, fouled, off=False):
	'''
	This function is used for all three point type plays. If a 2 point is missed then it
	only adds to the stat of attepmts. If it is made then it adds the score and then
	adds 2 point made and 2 total points to score.
	'''
	team = game['status']['possession']
	utils.addStat(game,'2PtAttempted',1,team)
	##if the shot was made
	if made:
		score2Points(game, team)
		utils.addStat(game,'2PtMade',1,team)
		if fouled:
			log.debug('Just scored 2 and going to set 1 foul for the one and one on')
			setFouls(game, 1)
	elif not made and not fouled and not off:
		log.debug('Going to add a defensive rebound on a 2 point shot to the other team')
		utils.addStat(game,'defRebound', 1, utils.reverseHomeAway(team))
	elif off:
		utils.addStat(game, 'offRebound',1,team)
	elif fouled and not made:
		setFouls(game, 2)
		log.debug('Missed a 2 point shot but going to set 2 free throws')
	else:
		log.warning("OOPS. should not be here in sub2Pt")
Beispiel #4
0
def sub3Pt(game, made, fouled, off=False):
    '''
	This function is used for all three point type plays. If a 3 point is missed then it
	only adds to the stat of attepmts. If it is made then it adds the score and then
	adds 3 point made and 3 total points to score. if fouled, then f_type is sent
	'''
    team = game['status']['possession']
    utils.addStat(game, '3PtAttempted', 1, team)
    if made:
        score3Points(game, team)
        utils.addStat(game, '3PtMade', 1, team)
        if fouled:
            log.debug(
                'Going to set foul information for a 3 point shot made with an and one'
            )
            setFouls(game, 1)
    elif not made and not fouled and not off:
        log.debug(
            'Going to add a defensive rebound on a 3 point shot to the other team'
        )
        utils.addStat(game, 'defRebound', 1, utils.reverseHomeAway(team))
    elif off:
        utils.addStat(game, 'offRebound', 1, team)
    elif fouled and not made:
        log.debug("going to set foul information for an agent ")
        setFouls(game, 3)
    else:
        log.warning("should not be here in the sub3Pt function")
Beispiel #5
0
def updateTime(game, play, result, offenseHomeAway):
	if result == 'FREE':
		return ''
	elif result == 'FREEDONE':
		timeOffClock = 0
	elif play == 'foul':
		log.debug('doing the stuff')
		timeOffClock = globals.ifoulTime
	else:
		timeOffClock = getTimeByPlay(game, play)
	log.debug("time off the clock was {}".format(timeOffClock))



	log.debug("Time off clock: {} : {}".format(game['status']['clock'], timeOffClock))
	game['status']['clock'] -= timeOffClock
	log.debug('clock after subtraction is {}'.format(game['status']['clock']))
	timeMessage = "{} left".format(utils.renderTime(game['status']['clock']))

	if game['status']['clock'] <= 0:
		log.debug("End of half: {}".format(game['status']['half']))
		actualTimeOffClock = timeOffClock + game['status']['clock']
		game['status']['clock'] = 0
		if not game['status']['free']:
			if play.lower() in (globals.steal3Pt, globals.stealDunk):
				utils.addStat(game, 'posTime', actualTimeOffClock, utils.reverseHomeAway(offenseHomeAway))
			else:
				utils.addStat(game, 'posTime', actualTimeOffClock, offenseHomeAway)
			timeMessage = endHalf(game)
			if game['status']['halfType'] != 'end' and game['status']['half'] > 2:
				log.debug('Setting OverTime information')
				game['status']['clock'] = globals.otLength
				game['score']['halves'].append({'home':0,'away':0})
				log.debug('Going to null the tip numbers out and make them all false in the game object.')
				database.nullTipNumbers(game['dataID'])
				game['tip']['homeTip'] = False
				game['tip']['awayTip'] = False
				coaches = [game['home']['coaches'][0], game['away']['coaches'][0]]
				utils.sendTipNumberMessages(game, coaches)
	else:
		actualTimeOffClock = timeOffClock

		if play.lower() in (globals.steal3Pt, globals.stealDunk):
			utils.addStat(game, 'posTime', actualTimeOffClock, utils.reverseHomeAway(offenseHomeAway))
		else:
			utils.addStat(game, 'posTime', actualTimeOffClock, offenseHomeAway)


	if game['status']['clock'] <= 0 and game['status']['halfType'] == 'end':
		return "The play took {} seconds, {}".format(actualTimeOffClock, timeMessage)
	elif game['status']['clock'] <= 0 and game['status']['halfType'] =='overtimeNormal':
		return "The play took {} seconds, {}".format(actualTimeOffClock, timeMessage)
	elif game['status']['clock'] <= 0 and game['status']['halfType'] not in ('end', 'overtimeNormal') and game['status']['free']:
		return "The play took {} seconds, No time left on the clock".format(actualTimeOffClock)
	else:
		return "The play took {} seconds, {}".format(actualTimeOffClock, timeMessage)
Beispiel #6
0
def updateTime(game, play, result, actualResult, yards, offenseHomeAway, timeOption, timeBetweenPlay):
	log.debug("Updating time with: {} : {} : {} : {} : {} : {}".format(play, result, actualResult, yards, offenseHomeAway, timeOption))
	timeOffClock = 0

	if actualResult in [Result.TOUCHDOWN, Result.TOUCHBACK, Result.SAFETY] and play not in classes.kickoffPlays:
		timeResult = Result.GAIN
	elif result == Result.INCOMPLETE:
		timeResult = Result.INCOMPLETE
	elif actualResult == Result.TURNOVER and result == Result.GAIN:
		timeResult = Result.GAIN
	else:
		timeResult = actualResult

	game.status.timeRunoff = False
	if actualResult == Result.SPIKE:
		timeOffClock += 3
	elif play == Play.PAT:
		timeOffClock += 0
	elif play == Play.TWO_POINT:
		timeOffClock += 0
	else:
		if actualResult == Result.KNEEL:
			timeOffClock += 1
		else:
			timeOffClock += getTimeByPlay(play, timeResult, yards)

		if actualResult in [Result.GAIN, Result.KNEEL] and result != Result.INCOMPLETE and play not in classes.kickoffPlays:
			game.status.timeRunoff = True

	log.debug("Time off clock: {} : {} : {}".format(game.status.clock, timeOffClock, game.status.timeRunoff))

	game.status.clock -= timeOffClock

	runStatus, timeOffClock, timeMessage = checkQuarterStatus(game, timeOffClock)
	if timeMessage is None:
		timeMessage = "{} left".format(string_utils.renderTime(game.status.clock))

	utils.addStat(game, 'posTime', timeOffClock, offenseHomeAway)

	return "The play took {} seconds, {}".format(max(timeOffClock + timeBetweenPlay, 0), timeMessage), timeOffClock
Beispiel #7
0
def executePlay(game, play, number, numberMessage):
	startingPossessionHomeAway = game['status']['possession']
	actualResult = None
	yards = None
	resultMessage = "Something went wrong, I should never have reached this"
	diffMessage = None
	success = True
	if game['status']['conversion']:
		if play in globals.conversionPlays:
			if number == -1:
				log.debug("Trying to execute a normal play, but didn't have a number")
				resultMessage = numberMessage
				success = False

			else:
				numberResult, diffMessage = getNumberDiffForGame(game, number)

				log.debug("Executing conversion play: {}".format(play))
				result = getPlayResult(game, play, numberResult)
				if result['result'] == 'twoPoint':
					log.debug("Successful two point conversion")
					resultMessage = "The two point conversion is successful"
					scoreTwoPoint(game, game['status']['possession'])

				elif result['result'] == 'pat':
					log.debug("Successful PAT")
					resultMessage = "The PAT was successful"
					scorePAT(game, game['status']['possession'])

				elif result['result'] == 'touchback':
					log.debug("Attempt unsuccessful")
					if play == "twoPoint":
						resultMessage = "The two point conversion attempt was unsuccessful"
					elif play == "pat":
						resultMessage = "The PAT attempt was unsuccessful"
					else:
						resultMessage = "Conversion unsuccessful"
					setStateTouchback(game, utils.reverseHomeAway(game['status']['possession']))

				database.clearDefensiveNumber(game['dataID'])

		else:
			resultMessage = "It looks like you're trying to get the extra point after a touchdown, but this isn't a valid play"
			success = False
	else:
		if play in globals.normalPlays:
			if number == -1:
				log.debug("Trying to execute a normal play, but didn't have a number")
				resultMessage = numberMessage
				success = False

			else:
				numberResult, diffMessage = getNumberDiffForGame(game, number)

				log.debug("Executing normal play: {}".format(play))
				result = getPlayResult(game, play, numberResult)
				if result['result'] == 'gain':
					if 'yards' not in result:
						log.warning("Result is a gain, but I couldn't find any yards")
						resultMessage = "Result of play is a number of yards, but something went wrong and I couldn't find what number"
						success = False
					else:
						log.debug("Result is a gain of {} yards".format(result['yards']))
						gainResult, yards, resultMessage = executeGain(game, play, result['yards'])
						if gainResult != "error":
							if yards is not None:
								actualResult = gainResult
						else:
							success = False

				elif result['result'] == 'touchdown':
					log.debug("Result is a touchdown")
					resultMessage = "It's a {} into the endzone! Touchdown {}!".format(play, game[game['status']['possession']]['name'])
					previousLocation = game['status']['location']
					utils.addStatRunPass(game, play, 100 - previousLocation)
					scoreTouchdown(game, game['status']['possession'])
					actualResult = "touchdown"
					yards = 100 - previousLocation

				elif result['result'] == 'fieldGoal':
					log.debug("Result is a field goal")
					resultMessage = "The {} yard field goal is good!".format(100 - game['status']['location'] + 17)
					utils.addStat(game, 'fieldGoalsScored', 1)
					scoreFieldGoal(game, game['status']['possession'])
					actualResult = "fieldGoal"

				elif result['result'] == 'punt':
					if 'yards' not in result:
						log.warning("Result is a punt, but I couldn't find any yards")
						resultMessage = "Result of play is a successful punt, but something went wrong and I couldn't find how long a punt"
					log.debug("Successful punt of {} yards".format(result['yards']))
					resultMessage = executePunt(game, result['yards'])
					actualResult = "punt"

				elif result['result'] == 'turnover':
					log.debug("Play results in a turnover")
					if play == "run":
						utils.addStat(game, 'turnoverInterceptions', 1)
						resultMessage = "Fumble! The ball is dropped, {} recovers!".format(game[utils.reverseHomeAway(game['status']['possession'])]['name'])
					elif play == "pass":
						utils.addStat(game, 'turnoverFumble', 1)
						resultMessage = "Picked off! The pass is intercepted, {} ball!".format(game[utils.reverseHomeAway(game['status']['possession'])]['name'])
					elif play == "fieldGoal" or play == "punt":
						utils.addStat(game, 'turnoverFumble', 1)
						resultMessage = "It's a miss!"
					else:
						utils.addStat(game, 'turnoverFumble', 1)
						resultMessage = "It's a turnover!"
					turnover(game)
					actualResult = "turnover"

				elif result['result'] == 'turnoverTouchdown':
					log.debug("Play results in a turnover and run back")
					if play == "run":
						resultMessage = "Fumble! The ball is dropped and it's run all the way back. Touchdown {}!".format(game[utils.reverseHomeAway(game['status']['possession'])]['name'])
					elif play == "pass":
						resultMessage = "Picked off! The pass is intercepted and it's run all the way back. Touchdown {}!".format(game[utils.reverseHomeAway(game['status']['possession'])]['name'])
					elif play == "fieldGoal" or play == "punt":
						resultMessage = "It's blocked! The ball is picked up and run all the back. Touchdown {}!".format(game[utils.reverseHomeAway(game['status']['possession'])]['name'])
					else:
						resultMessage = "It's a turnover and run back for a touchdown!"
					scoreTouchdown(game, utils.reverseHomeAway(game['status']['possession']))
					actualResult = "turnoverTouchdown"

				if success and play == 'fieldGoal':
					utils.addStat(game, 'fieldGoalsAttempted', 1)

				database.clearDefensiveNumber(game['dataID'])

		elif play in globals.timePlays:
			if play == 'kneel':
				log.debug("Running kneel play")
				actualResult = "kneel"
				game['status']['down'] += 1
				if game['status']['down'] > 4:
					log.debug("Turnover on downs")
					turnover(game)
					resultMessage = "Turnover on downs"
				else:
					resultMessage = "The quarterback takes a knee"

			elif play == 'spike':
				log.debug("Running spike play")
				actualResult = "spike"
				game['status']['down'] += 1
				if game['status']['down'] > 4:
					log.debug("Turnover on downs")
					turnover(game)
					resultMessage = "Turnover on downs"
				else:
					resultMessage = "The quarterback spikes the ball"

		else:
			resultMessage = "{} isn't a valid play at the moment".format(play)
			success = False

	messages = [resultMessage]
	if actualResult is not None:
		timeMessage = updateTime(game, play, actualResult, yards, startingPossessionHomeAway)

		messages.append(timeMessage)

	if diffMessage is not None:
		messages.append(diffMessage)

	return success, '\n\n'.join(messages)
Beispiel #8
0
def updateTime(game, play, result, yards, offenseHomeAway):
	if result in ['touchdown', 'touchback']:
		actualResult = "gain"
	else:
		actualResult = result
	if result == 'spike':
		timeOffClock = 1
	else:
		if result == 'kneel':
			timeOffClock = 1
		else:
			timeOffClock = getTimeByPlay(play, actualResult, yards)

		if result in ["gain", "kneel"]:
			if game['status']['requestedTimeout'][offenseHomeAway] == 'requested':
				log.debug("Using offensive timeout")
				game['status']['requestedTimeout'][offenseHomeAway] = 'used'
				game['status']['timeouts'][offenseHomeAway] -= 1
			elif game['status']['requestedTimeout'][utils.reverseHomeAway(offenseHomeAway)] == 'requested':
				log.debug("Using defensive timeout")
				game['status']['requestedTimeout'][utils.reverseHomeAway(offenseHomeAway)] = 'used'
				game['status']['timeouts'][utils.reverseHomeAway(offenseHomeAway)] -= 1
			else:
				if result == 'kneel':
					timeOffClock += 39
				else:
					timeOffClock += getTimeAfterForOffense(game, offenseHomeAway)
		log.debug("Time off clock: {} : {}".format(game['status']['clock'], timeOffClock))

	game['status']['clock'] -= timeOffClock
	timeMessage = "{} left".format(utils.renderTime(game['status']['clock']))

	if game['status']['clock'] < 0:
		log.debug("End of quarter: {}".format(game['status']['quarter']))
		actualTimeOffClock = timeOffClock + game['status']['clock']
		if game['status']['quarter'] == 1:
			timeMessage = "end of the first quarter"
		elif game['status']['quarter'] == 3:
			timeMessage = "end of the third quarter"
		else:
			if game['status']['quarter'] == 4:
				if game['score']['home'] == game['score']['away']:
					timeMessage = "full time! The score is tied, but unfortunately overtime is not implemented yet."
				else:
					timeMessage = "full time!"
				game['status']['clock'] = 0
				game['waitingAction'] = 'end'
			else:
				if game['status']['quarter'] == 2:
					timeMessage = "end of the first half"

				setStateTouchback(game, game['receivingNext'])
				game['receivingNext'] = utils.reverseHomeAway(game['receivingNext'])
				game['status']['timeouts'] = {'home': 3, 'away': 3}

		if game['status']['quarter'] < 4:
			game['status']['quarter'] += 1
			game['status']['clock'] = globals.quarterLength
	else:
		actualTimeOffClock = timeOffClock

	utils.addStat(game, 'posTime', actualTimeOffClock, offenseHomeAway)

	return "The play took {} seconds, {}".format(timeOffClock, timeMessage)
Beispiel #9
0
def setTurnovers(game,turnover):
	s_turnover =  "{}{}".format(turnover,'s')
	current =  game['status']['possession']
	if turnover == 'steal':
		utils.addStat(game, s_turnover, 1, utils.reverseHomeAway(current))
	utils.addStat(game, 'turnovers', 1, current)
Beispiel #10
0
def executePlay(game, play, number, numberMessage):
	startingPossessionHomeAway = game['status']['possession']
	actualResult = None
	resultMessage = "Something went wrong, I should never have reached this"
	diffMessage = None
	success = True
	timeMessage = None
	fouled = False


	log.debug("starting to execute Play with play being {} and number being {}".format(play, number))
	if game['status']['free'] != False:
		result = "FREE"
		if number == -1:
			log.debug("Trying to shoot a free throw play, but didn't have a number")
			resultMessage = numberMessage
			success = False
			return False, resultMessage
		elif number > -1:
			game['status']['frees'] -= 1

			utils.addStat(game,'FTAttempted',1,startingPossessionHomeAway)
			numberResult, diffMessage = getNumberDiffForGame(game, number)
			freeResult = getFreeThrowResult(game,numberResult)


			if freeResult:
				game['play']['result'] = 'Free Made'
				log.debug("Successful Free Throw")
				tempMessage = ["{}'s Free throw was successful.\n\n ".format(game[game['status']['possession']]['name'])]
				utils.addStat(game,'FTMade',1,startingPossessionHomeAway)
				scoreFreeThrow(game, startingPossessionHomeAway)
				tempMessage.append("\nThe score is now **{}**: {}, **{}**: {}".format(game['away']['name'],game['score']['away'], game['home']['name'], game['score']['home']))
				resultMessage = ''.join(tempMessage)
				if game['status']['free'] == '1and1Start':
					game['status']['frees'] = 1
					game['status']['free'] = True
			else:
				game['play']['result'] = 'Free Missed'
				log.debug("failed free throw")
				resultMessage =  "You missed the free throw."
			if game['status']['frees'] == 0:
				game['status']['free'] = False
				game['waitingAction'] =  'play'
				game['play']['playResult'] = 'freeDone'
				game['freeThrows']['freeType'] = None
				result = "FREEDONE"
			else:
				pass
##			database.clearDefensiveNumber(game['dataID'])
		else:
			resultMessage = "It looks like /]you're trying to get the extra point after a touchdown, but this isn't a valid play"
			success = False
	elif game['status']['ifoul']:
		resultMessage = setFouls(game, 0)
		game['play']['playResult'] = 'fouled'

	else:
		if play in globals.offPlays:
			utils.addStat(game,'possessions',1,startingPossessionHomeAway)
			if number == -1:
				log.debug("Trying to execute a normal play, but didn't have a number")
				resultMessage = numberMessage
				success = False
			else:
				numberResult, diffMessage = getNumberDiffForGame(game, number)
				log.debug("numberResult was {}".format(numberResult))
				log.debug("Executing normal play: {}".format(play))
				result = getPlayResult(game, play, numberResult)
				game['play']['result'] = result['result']
				playResultName = result['result'].lower()
				log.debug('playResultName is {}'.format(playResultName))
				ptf = re.search('2|3', playResultName)
				log.debug("ptf is {}".format(ptf))
				if ptf:
					pointsTriedFor = int(ptf.group(0))
					log.debug("this shot as an attempt for {} points".format(pointsTriedFor))
				if playResultName.lower() in globals.pointResults :
					if 'points' not in result:
						log.warning("Result is a score, but I couldn't find any points")
						resultMessage = "Result of play is a number of points, but something went wrong and I couldn't find what number"
						success = False
					else:
						if playResultName in globals.foulPlays:
							##After this play we will be waiting on the current devensive
							##team since they will have to send a defensive number
							fouled =  True
						points = result['points']
						tempMessage = ["{}'s Basket is good for {} points.\n\n".format(game[game['status']['possession']]['name'],points)]
						if fouled:
							tempMessage.append('AND ONE. Player is fouled.\n\n')
						if points ==  2:
							sub2Pt(game, True, fouled)
							game['play']['playDesc'] = '2'
							game['play']['playResult'] = 'made'
							game['status']['scored'] = True
						elif points == 3:
							sub3Pt(game, True, fouled)
							game['play']['playResult'] = 'made'
							game['play']['playDesc'] = '3'
							game['status']['scored'] = True
						log.debug("Result is a gain of {} points".format(points))
						tempMessage.append("\nThe score is now **{}**: {}, **{}**: {}".format(game['away']['name'],game['score']['away'], game['home']['name'], game['score']['home']))
						resultMessage = ''.join(tempMessage)
				elif playResultName in globals.foulMissPlays:
					log.debug("In foul Miss Plays")
					##get numbers to see how many free thors we will shoot
					setFouls(game, pointsTriedFor)
					resultMessage = 'Fouled on a {0}pt shot. The shot is missed.  Going to shoot {0} free throws.'.format(pointsTriedFor)
					game['play']['playResult'] = 'fouled'
				elif playResultName in globals.nonShootingFoul:
					##This sets possession in the bonus check
					resultMessage = setFouls(game, 0)
					game['play']['playResult'] = 'fouled'
				elif playResultName in globals.missPlays:
					log.debug('In miss plays')
					game['play']['playResult'] = 'miss'##No need to change who we are waitingon here
					if pointsTriedFor == 2:
						sub2Pt(game, False, False)

					elif pointsTriedFor == 3:
						sub3Pt(game, False, False)
					else:
						return False, "Could not detect a number like we think it should. We must pay with our "
					resultMessage = "Missed a {} point shot.".format(pointsTriedFor)
				elif playResultName in globals.offRebounds:
					game['play']['playResult'] = 'offrebound'
					shotType = utils.coinToss()


					if shotType:
						log.debug('By random choice this was a 2 point shot')
						sub2Pt(game, False, False, True)
					else:
						log.debug('By random choice this was a 3 point shot')
						sub3Pt(game, False, False, True)


					resultMessage = "Missed a shot but got the offensive rebound"
				elif playResultName in globals.turnovers:
					game['play']['playResult'] = 'turnover'
					setTurnovers(game, playResultName.lower())
					if playResultName == "Steal":
						resultMessage = "Hark, a steal"
					else:
						resultMessage = 'Turned the ball over'
				elif playResultName == 'block':
					resultMessage = "the shot was BLOCKED"
					game['play']['playResult'] = 'block'
					setBlock(game, 'block')
				elif playResultName == globals.stealDunk:
					tempMessage = ['The ball was stolen by {} and dunked for two points\n\n'.format(game[utils.reverseHomeAway(game['status']['possession'])]['name'])]
					setTurnovers(game, 'steal')
					utils.addStat(game, 'possessions',1, utils.reverseHomeAway(startingPossessionHomeAway))
					game['status']['possession'] = utils.reverseHomeAway(startingPossessionHomeAway)
					log.debug('{} had the ball stolen and {} is about to score'.format(startingPossessionHomeAway, utils.reverseHomeAway(startingPossessionHomeAway)))
					sub2Pt(game, True, False)
					game['play']['playResult'] = 'made'
					game['waitingOn'] = utils.reverseHomeAway(startingPossessionHomeAway)
					tempMessage.append("\nThe score is now **{}**: {}, **{}**: {}".format(game['away']['name'],game['score']['away'], game['home']['name'], game['score']['home']))
					resultMessage = ''.join(tempMessage)
				elif playResultName == globals.steal3Pt:
					tempMessage = ['The ball was stolen by {} and shot for a 3 PT.\n\n '.format(game[utils.reverseHomeAway(game['status']['possession'])]['name'])]
					setTurnovers(game, 'steal')
					utils.addStat(game, 'possessions',1, utils.reverseHomeAway(startingPossessionHomeAway))
					game['status']['possession'] = utils.reverseHomeAway(startingPossessionHomeAway)
					log.debug('{} had the ball stolen and {} is about to score'.format(startingPossessionHomeAway, utils.reverseHomeAway(startingPossessionHomeAway)))
					sub3Pt(game, True, False)
					game['play']['playResult'] = 'made'
					game['waitingOn'] = utils.reverseHomeAway(startingPossessionHomeAway)
					tempMessage.append("\nThe score is now **{}**: {}, **{}**: {}".format(game['away']['name'],game['score']['away'], game['home']['name'], game['score']['home']))
					resultMessage = ''.join(tempMessage)

				database.clearDefensiveNumber(game['dataID'])
		else:
			resultMessage = "{} isn't a valid play at the moment".format(play)
			success = False
	messages = [resultMessage]
	if resultMessage is not None:
		if success:
			if game['status']['ifoul']:
				game['status']['ifoul'] = False
				diffMessage = None
				result = None
				timeMessage = updateTime(game, play, result, startingPossessionHomeAway)
			if timeMessage is None:
				timeMessage = updateTime(game, play, result, startingPossessionHomeAway)
			messages.append(timeMessage)
	if diffMessage is not None:
		messages.append(diffMessage)
	log.debug("Finishing execution of play")
	log.debug("We will be waiting on {} for next number".format(game['waitingOn']))
	log.debug("messages: resultMessage: {}, timeMessage:{}, diffMessage:{}".format(resultMessage, timeMessage, diffMessage))
	##determine here if we need to change possession
	changePossession(game)


	return success, '\n\n'.join(messages)
Beispiel #11
0
def executePlay(game, play, number, timeOption):
	startingPossessionHomeAway = game.status.possession.copy()
	actualResult = None
	result = None
	yards = None
	resultMessage = "Something went wrong, I should never have reached this"
	diffMessage = None
	success = True
	timeMessage = None

	playSummary = PlaySummary()
	playSummary.down = game.status.down
	playSummary.toGo = game.status.yards
	playSummary.location = game.status.location
	playSummary.offNum = number
	playSummary.posHome = game.status.possession.isHome

	runoffResult, timeMessageBetweenPlay, timeBetweenPlay = betweenPlayRunoff(game, play, startingPossessionHomeAway, timeOption)

	if runoffResult == RunStatus.STOP_QUARTER:
		log.debug("Hit stop_quarter, not running play")
	else:
		if play in classes.conversionPlays:
			numberResult, diffMessage, defenseNumber = getNumberDiffForGame(game, number)
			playSummary.defNum = defenseNumber

			log.debug("Executing conversion play: {}".format(play))
			result = getPlayResult(game, play, numberResult)
			actualResult = result['result']

			if result['result'] == Result.TWO_POINT:
				log.debug("Successful two point conversion")
				resultMessage = "The two point conversion is successful"
				scoreTwoPoint(game, game.status.possession)
				if utils.isGameOvertime(game):
					timeMessage = overtimeTurnover(game)
				else:
					setStateKickoff(game, game.status.possession)

			elif result['result'] == Result.PAT:
				log.debug("Successful PAT")
				resultMessage = "The PAT was successful"
				scorePAT(game, game.status.possession)
				if utils.isGameOvertime(game):
					timeMessage = overtimeTurnover(game)
				else:
					setStateKickoff(game, game.status.possession)

			elif result['result'] == Result.KICKOFF:
				log.debug("Attempt unsuccessful")
				if play == Play.TWO_POINT:
					resultMessage = "The two point conversion attempt was unsuccessful"
				elif play == Play.PAT:
					resultMessage = "The PAT attempt was unsuccessful"
				else:
					resultMessage = "Conversion unsuccessful"
				if utils.isGameOvertime(game):
					timeMessage = overtimeTurnover(game)
				else:
					setStateKickoff(game, game.status.possession)

			elif result['result'] == Result.TURNOVER_PAT:
				log.debug("Turnover PAT")
				resultMessage = "The attempt was fumbled and run all the way back! Two points {}!".format(game.team(game.status.possession.negate()).name)
				scoreTwoPoint(game, game.status.possession.negate())
				if utils.isGameOvertime(game):
					timeMessage = overtimeTurnover(game)
				else:
					setStateKickoff(game, game.status.possession)

			game.status.defensiveNumber = None

		elif play in classes.kickoffPlays:
			numberResult, diffMessage, defenseNumber = getNumberDiffForGame(game, number)
			playSummary.defNum = defenseNumber

			log.debug("Executing kickoff play: {}".format(play))
			result = getPlayResult(game, play, numberResult)
			actualResult = result['result']

			if result['result'] == Result.KICK:
				if 'yards' not in result:
					log.warning("Result is a successful kick, but I couldn't find any yards")
					resultMessage = "Result of kick is a number of yards, but something went wrong and I couldn't find what number"
					success = False
				else:
					log.debug("Result is a kick of {} yards".format(result['yards']))
					yards = result['yards']
					game.status.location = game.status.location + yards
					if utils.isGameOvertime(game):
						timeMessage = overtimeTurnover(game)
					else:
						turnover(game)
					resultMessage = "{} yard kick.".format(yards)

			elif result['result'] == Result.GAIN:
				if 'yards' not in result:
					log.warning("Result is a dropped kick, but I couldn't find any yards")
					resultMessage = "The receiver drops the kick, but something went wrong and I couldn't find where"
					success = False
				else:
					log.debug("Result is a dropped kick of {} yards".format(result['yards']))
					yards = result['yards']
					game.status.location = game.status.location + yards
					resultMessage = "It's dropped! Recovered by {} on the {}".format(game.team(game.status.possession).name, string_utils.getLocationString(game))
					game.status.waitingAction = Action.PLAY

			elif result['result'] == Result.TOUCHBACK:
				log.debug("Result is a touchback")
				setStateTouchback(game, game.status.possession.negate())
				resultMessage = "The kick goes into the end zone, touchback."

			elif result['result'] == Result.TOUCHDOWN:
				log.debug("Result is a touchdown")
				resultMessage = "It's dropped! The kicking team recovers and runs it into the end zone! Touchdown {}!".format(game.team(game.status.possession).name)
				scoreTouchdown(game, game.status.possession)

			elif result['result'] == Result.TURNOVER_TOUCHDOWN:
				log.debug("Result is a run back for touchdown")
				resultMessage = "It's run all the way back! Touchdown {}!".format(game.team(game.status.possession.negate()).name)
				scoreTouchdown(game, game.status.possession.negate())

		elif play in classes.normalPlays:
			numberResult, diffMessage, defenseNumber = getNumberDiffForGame(game, number)
			playSummary.defNum = defenseNumber

			log.debug("Executing normal play: {}".format(play))
			result = getPlayResult(game, play, numberResult)

			if play == Play.FIELD_GOAL:
				utils.addStat(game, 'fieldGoalsAttempted', 1)

			actualResult = result['result']
			if play == Play.PUNT and result['result'] == Result.GAIN and game.status.location + result['yards'] >= 100:
				result['result'] = Result.PUNT
				actualResult = Result.PUNT

			if result['result'] == Result.GAIN:
				if play == Play.PUNT:
					log.debug("Muffed punt. Ball moved from {} to {}".format(game.status.location, game.status.location + result['yards']))
					game.status.location = game.status.location + result['yards']
					game.status.yards = 10
					game.status.down = 1
					yards = result['yards']
					resultMessage = "The receiver drops the ball! {} recovers on the {}.".format(game.team(game.status.possession).name, string_utils.getLocationString(game))

				else:
					if 'yards' not in result:
						log.warning("Result is a gain, but I couldn't find any yards")
						resultMessage = "Result of play is a number of yards, but something went wrong and I couldn't find what number"
						success = False
					else:
						log.debug("Result is a gain of {} yards".format(result['yards']))
						gainResult, yards, resultMessage = executeGain(game, play, result['yards'])
						if gainResult != Result.ERROR:
							if yards is not None:
								actualResult = gainResult
						else:
							success = False

			elif result['result'] == Result.INCOMPLETE:
				log.debug("Result is an incomplete pass")
				actualResult, yards, resultMessage = executeGain(game, play, 0, True)

			elif result['result'] == Result.TOUCHDOWN:
				log.debug("Result is a touchdown")
				resultMessage = "It's a {} into the endzone! Touchdown {}!".format(play.name.lower(), game.team(game.status.possession).name)
				previousLocation = game.status.location
				utils.addStatRunPass(game, play, 100 - previousLocation)
				scoreTouchdown(game, game.status.possession)
				yards = 100 - previousLocation

			elif result['result'] == Result.FIELD_GOAL:
				log.debug("Result is a field goal")
				resultMessage = "The {} yard field goal is good!".format(100 - game.status.location + 17)
				utils.addStat(game, 'fieldGoalsScored', 1)
				scoreFieldGoal(game, game.status.possession)
				if utils.isGameOvertime(game):
					timeMessage = overtimeTurnover(game)
				else:
					setStateKickoff(game, game.status.possession)

			elif result['result'] == Result.PUNT:
				if 'yards' not in result:
					log.warning("Result is a punt, but I couldn't find any yards")
					resultMessage = "Result of play is a successful punt, but something went wrong and I couldn't find how long a punt"
				else:
					log.debug("Successful punt of {} yards".format(result['yards']))
					if utils.isGameOvertime(game):
						log.warning("A punt happened in overtime, this shouldn't have happened")
						resultMessage = "A punt happened, but it's overtime. This shouldn't be possible."
					else:
						resultMessage = executePunt(game, result['yards'])
						yards = result['yards']

			elif result['result'] in [Result.TURNOVER, Result.MISS]:
				log.debug("Play results in a turnover")
				if play == Play.RUN:
					utils.addStat(game, 'turnoverFumble', 1)
					resultMessage = "Fumble! The ball is dropped, {} recovers!".format(game.team(game.status.possession.negate()).name)
				elif play == Play.PASS:
					utils.addStat(game, 'turnoverInterceptions', 1)
					resultMessage = "Picked off! The pass is intercepted, {} ball!".format(game.team(game.status.possession.negate()).name)
				elif play == Play.FIELD_GOAL:
					if result['result'] == Result.TURNOVER:
						utils.addStat(game, 'turnoverFumble', 1)
						resultMessage = "It's blocked!"
					else:
						resultMessage = "The kick is wide."

				elif play == Play.PUNT:
					utils.addStat(game, 'turnoverFumble', 1)
					resultMessage = "It's blocked!"
				else:
					utils.addStat(game, 'turnoverFumble', 1)
					resultMessage = "It's a turnover!"
				if utils.isGameOvertime(game):
					timeMessage = overtimeTurnover(game)
				else:
					turnover(game)

			elif result['result'] == Result.TURNOVER_TOUCHDOWN:
				log.debug("Play results in a turnover and run back")
				if play == Play.RUN:
					utils.addStat(game, 'turnoverFumble', 1)
					resultMessage = "Fumble! The ball is dropped and it's run all the way back. Touchdown {}!".format(game.team(game.status.possession.negate()).name)
				elif play == Play.PASS:
					utils.addStat(game, 'turnoverInterceptions', 1)
					resultMessage = "Picked off! The pass is intercepted and it's run all the way back. Touchdown {}!".format(game.team(game.status.possession.negate()).name)
				elif play == Play.FIELD_GOAL:
					resultMessage = "It's blocked! The ball is picked up and run all the way back. Touchdown {}!".format(game.team(game.status.possession.negate()).name)
				elif play == Play.PUNT:
					utils.addStat(game, 'turnoverFumble', 1)
					resultMessage = "The punt is returned all the way! Touchdown {}!".format(game.team(game.status.possession.negate()).name)
				else:
					utils.addStat(game, 'turnoverFumble', 1)
					resultMessage = "It's a turnover and run back for a touchdown!"
				yards = game.status.location
				scoreTouchdown(game, game.status.possession.negate())
				if utils.isGameOvertime(game):
					output = utils.endGame(game, game.team(game.status.possession).name)
					timeMessage = "Game over! {} wins!\n\n{}".format(string_utils.flair(game.team(game.status.possession)), output)

			game.status.defensiveNumber = None

		elif play in classes.timePlays:
			if play == Play.KNEEL:
				log.debug("Running kneel play")
				actualResult = Result.KNEEL
				game.status.down += 1
				if game.status.down > 4:
					log.debug("Turnover on downs")
					if utils.isGameOvertime(game):
						timeMessage = overtimeTurnover(game)
					else:
						turnover(game)
					resultMessage = "Turnover on downs"
				else:
					resultMessage = "The quarterback takes a knee"

			elif play == Play.SPIKE:
				log.debug("Running spike play")
				actualResult = Result.SPIKE
				game.status.down += 1
				if game.status.down > 4:
					log.debug("Turnover on downs")
					if utils.isGameOvertime(game):
						timeMessage = overtimeTurnover(game)
					else:
						turnover(game)
					resultMessage = "Turnover on downs"
				else:
					resultMessage = "The quarterback spikes the ball"
			result = {'result': actualResult}

		else:
			log.debug("Something went wrong, invalid play: {}".format(play))
			resultMessage = "Something went wrong, invalid play: {}".format(play)
			success = False

	if runoffResult == RunStatus.STOP_QUARTER:
		messages = []
	else:
		messages = [resultMessage]
	timeOffClock = None
	if actualResult is not None and game.status.quarterType == QuarterType.NORMAL:
		if timeMessage is None:
			timeMessage, timeOffClock = updateTime(game, play, result['result'], actualResult, yards, startingPossessionHomeAway, timeOption, timeBetweenPlay)

	if timeMessageBetweenPlay is not None:
		messages.append(timeMessageBetweenPlay)

	if timeMessage is not None:
		messages.append(timeMessage)

	messages.append("{}\n\n".format(
		string_utils.getCurrentPlayString(game)
	))

	if diffMessage is not None:
		messages.append(diffMessage)

	playSummary.play = play
	playSummary.result = result['result'] if result is not None else None
	playSummary.actualResult = actualResult
	if actualResult in [Result.TURNOVER]:
		playSummary.yards = None
	else:
		playSummary.yards = yards
	playSummary.time = timeOffClock

	if success:
		game.status.plays.append(playSummary)

	messages.append(string_utils.getCoachString(game, game.status.waitingOn.negate()))

	return success, '\n\n'.join(messages)