Exemple #1
0
def checkInProgressGames(tourney_id):
	"""This is called periodically to look for games that are finished.  If we find
	a finished game, we record the winner"""

	#Find all games that we think aren't finished
	activeGames = games.Game.all().filter("winner =", None).filter("tourney_id =", tourney_id)

	for g in activeGames:
		#call WarLight's GameFeed API so that it can tell us if it's finished or not
		apiret = main.hitapi('/API/GameFeed?GameID=' + str(g.wlnetGameID), {})
		data = json.loads(apiret)
		state = data.get('state', 'err')

		if state == 'err': raise Exception("GameFeed API failed.  Message = " + data.get('error', apiret))

		if state == 'Finished':
			#It's finished. Record the winner and save it back.
			winner = findWinner(data,tourney_id)
			logging.info('Identified the winner of game ' + str(g.wlnetGameID) + ' is ' + str(winner))
			loser = findLoser(data,tourney_id)
			logging.info('Identified the loser of game ' + str(g.wlnetGameID) + ' is ' + str(loser))
			g.winner = winner.key().id()
			g.loser = loser.key().id()
			#g.winningTeamName = 'bob' #winner.key().name()
			g.dateEnded = datetime.datetime.now()
			g.save()
		else:
			#It's still going.
			
			#terminate games that have not started for a long time. 
			if state == 'WaitingForPlayers':
				latest_joining_time = g.dateCreated +datetime.timedelta(0,60*main.getHowLongYouHaveToJoinGames(tourney_id)) 
				if datetime.datetime.now() > latest_joining_time:
					logging.info('game ' + str(g.wlnetGameID) + ' has taken too long to start')
					#game has taken too long to start.
					
					game_id = g.key().id()
					logging.info('game_id='+str(game_id))
					for gp in games.GamePlayer.all().filter("tourney_id =", tourney_id):
						logging.info(gp)
					game_players = games.GamePlayer.all().filter("gameID =", game_id).filter("tourney_id =", tourney_id)
					players_ids = [p.playerID for p in game_players]
					logging.info(players_ids)
					random.shuffle(players_ids)
					g.winner = players_ids[0]
					g.loser = players_ids[1]
					g.legitimateGame = False
					g.dateEnded = datetime.datetime.now()
					g.save()
			
			
			logging.info('Game ' + str(g.wlnetGameID) + ' is not finished, state=' + state + ', numTurns=' + data['numberOfTurns']+' ----------------------------------------------------------------------------')
Exemple #2
0
def go(request):
	"""Create a player.	GET shows a blank form, POST processes it."""
	logging.info('in join.go')

	form = JoinForm(data=request.POST or None)

	#now deal with the form etc

	if not request.POST:
		return shortcuts.render_to_response('join.html', {'form': form})

	if not form.is_valid():
		return shortcuts.render_to_response('join.html', {'form': form})

	#see if we are letting more players join.
	tourney_id = int(form.clean_data['tourney_id'])
	tourney_clotconfig = main.getClotConfig(tourney_id)#.run(batch_size=1000)
	if not tourney_clotconfig:
		form.errors['tourney_id'] = 'tourney_id is invalid.'
		return shortcuts.render_to_response('join.html', {'form': form})
	
	players_are_gated_q = False
	if main.arePlayersGated(tourney_id, tourney_clotconfig):
		players_are_gated_q = True
		logging.info('players_are_gated_q = '+str(players_are_gated_q))
		return http.HttpResponseRedirect('/players_are_gated')

	if players.numPlayersParticipating(tourney_id) >= main.getMaximumNumberOfPlayers(tourney_id, tourney_clotconfig):
		logging.info('too many players')
		return http.HttpResponseRedirect('/cannot_join') 


	inviteToken = form.clean_data['inviteToken']

	#Call the warlight API to get the name, color, and verify that the invite token is correct
	apiret = main.hitapi('/API/ValidateInviteToken', { 'Token':  inviteToken })

	if not "tokenIsValid" in apiret:
		form.errors['inviteToken'] = 'The supplied invite token is invalid. Please ensure you copied it from WarLight.net correctly.'
		return shortcuts.render_to_response('join.html', {'form': form})

	tourney_password = str(form.clean_data['tourney_password'])
	if main.getIfRequirePasswordToJoin(tourney_id, tourney_clotconfig):
		if tourney_password != main.getTourneyPassword(tourney_id, tourney_clotconfig):
			form.errors['tourney_password'] = '******'
			return shortcuts.render_to_response('join.html', {'form': form})

	#Ensure this invite token doesn't already exist
	existing = players.Player.all().filter('inviteToken =', inviteToken).filter("tourney_id =", tourney_id).get()
	if existing:
		#If someone tries to join when they're already in the DB, just set their isParticipating flag back to true
		existing.isParticipating = True
		existing.save()
		return http.HttpResponseRedirect('tourneys/' + str(tourney_id) + '/player/' + str(existing.key().id()))

	data = json.loads(apiret)

	player_name = data['name']
	if type(data['name']) is unicode:
		logging.info('dealing with unicode player name ...')
		player_name = player_name.encode('ascii','ignore')  #this deals with special characters that would mess up our code, by removing them. 
		logging.info('player_name:')
		logging.info(player_name)
		logging.info('player-name looks ok or not?')

	player = players.Player(inviteToken=inviteToken, name=player_name, color=data['color'], isMember=data['isMember'].lower() == 'true') 

	if main.getIsMembersOnly(tourney_id, tourney_clotconfig) and not player.isMember:
		form.errors['inviteToken'] = 'This site only allows members to join.	See the Membership tab on WarLight.net for information about memberships.'
		return shortcuts.render_to_response('join.html', {'form': form})

	player.put()
	player.player_id = str(player.key().id())
	player.tourney_id = tourney_id
	player.save()
	logging.info("Created player")
	logging.info(player)
	
	return http.HttpResponseRedirect('tourneys/' + str(tourney_id) + '/player/' + str(player.key().id()))
Exemple #3
0
def checkInProgressGames(tourney_id, tourney_clotconfig):
	"""This is called periodically to look for games that are finished.  If we find
	a finished game, we record the winner"""

	#Find all games that we think aren't finished
	activeGames = games.Game.all().filter("winner =", None).filter("tourney_id =", tourney_id)#.run(batch_size=1000)

	for g in activeGames:
		#call WarLight's GameFeed API so that it can tell us if it's finished or not
		apiret = main.hitapi('/API/GameFeed?GameID=' + str(g.wlnetGameID), {})
		data = json.loads(apiret)
		state = data.get('state', 'err')
		
		#logging.info('+++++++++++++++++++++++++++++++++++++++++++')
		#logging.info('data: ' + str(data) + ' ')
		#logging.info('+++++++++++++++++++++++++++++++++++++++++++')
		
		player_data = data.get('players')
		
		#logging.info('player_data: ' + str(player_data) + ' ')
		#logging.info('+++++++++++++++++++++++++++++++++++++++++++')

		if state == 'err': raise Exception("GameFeed API failed.  Message = " + data.get('error', apiret))

		if state == 'Finished':
			#It's finished. Record the winner and save it back.
			winner = findWinner(data,tourney_id)
			logging.info('Identified the winner of game ' + str(g.wlnetGameID) + ' is ' + str(winner))
			loser = findLoser(data,tourney_id)
			logging.info('Identified the loser of game ' + str(g.wlnetGameID) + ' is ' + str(loser))
			g.winner = winner.key().id()
			g.loser = loser.key().id()
			g.dateEnded = datetime.datetime.now()
			g.save()
		else:
			#It's still going.
			logging.info('Game ' + str(g.wlnetGameID) + ' is not finished, state=' + state + ', numTurns=' + data['numberOfTurns']+' ----------------------------------------------------------------------------')
			
			#terminate games that have not started for a long time. 
			if state == 'WaitingForPlayers':
				latest_joining_time = g.dateCreated +datetime.timedelta(0,60*main.getHowLongYouHaveToJoinGames(tourney_id, tourney_clotconfig)) 
				if datetime.datetime.now() > latest_joining_time:
					logging.info('game ' + str(g.wlnetGameID) + ' has taken too long to start')
					logging.info('data: ' + str(data) + ' ')

					#find who Joined and who did not.
					good_player_wlids = []
					bad_player_wlids = []
					logging.info('')
					logging.info('players are:')
					for p in player_data:
						logging.info(p)
						if p['state']=='Playing':                  #only 'Playing' is the acceptable status - anything else means you did not join (ie ignored, or declined). 
							good_player_wlids.append(int(p['id']))
						else:
							bad_player_wlids.append(int(p['id']))
					
					#shuffle randomly in case we need to select winner at random
					random.shuffle(good_player_wlids)
					random.shuffle(bad_player_wlids)
					
					#set the winner and loser
					if len(good_player_wlids)==1 and len(bad_player_wlids)==1:
						logging.info('1 player Joined, the other did not ')
						g.winner = findPlayerID_FromWarlightID(good_player_wlids[0],tourney_id)
						g.loser = findPlayerID_FromWarlightID(bad_player_wlids[0],tourney_id)
					elif len(bad_player_wlids)==2:
						logging.info('neither player Joined, winner/loser will be selected randomly')
						g.winner = findPlayerID_FromWarlightID(bad_player_wlids[0],tourney_id)
						g.loser = findPlayerID_FromWarlightID(bad_player_wlids[1],tourney_id)
					else:
						assert False   #must not occur
					g.dateEnded = datetime.datetime.now()
					
					logging.info('player ' + str(g.winner) + ' won')
					logging.info('player ' + str(g.loser) + ' lost')
					g.save()