#!/usr/bin/perl -w # Tuesday, September 24, 2002 use strict; use diagnostics; #CONSTANTS & GLOBALS SECTION ############################################# # For the db and season files dont forget to modify sub checkThese use constant CONFIG_FILE => 'sim.cfg' ; use constant PLAYERS_DB => 'playersdb.csv' ; use constant GOALIES_DB => 'goaliesdb.csv' ; use constant TEAMS_DB => 'teamsdb.csv' ; use constant SEASON_P_DB => 'season_p_db.csv'; use constant SEASON_G_DB => 'season_g_db.csv'; use constant EMPTY => '' ; use constant TRUE => 1 ; use constant FALSE => 0 ; use constant SEASON_DIR => 'season' ; use constant TEAM_DIR => 'teams' ; use constant PLAYOFF_DIR => 'playoffs' ; use constant SCHED_DAT => 'schedule.dat' ; use constant SIM_SPEED => 0 ; use constant FREE_AGENT => '---' ; use constant SCORER_INDEX => 2 ; use constant PENALTY_INDEX => 4 ; my $BROWSER = "explorer"; my $START = 1; # flag only when game 1st up my $LEAGUE_NAME = "default"; my $SEASON_NAME = "default"; my $SEASON_NUM = 0; my $PLAYOFF_MODE = 0; #0=reg. season, 1=playoffs. my $ROUND = 0; #Playoff round my $SEASON_OVER_FLAG = 0; my $PP_FLAG = 0; my $HOME_ADVANTAGE = 5; my $P_P_ADVANTAGE = 3; my $GOALIE_STRENGTH = 2; my $OT = 1; # 0=3 per, 1=1 ot, 2=ot till per. my $DBUG = FALSE; #SUBROUTINE SECTION ###################################################### ##################INITIALIZE CONSTANTS################################# # This subroutine initializes all the constants and does some # houskeeping. # # INPUT: None. # OUTPUT: Constants are initialized to config file specs. # DEPENDENCES: openFile(CONFIG_FILE); # saveStats(CONFIG_FILE, $newline); # EXAMPLE CALL: initializeConstants(); # NOTE OF IMPORTANCE: . ####################################################################### sub initializeConstants { # If not there make it ============================================= my $not_there = 0; open(CFILE, CONFIG_FILE) || ($not_there = 1); if ($not_there){ setUpSimCfg(); } close(CFILE); # Take out all blank lines========================================== my @configuration = openFile(CONFIG_FILE); my $x = "\n"; my @c = (); my $newline = ""; foreach my $line (@configuration){ $line =~ s/$x//g; @c = split (/,/, $line); if (@c > 1){ $newline = "$newline$line\n"; } } saveStats(CONFIG_FILE, $newline); # Set this sessions constants ====================================== my @configln = openFile(CONFIG_FILE); foreach my $config (@configln){ chomp $config; my @config_array = split(/,/, $config); if ($config_array[0] eq "PLAYOFF_MODE"){ $PLAYOFF_MODE = $config_array[1];#0=reg. season, 1=playoffs. } elsif ($config_array[0] eq "SEASON_NAME"){ $SEASON_NAME = $config_array[1]; } elsif ($config_array[0] eq "SEASON_NUM"){ $SEASON_NUM = $config_array[1]; } elsif ($config_array[0] eq "LEAGUE_NAME"){ $LEAGUE_NAME = $config_array[1]; } elsif ($config_array[0] eq "START"){ $START = $config_array[1]; } elsif ($config_array[0] eq "BROWSER"){ $BROWSER = $config_array[1]; } elsif ($config_array[0] eq "SEASON_OVER_FLAG"){ $SEASON_OVER_FLAG = $config_array[1]; } elsif ($config_array[0] eq "OT"){ $OT = $config_array[1]; } elsif ($config_array[0] eq "ROUND"){ $ROUND = $config_array[1]; } } } ##################MAKE GAME ARRAY###################################### # This subroutine makes an array of lines which contain a # player and their information. The structure is as follows: # # [0 to 17]name,team,pts,plus/Minus,pen,pp,sh,gw,gt, # line(1-4) # # [18 & 19]*the last two are goalies: # name,team,pct,Start(1=start,2=backup) # # INPUT: team abr. example: nyr # OUTPUT: an array of the team ready for game # Dependencies: openFile(fileName),inspectLines(team), # changeLine(team,m or a[1,0]), saveStats, # countLines. # EXAMPLE CALL: @home=mkGameArray($team); # NOTE OF IMPORTANCE: Lines are checked and set if incorrect # - then checked again. Even so your # calling program should not continue # if the error message is prionted as # the game array will not work in the # game. ######################################################################## sub mkGameArray { my($t) = @_; my $d = 5; # debug indent if($DBUG){debug ($d, "\nMAKE GAME ARRAY:\n");} if($DBUG){debug ($d, "In ==> $t\n");} if(inspectLines($t) == 1){ changeLines($t, 0); if (inspectLines($t) == 1){ print"INVALID LINES\n"; } } my @array=(); my @stats=openFile(PLAYERS_DB); foreach my $teamMembers (@stats){ my @member = split(/,/,$teamMembers); if($member[1] eq $t && $member[9] < 5){ $array[@array] =join (',', @member); } } @stats=openFile(GOALIES_DB); foreach my $teamMembers (@stats){ my @member = split(/,/,$teamMembers); if($member[1] eq $t && $member[3] < 3){ $array[@array] =join (',', @member); } } #print "\n\nGame Array:\n@array\n"; #use this to print a lineup summary! if($DBUG){debug ($d, "END OF MAKE GAME ARRAY\n");} if($DBUG){debug ($d, "Out ==> @array\n");} return @array; } #GAME SET UP################################################# # This sub-routine will check to see if a team exist, and # then create a game array. # # INPUT: team id string like "nyr" # OUTPUT: an array from 1 to 20 of player values. # see mkGameArray() # DEPENDENCIES: checkTeam(), teamsArray("___"), mkGameArray(); # SAMPLE CALL: @home=gameSetUp($homeTeam); ############################################################# sub gameSetUp{ my($id) = @_; my $d = 3; #debug indent if($DBUG){debug ($d, "\nGAME SET UP:\n");} if($DBUG){debug ($d, "input ==> $id\n");} if($DBUG){debug ($d, 'if (!checkTeam($id, teamsArray("___"))) '. '==>');} if (!checkTeam($id, teamsArray("___"))){ # Does team exist? if($DBUG){debug(1, " true\n");} print "\n\nGAMESETUP:Team $id does not exist!\n\n"; next; } else {if($DBUG){debug ($d, " false\n");} } if($DBUG){debug ($d, 'if(inspectLines($id) == 1)==>');} if(inspectLines($id) == 1){ # Are lines set? if($DBUG){debug ($d, " true\n");} changeLines($id, 0); } else {if($DBUG){debug ($d, " false\n");} } if($DBUG){debug ($d, "return\n");} return mkGameArray($id); } ##TEST FOR GAME MISCONDUCT################################### # This subroutine tests for a pen greater than 10 min and # prints to the screen the approporiate pre message for the # game text. # # INPUT: int representing the penalty seconds # OUTPUT: string pre-message for the report # DEPENDANT: none # SAMPLE: testGameMis(); ############################################################# sub testGameMis{ my($sec) = @_; my $min=$sec/60; if($DBUG){ my ($p, $f, $l) = caller; print"---------- TEST GAME MISCONDUCT ------------\n"; print"$p:$f called from line $l\n"; print"--------------------------------------------\n"; print"minutes = $min\n"; } if($min>10){ return "Game Misconduct for "; }else{ return "$min:00 for "; } } ##SPECIFIC PENALTY########################################### # This routine will return a specific penalty randomly # # INPUT: none # OUTPUT: array (penalty string, seconds penalized, # description{1 = 1 person penalty # 2 = matching penalties # 3 = instigator for other team # 4 = instigator for this team # 5 = matching game misconducts # 6 = 1 person game misconduct}) # DEPENDANCIES: none # SAMPLE CALL: @penalty=specificPen(); ############################################################# sub specificPen{ my $instigator; my $penmin; my $SINGLE_PEN = 1; my $MATCHING_PEN = 2; my $INSTIGATOR_OTHER_PEN = 3; my $INSTIGATOR_THIS_PEN = 4; my $MATCH_MISCONDUCT = 5; my $GAME_MISCONDUCT = 6; sub pDesc{ my @a = (1,1,1,1,1,2,2,2,2,3,3,3,4,4,5); return $a[int(rand $#a)]; } sub fDesc{ my @a = (6,6,6,6,6,2,2,2,2,3,3,3,3,4,4,5); return $a[int(rand $#a)]; } if ($DBUG){ print"----------SPECIFIC PENALTY----------\n"; my $a = pDesc(); my $b = fDesc(); print"pDesc(rand) = $a\n"; print"fDesc(rand) = $b\n"; } ##SPECIFIC MINOR##################################### # This routine will return a string that specifies # the minor penalty. # # INPUT: none # OUTPUT: string # DEPEND: none # SAMPLE CALL: $pen=specificMinor(); ##################################################### sub specificMinor{ my $SINGLE_PEN = 1; my $MATCHING_PEN = 2; my $INSTIGATOR_OTHER_PEN = 3; my $INSTIGATOR_THIS_PEN = 4; my $MATCH_MISCONDUCT = 5; my $GAME_MISCONDUCT = 6; my $returnArrayandNum=int(rand 158); if($returnArrayandNum <= 25){ return ("High Sticking", 2*60, pDesc()); }elsif($returnArrayandNum <= 50){ return ("Holding", 2*60, pDesc()); }elsif($returnArrayandNum <= 75){ return ("Hooking", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 84){ return ("Cross Checking", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 96){ return ("Roughing", 2*60, pDesc()); }elsif($returnArrayandNum < 105){ return ("Interference", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 115){ return ("Tripping", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum < 120){ return ("Charging", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 123){ return ("Boarding", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum < 126){ return ("Playing with Broken Stick", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 129){ return ("Clipping", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum < 132){ return ("Delay of Game", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum < 135){ return ("To Many Men on the Ice", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 138){ return ("Displacing Goal Post", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum < 148){ return ("Elbowing", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 151){ return ("Keeing", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum < 154){ return ("Hand Pass", 2*60, $SINGLE_PEN); }elsif($returnArrayandNum < 157){ return ("Falling on Puck", 2*60, $SINGLE_PEN); }else{ return ("Throwing a Stick", 2*60, $SINGLE_PEN); } } ##SPECIFIC MAJOR##################################### # This routine will return a string that specifies # the major penalty. # # INPUT: none # OUTPUT: string # DEPEND: none # SAMPLE CALL: $pen=specificMajor(); ##################################################### sub specificMajor{ my $returnArrayandNum=int(rand 87); my $SINGLE_PEN = 1; my $MATCHING_PEN = 2; my $INSTIGATOR_OTHER_PEN = 3; my $INSTIGATOR_THIS_PEN = 4; my $MATCH_MISCONDUCT = 5; my $GAME_MISCONDUCT = 6; if($returnArrayandNum <= 7){ return ("Boarding", 5*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 13){ return ("Interference", 5*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 22){ return ("Elbowing", 5*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 23){ return ("Butt-Ending", 5*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 31){ return ("Charging", 5*60, $SINGLE_PEN); }elsif($returnArrayandNum < 36){ return ("Checking From Behind", 5*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 46){ return ("Cross-Checking", 5*60, pDesc()); }elsif($returnArrayandNum < 48){ return ("Head-Butting", 5*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 63){ return ("Hooking", 5*60, $SINGLE_PEN); }elsif($returnArrayandNum < 67){ return ("Kneeing", 5*60, $SINGLE_PEN); }else{ return ("Slashing", 5*60, pDesc()); } } ##SPECIFIC DOUBLE MINOR############################## # This routine will return a string that specifies # the double minor penalty. # # INPUT: none # OUTPUT: string # DEPEND: none # SAMPLE CALL: $pen=specificDM(); ##################################################### sub specificDM{ my $returnArrayandNum=int(rand 80); my $SINGLE_PEN = 1; my $MATCHING_PEN = 2; my $INSTIGATOR_OTHER_PEN = 3; my $INSTIGATOR_THIS_PEN = 4; my $MATCH_MISCONDUCT = 5; my $GAME_MISCONDUCT = 6; if($returnArrayandNum <= 1){ return ("Butt-Ending", 4*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 4){ return ("Head-Butting", 4*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 54){ return ("Slashing", 4*60, $SINGLE_PEN); }else{ return ("Spearing", 4*60, $SINGLE_PEN); } } ##SPECIFIC FIGHTING PENALTY MINUTES################## # This routine will return a integer that specifies # the fighting penalty. # # INPUT: none # OUTPUT: integer # DEPEND: none # SAMPLE CALL: $minutesPenalized=fightPenMin(); ##################################################### sub fightPenMin{ my $returnArrayandNum=int(rand 100); my $SINGLE_PEN = 1; my $MATCHING_PEN = 2; my $INSTIGATOR_OTHER_PEN = 3; my $INSTIGATOR_THIS_PEN = 4; my $MATCH_MISCONDUCT = 5; my $GAME_MISCONDUCT = 6; if($returnArrayandNum <= 65){ return 5; }elsif($returnArrayandNum <= 85){ return 2; }else{ return 999; } } ##SPECIFIC MISCONDUCT################################ # This routine will return a string that specifies # the misconduct penalty. # # INPUT: none # OUTPUT: string # DEPEND: none # SAMPLE CALL: $pen=specificMisconduct(); ##################################################### sub specificMisconduct{ my $returnArrayandNum=int(rand 157); my $SINGLE_PEN = 1; my $MATCHING_PEN = 2; my $INSTIGATOR_OTHER_PEN = 3; my $INSTIGATOR_THIS_PEN = 4; my $MATCH_MISCONDUCT = 5; my $GAME_MISCONDUCT = 6; if($returnArrayandNum <= 2){ return ("Charging the Goalie", 10*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 27){ return ("Checking from Behind", 10*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 32){ return ("Head-Butting", 10*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 52){ return ("Hooking", 10*60, $SINGLE_PEN); }elsif($returnArrayandNum <= 57){ return ("Kneeing", 10*60, $SINGLE_PEN); }elsif($returnArrayandNum < 107){ return ("Unsportsmanlike Conduct", 10*60, pDesc()); }elsif($returnArrayandNum <= 132){ return ("Slashing", 10*60, pDesc()); }else{ return ("Spearing", 10*60, $SINGLE_PEN); } } ##SPECIFIC GAME MISCONDUCT########################### # This routine will return a string that specifies # the misconduct penalty. # # INPUT: none # OUTPUT: string # DEPEND: none # SAMPLE CALL: $pen=specificGM(); ##################################################### sub specificGM{ my $returnArrayandNum=int(rand 155); my $SINGLE_PEN = 1; my $MATCHING_PEN = 2; my $INSTIGATOR_OTHER_PEN = 3; my $INSTIGATOR_THIS_PEN = 4; my $MATCH_MISCONDUCT = 5; my $GAME_MISCONDUCT = 6; if($returnArrayandNum <= 25){ return ("Checking from Behind", 999*60, $GAME_MISCONDUCT); }elsif($returnArrayandNum <= 30){ return ("Deliberate Injury", 999*60, $GAME_MISCONDUCT); }elsif($returnArrayandNum <= 35){ return ("Head-Butting", 999*60, $GAME_MISCONDUCT); }elsif($returnArrayandNum <= 50){ return ("Hooking", 999*60, $GAME_MISCONDUCT); }elsif($returnArrayandNum <= 55){ return ("Kicking", 999*60, $GAME_MISCONDUCT); }elsif($returnArrayandNum < 105){ return ("Unsportsmanlike Conduct", 999*60, $GAME_MISCONDUCT); }elsif($returnArrayandNum <= 130){ return ("Slashing", 999*60, $GAME_MISCONDUCT); }else{ return ("Spearing", 999*60, $GAME_MISCONDUCT); } } ###############MAIN################################## # Specify how many seconds in a minute for # readability my $minutes=60; # Get a random number that reflects the ratios of # actual pens. called in the NHL my $returnArrayandNum=int(rand 166); # Main algo. if($returnArrayandNum <= 100){#MINOR PENALTIES ################ return specificMinor(); }elsif($returnArrayandNum <= 121){#MAJOR PENALTIES ############ return specificMajor(); }elsif($returnArrayandNum <= 136){#DOUBLE MINOR PENALTIES ##### return specificDM(); }elsif($returnArrayandNum <= 150){#FIGHTING PENALTIES ######### $instigator=2;#Usually both go off my $penMin=fightPenMin();#Look for game miscond. if($penMin > 5){#Sometimes one will get game #misconduct for instigating return ("Fighting", $penMin*$minutes, fDesc()); } return ("Fighting", $penMin*$minutes, $MATCHING_PEN); }elsif($returnArrayandNum <= 164){#MISCONDUCT PENALTIES ####### return specificMisconduct(); }elsif($returnArrayandNum > 165){#GAME MISCONDUCT PENALTIES ### return specificGM(); }else{#PENALTY SHOT PENALTIES ####################### return ("penaltyShot", 0*$minutes, $SINGLE_PEN); } } ##################DECIDER#################################### # This subroutine takes a percentage and based on that # percentage number spits out either 1 (true) or 0 (false). # It will return 1 the % number of times. # # INPUT: an integer (percentage) # OUTPUT: Aboolean t=1, f=0 # DEPENDENCIES: None # SAMPLE CALL: $decided = decider($percentage); ############################################################# sub decider { my($percentage) = @_; if ($percentage >= int(rand (100 + int(rand(5))))){ return 1; }else{ return 0; } } ##D E C I D E O N T H R E E################################ # This routine returns a decision given three percentages # (Percent chance of three events). Works best with best # percentage first # # INPUT: 3 integers each a % of 100 # OUTPUT: an integer 1..3 which corresponds to the argument # chosen # DEPENDANCIES: decider($percentage) # SAMPLE CALL: $decision = decideOn3(70, 20, 10); ############################################################# sub decideOn3{ my($p1, $p2, $p3) = @_; if (decider($p1)){ return 1; } if (decider($p3)){ return 3; }else{ return 2; } } ##Event Subroutines########################################## # This routine returns a random event in a hockey game. # There are three events. Scoring chance, Penalty, Play # stoppage. # # INPUT: None # OUTPUT: random event (string) # DEPENDANCIES: decideOn3(per1, per2, per3); # SAMPLE CALL: $event = randEvent(); ############################################################# sub randEvent{ my @event=('Scoring Opportunity', 'Stoppage in play', 'Penalty'); my $SCORE_OPP = 60; # The % that this will happen my $STOP_PLAY = 30; # The % that this will happen my $PENALTY = 10; # The % that this will happen my $e = decideOn3($SCORE_OPP, $STOP_PLAY, $PENALTY); return $event[$e - 1]; } ##PRINT CLOCK################################################# # This routine will display the time on the game clock.. # # INPUT: array[0=period,1=minutes,2=seconds] # OUTPUT: to the screen the time. # DEPENDANCIES: none # SAMPLE CALL: printClock(@timeOfEvent); ############################################################# sub printClock{ my(@time) = @_; printf(" %02.0f%s%02.0f", $time[1], ":", $time[2]); } ##Game Clock################################################# # This routine runs a game clock for a hockey game. # This subroutine takes in an array(period, minutes, seconds) # and increments it. This subroutine returns that array. # Note that calling routine must check to see if $time[0] = # 4, and if so end of game. # # INPUT: array[0=period,1=minutes,2=seconds] # OUTPUT:array[0=period,1=minutes,2=seconds] # DEPENDANCIES: none # SAMPLE CALL: @timeOfEvent=gameClock(1, 0, 5); ############################################################# sub gameClock{ my(@time) = @_; my $seconds=($time[1]*60)+$time[2]; my $increment = (int(rand 1200/ (int(rand 75)+1)))+int(rand 15); #+int(rand (5..15)) because at #least 15 seconds between #events my $incrementTotal = $seconds+$increment; if($incrementTotal>1200){ $time[0]++; $incrementTotal=$incrementTotal-1200; } $time[1]= int($incrementTotal/60); $time[2]= int($incrementTotal%60); return @time; } ###############COUNT LINES################################### # This subroutine counts the players that are on each line. # This subroutine NEEDS the subroutine OPEN FILE. ############################################################# sub countLines { my($teamWanted) = @_; my @playersStats=openFile(PLAYERS_DB); my @goalieStats =openFile(GOALIES_DB); ###############LINE COUNT ARRAY###################### #This array is an array of numbers of players on #each line. [0] is line 1, [1] is line 2. [2] is #line 3, [3] is line 4, [4] is not dressed. my @lineCount = (0,0,0,0,0); ###############GOALIE COUNT ARRAY#################### #This array is an array of numbers of goalies on #each line. [0] is line 1 (starting), [1] is line 2 #(backup), [2] is not dressed. my @goalieCount = (0,0,0); ##################################################### foreach my $playerStat (@playersStats){ my @player = split(/,/,$playerStat); if ($player[1] eq $teamWanted && $player[9] == 1){ $lineCount[0]++; }elsif($player[1] eq $teamWanted && $player[9] == 2){ $lineCount[1]++; }elsif($player[1] eq $teamWanted && $player[9] == 3){ $lineCount[2]++; }elsif($player[1] eq $teamWanted && $player[9] == 4){ $lineCount[3]++; }elsif($player[1] eq $teamWanted && $player[9] == 5){ $lineCount[4]++; } } foreach my $goalieStat (@goalieStats){ my @goalie = split(/,/,$goalieStat); if ($goalie[1] eq $teamWanted && $goalie[3] == 1){ $goalieCount[0]++; }elsif($goalie[1] eq $teamWanted && $goalie[3] == 2){ $goalieCount[1]++; }elsif($goalie[1] eq $teamWanted && $goalie[3] == 3){ $goalieCount[2]++; } } } ##################WHO SCORED################################# # This subroutine takes a team array and decides who has # scored. # # INPUT: $index (integer)- this will index which set # of stats to decide from, @team (array) # OUTPUT: @scorers [scorer, assister, assister] # DEPENDENCIES: mkGameArray("$homeTeam") openFile(fileName), # inspectLines(team),changeLine # (team,m or a[1,0]), countLines, # saveStats(filepath, data) # # SAMPLE CALL: @scorer = whoScored(5, @homeTeam); # NOTE: Make sure that user tests to se if unassisted # is in the no. 1 spot in the array retuned for # reasons that the user program can use. ############################################################# sub whoScored { my($index, @t) = @_; my $assist1; my $assist2; my @p4; my $p3; my %p2; #DESTINY SUBROUTINE################################## # This subroutine takes a hash and spits out a member # of that has. The hash is first put into an array # and the hask keys with the biggest values are more # likely to be in th array more times than the other # lesser ones. # # IN: Hash key=name, value=points # OUT: Scorer # DEPEDANCIES: none # SAMPLE CALL: $player=destiny(%fun); ##################################################### sub destiny{ my(%p) = @_; my @d=(); my $howManyTimes=1;#better players more frequent foreach my $member (sort {$p{$a} <=> $p{$b}} keys %p){ for(my $i=$howManyTimes; $i>0; $i--){ $d[@d]= $member; } $howManyTimes++; } return $d[int(rand @d)-1]; }#################################################### #Random Line generator, 1st line is picked most my @lineDestiny=(1, 1, 1, 1, 2, 2, 2, 3, 3, 4); my $line=$lineDestiny[int(rand @lineDestiny)-1]; #Random assist generator, 1 assist is picked most #0=unassisted, 1=1 assist, 2=2assists my @assistsDestiny=(0, 1, 2, 2, 2, 2, 1); my $assist=$assistsDestiny[int(rand @assistsDestiny)-1]; #Make an array of potential scorers on the same line my @scorer_array=(); my @member=(); for(my $i=0; $i<(@t-2); $i++){ my $this=$t[$i]; my @member = split(/,/,$this); my $m=$member[9]; chomp $m; if($m eq $line){ $scorer_array[@scorer_array] = join (',', @member); } } #Make a hash and fill with players my %players=(); foreach my $eachScorer (@scorer_array){ my @points=split(/,/, $eachScorer); $players{$points[0]}=$points[2]; } #Call up destiny which sorts and returns a player. my $scorer=destiny(%players); #Check for asists then return scorers my @scorers=(); if($assist==0){ # If no assists then set scorers # to 1 player unassisted in the # position of the array to be # returned $scorers[0]=$scorer; $scorers[1]="unassisted"; }else{ # If there are assists then read in # the available scorers and choose # with destiny any player that is not # the scorer; put that assist person # into the number 2 spot in the array # to be returned. $scorers[0]=$scorer; %p2=();#EMPTY HASH foreach my $eachScorer (@scorer_array){ my @p=split(/,/, $eachScorer); if($p[0] ne $scorer){ $p2{$p[0]}=$p[2]; } } $assist1=destiny(%p2); $scorers[1]=$assist1; if($assist==2){# If there are two # assists than the second if will do # the same as the previous and put # that assist person into the 2 spot # in the array to be returned. my %p3=(); foreach my $eachScorer (@scorer_array){ @p4=split(/,/, $eachScorer); if($p4[0] ne $scorer && $p4[0] ne $assist1){ $p3{$p4[0]}= $p4[2]; } } $assist2=destiny(%p3); $scorers[2]=$assist2; }else{ $scorers[2]=" "; } } return @scorers;# This array will contain the # scorers and the potential # assist persons } #PUCK POSITION ############################################## # This sub-routine takes two integers, a power play flag, # a integer that specifies the home advantage, and the power # play advantage scaler ... # then returns a puck Position. The two integers are the plus # minus total of the teams. Remember that if 0 then the puck # is in the away zone. # # INPUT: Two integers(home and away +/-), # integer power play flag (0=reg, # 1=power-play[home], # 2=power-play[away], # home advantage integer. # OUTPUT: One integer (home zone=0 or away zone=1) # DEPENDENCIES: decider($percentage), # percentAdjustTo($percentage). # SAMPLE CALL: $whersPuck=puckPosition($homePlusMinus, # $awayPlusMinus, 0, 15, 50); ############################################################# sub puckPosition{ my($h, $a, $ppf, $ha, $ppa) = @_; if ($h < 1){ #Slide the values into a positive value $a = $a + abs($h); $h = 1; } if ($a < 1){ $h = $h + abs($a); $a = 1; } if($ppf==1){ # Is either team on the power play? $h=$h+$ppa; } elsif($ppf==2){ $a=$a+$ppa; } $h = (int(($h/($h+$a))*100))+$ha;## Set percentage $h = percentAdjustTo($h); return decider($h); ## Decide } ##################P E R C E N T A D J U S T T O ############ # This subroutine Takes an integer and adjusts it to stay # within the < high range and > lowrange bounds. # # INPUT: an integer (percentage) # OUTPUT: an integer (adjusted percentage) # DEPENDENCIES: None # SAMPLE CALL: $per = percentAdjustTo($per); ############################################################## sub percentAdjustTo{ my($p) = @_; my $LOW_RANGE = 30; my $HIGH_RANGE = 70; if ($p >= $HIGH_RANGE){ return $HIGH_RANGE; }elsif($p <= $LOW_RANGE){ return $LOW_RANGE; }else{ return $p; } } #GET VALUES################################################## # This sub-routine gets a certain value from an array and # adds them together. # # INPUT: values index, and range (from, to), # the array(coma delimited) # OUTPUT: value of all the data added together at the # given position # DEPENDENCIES: none # SAMPLE CALL: $homePlusMinus=getValues(3, 0, 17, @home); ############################################################# sub getValues { my($position, $from, $to, @a) = @_; my $value=0; my $line; for (my $i=$from; $i<$to; $i++){ $line=$a[$i]; my @player = split(/,/,$line); $value=$value+$player[$position]; } return $value; } #getGoalie Subroutine####################################### # This routine finds the starting goalie and returns their # names and save percentages. # # # INPUT: $goalieStrength, @wayTeamArray # OUTPUT: @goalies=(0=goalie name, 1=goalie name,) # DEPENDANCIES: getValue(#,#,@), # openFile(PLAYERS_DB); # inspectLines(team); # countLines(team); # (getValue(2, 19, @a); # Must have created the input! # SAMPLE CALL: @goalie=getGoalie($GOALIE_STRENGTH, @home); # NOTE: remember that each team array is 0-19 ############################################################# sub getGoalie{ my($STRENGTH, @a) = @_; my @ga=(); my $g1=getValue(3, 18, @a); # Last two pos. are goalies my $g2=getValue(3, 19, @a); # [3] is the line # if($g1>$g2){ $ga[0]=getValue(0, 19, @a); # Get name # Make % $ga[1]=int((getValue(2, 19, @a)*100)) + $STRENGTH; return @ga; }else{ $ga[0]=getValue(0, 18, @a); $ga[1]=int((getValue(2, 18, @a)*100)) + $STRENGTH; return @ga; } } #GET VALUE################################################### # This sub-routine gets a certain value from an array. # # INPUT: values index, which line, # the array(coma delimited) # OUTPUT: value of the data # DEPENDENCIES: none # SAMPLE CALL: $homePlusMinus=getValue(3, 17, @home); ############################################################# sub getValue { my($position, $from, @a) = @_; my $value=0; my $line=$a[$from]; my @player = split(/,/,$line); $value=$player[$position]; return $value; } ##UPDATE PENALTY BOX########################################## # This routine will check the penalty box hash and delete any # keys that contain expired box inhabitants. # # INPUT: $integer that is seconds into the game, # %hash that is the pen box hash # OUTPUT: %hash without the expired keys # DEPENDANCIES: none # SAMPLE CALL: %penaltyBox= # updateBox($secondCount,%penaltyBox); ############################################################# sub updateBox{ my($s,%pb) = @_; foreach my $i (keys %pb){ if($pb{$i}<$s){ delete $pb{$i}; } } return %pb; } ##CURRENT SECOND############################################# # This routine will return the current second in the game # starting at 0 and continuing on till the end of game. # # INPUT: array[0=period,1=minutes,2=seconds] # OUTPUT: $integer (seconds into the game) # DEPENDANCIES: none # SAMPLE CALL: $SecondCount=currentSecond(@timeOfEvent); ############################################################# sub currentSecond{ my(@time) = @_; return (($time[0]-1)*1200)+($time[1]*60)+$time[2]; } ##C H E C K T H E B O X ################################### # This routine will check the hash for a value anf then # return the array that dosent test positive. # # INPUT: An integer (row index to check), # and array (teams lineup file or game array) # OUTPUT: An array [0] = player 1 (scorer etc.), # [1] = unassisted player 2, # [2] = player 2 or 3 (assist etc.), # DEPENDANCIES: whoScored(4, @home); # mkGameArray("$homeTeam"); # openFile(fileName); # inspectLines(team); # changeLine(team,m or a[1,0]); # countLines(): # saveStats(filepath, data); # countLines(); # SAMPLE CALL: @homePenPerson = checkTheBox($PEN_INDEX, # $hashReference, # @home); ############################################################# sub checkTheBox{ my($type, $hshref, @lineup) = @_; my @output = ("X", "X", "X"); #Container for the output my %hash = (); %hash = %$hshref; my @temp = (); @temp = %hash; while (1){ @output = ("X", "X", "X"); @output = whoScored($type, @lineup); if ($output[1] eq "unassisted"){ $output[2] = "unassisted"; } if ((!(exists($hash{$output[0]}))) && #check player (!(exists($hash{$output[1]}))) && #check player (!(exists($hash{$output[2]})))){ #check linemate return @output; } } } ##P E N A L T Y B O X B O X O F F I C I A L ###### # This routine will lok into the penalty box (hash) # and set the penalty flags accordingly. # 0 = equal pressure 1 = home pp, and 2 = away pp. # # INPUT: string(home team), # string(away team), # hash(penalty box) # OUTPUT: integer (penalty flag) # DEPEND: mkGameArray("$home"); # openFile(fileName); # inspectLines(team); # changeLine(team,m or a[1,0]); # saveStats(PLAYERS_DB, @playersStats); # countLines(); # doesPlayerExist($name, @teamArray); # checkTeam(); # teamsArray("___"); # SAMPLE CALL: $flag = penBoxOfficial($home, # $away, # %penaltyBox); ##################################################### sub penBoxOfficial{ my ($homeRef, $awayRef, %penaltyBox) = @_; my $EVEN_STRENGTH = 0; #return flag my $HOME_PP = 1; #return flag my $AWAY_PP = 2; #return flag my $homeFlagCount = 0; my $awayFlagCount = 0; my $elements = keys %penaltyBox; my @homeTeamArray = @$homeRef; my @awayTeamArray = @$awayRef; if ($elements <= 0){ return $EVEN_STRENGTH; }else{ foreach my $element(keys %penaltyBox){ if(doesPlayerExist($element, @homeTeamArray)){ $homeFlagCount++; }elsif(doesPlayerExist($element, @awayTeamArray)){ $awayFlagCount++; } } } if ($homeFlagCount > $awayFlagCount){ return $AWAY_PP; }elsif($homeFlagCount < $awayFlagCount){ return $HOME_PP; }else{ return $EVEN_STRENGTH; } } ##D O E S P L A Y E R E X I S T ################### # This routine will return a boolean which will # reflect the search for a specific player in a team # array. # # INPUT: string(name), array(team array) # OUTPUT: boolean 1 = true, 0 = false # DEPEND: none # SAMPLE CALL: if(doesPlayeExist($name, @teamArray)) ##################################################### sub doesPlayerExist{ my ($name, @team) = @_; foreach (@team){ if (m/$name/g){ return TRUE; } } return FALSE; } ##C L O C K T O S T R I N G ############################# # This routine will return the time on the game clock.. # # INPUT: array[0=period,1=minutes,2=seconds] # OUTPUT: string (Formatted Time). # DEPENDANCIES: none # SAMPLE CALL: $t = clockToString(@timeOfEvent); ############################################################# sub clockToString{ my(@time) = @_; my $rString = ""; if ($time[1] < 10){ $rString = " "; } $rString = $rString . $time[1] . ":"; if ($time[2] < 10){ $rString = $rString . "0"; } return $rString . $time[2]; } ## H A N D L E E V E N T ################################### # This routine will set the current results data structure to # reflect this event. # # INPUT: int (current period) # string (formatted time of event) # string (goal, shot, pen) # string (player name) # string (player two name, null if none) # string (player three name, null if none) # string (team name) # string (home, away) # int (power play flag)1=homepp, 2=awaypp, 0=evenstrength # int (penalty seconds) # string (penalty description) # array (the return array) # [0] = 1st period home team points # [1] = 2nd period home team points # [2] = 3rd period home team points # [3] = OT periods home team points # [4] = 1st period away team points # [5] = 2nd period away team points # [6] = 3rd period away team points # [7] = OT periods away team points # [8] = 1st period events list(; seperated) # [9] = 2nd period events list(; seperated) # [10] = 3rd period events list(; seperated) # [11] = OT period events list(; seperated) # [12] = 1st period home team shots # [13] = 2nd period home team shots # [14] = 3rd period home team shots # [15] = OT periods home team shots # [16] = 1st period away team shots # [17] = 2nd period away team shots # [18] = 3rd period away team shots # [19] = OT periods away team ahots # [20] = home power play conversions # [21] = away power play conversions # [22] = home goalie # [23] = away goalie # [24] = home pen minutes # [25] = away pen minutes # [26] = periods # [27] = game misconducts list (, seperated) # [28] = home Full Team Name String # [29] = away Full Team Name String # [30] = game winning goal scorer # OUTPUT: array (the above messauged a little) # DEPENDANCIES: none # SAMPLE CALL: handleEvent($currentPeriod, # $time, # $EVENT, # $player1, # $player2, # $player3, # $team, # $H_OR_A, # $powerPlayFlag, # $penSec, # $penDesc, # $gameMisconductFlag, # @results); ############################################################# sub handleEvent{ my($currentPeriod, $currentTime, $event, $p1, $p2, $p3, $teamName, $team, $ppFlag, $pen_sec, $pd, $gameMisconductFlag, @r) = @_; my $pnMin = ($pen_sec/60); # S E T U P P L A Y E R S S T R I N G ############# my $playerString = ""; $playerString = $p1; if ($p2 ne "unassisted" && $p2 ne "null"){ $playerString = $playerString . ", " . $p2; if ($p3 ne "unassisted" && $p3 ne "null" && $p3 ne "" && $p3 ne " "){ $playerString = $playerString . ", " . $p3; } } # P R O C E S S A G O A L############################# if ($event eq "goal" && $team eq "home"){ if ($currentPeriod == 1){ $r[0]++; if ($r[8] eq "0"){$r[8] =~ s/0//} $r[8] = $r[8] . ";" . $currentTime . " " . $event . " " . $teamName . " (" . $playerString . ")"; }elsif ($currentPeriod == 2){ $r[1]++; if ($r[9] eq "0"){$r[9] =~ s/0//} $r[9] = $r[9] . ";" . $currentTime . " " . $event . " " . $teamName . " (" . $playerString . ")"; }elsif ($currentPeriod == 3){ $r[2]++; if ($r[10] eq "0"){$r[10] =~ s/0//} $r[10] = $r[10] . ";" . $currentTime . " " . $event . " " . $teamName . " (" . $playerString . ")"; }elsif ($currentPeriod > 3){ $r[3]++; if ($r[11] eq "0"){$r[11] =~ s/0//} $r[11] = $r[11] . ";" . $currentTime . " " . $event . " " . $teamName . " (" . $playerString . ")"; } # P R O C E S S P P C O N V E R S I O N ############ if ($ppFlag == 1){ $r[20]++; } } elsif ($event eq "goal" && $team eq "away"){ if ($currentPeriod == 1){ $r[4]++; if ($r[8] eq "0"){$r[8] =~ s/0//} $r[8] = $r[8] . ";" . $currentTime . " " . $event . " " . $teamName . " (" . $playerString . ")"; }elsif ($currentPeriod == 2){ $r[5]++; if ($r[9] eq "0"){$r[9] =~ s/0//} $r[9] = $r[9] . ";" . $currentTime . " " . $event . " " . $teamName . " (" . $playerString . ")"; }elsif ($currentPeriod == 3){ $r[6]++; if ($r[10] eq "0"){$r[10] =~ s/0//} $r[10] = $r[10] . ";" . $currentTime . " " . $event . " " . $teamName . " (" . $playerString . ")"; }elsif ($currentPeriod > 3){ $r[7]++; if ($r[11] eq "0"){$r[11] =~ s/0//} $r[11] = $r[11] . ";" . $currentTime . " " . $event . " " . $teamName . " (" . $playerString . ")"; } # P R O C E S S P P C O N V E R S I O N ############ if ($ppFlag == 2){ $r[21]++; } # P R O C E S S A S H O T ############################# } elsif ($event eq "shot" && $team eq "home"){ if ($currentPeriod == 1){ $r[12]++; }elsif ($currentPeriod == 2){ $r[13]++; }elsif ($currentPeriod == 3){ $r[14]++; }elsif ($currentPeriod > 3){ $r[15]++; } } elsif ($event eq "shot" && $team eq "away"){ if ($currentPeriod == 1){ $r[16]++; }elsif ($currentPeriod == 2){ $r[17]++; }elsif ($currentPeriod == 3){ $r[18]++; }elsif ($currentPeriod > 3){ $r[19]++; } # P R O C E S S A P E N A L T Y ############################### } elsif ($event eq "pen"){ if ($currentPeriod == 1){ if ($r[8] eq "0"){$r[8] =~ s/0//} $r[8] = $r[8] . ";" . $currentTime . " " . $event . " " . $teamName . " " . $playerString; if ($gameMisconductFlag == 0){ $r[8] = $r[8] . " " . $pnMin . " min. for " . $pd; } else { $r[8] = $r[8] . " Game Misconduct for " . $pd; } }elsif ($currentPeriod == 2){ if ($r[9] eq "0"){$r[9] =~ s/0//} $r[9] = $r[9] . ";" . $currentTime . " " . $event . " " . $teamName . " " . $playerString; if ($gameMisconductFlag == 0){ $r[9] = $r[9] . " " . $pnMin . " min. for " . $pd; } else { $r[9] = $r[9] . " Game Misconduct for " . $pd; } }elsif ($currentPeriod == 3){ if ($r[10] eq "0"){$r[10] =~ s/0//} $r[10] = $r[10] . ";" . $currentTime . " " . $event . " " . $teamName . " " . $playerString; if ($gameMisconductFlag == 0){ $r[10] = $r[10] . " " . $pnMin . " min. for " . $pd; } else { $r[10] = $r[10] . " Game Misconduct for " . $pd; } }elsif ($currentPeriod > 3){ if ($r[11] eq "0"){$r[11] =~ s/0//} $r[11] = $r[11] . ";" . $currentTime . " " . $event . " " . $teamName . " " . $playerString; if ($gameMisconductFlag == 0){ $r[11] = $r[11] . " " . $pnMin . " min. for " . $pd; } else { $r[11] = $r[11] . " Game Misconduct for " . $pd; } } if($DBUG){ print "----------HANDLE EVENT----------\n"; print "-------ADDING PENS BEFORE-------\n"; print "team: $team\n"; print "Home pen min.: $r[24]\n"; print "Away pen min.: $r[25]\n"; print "Game Misconduct Flag: $gameMisconductFlag\n"; print "Pen. min. to add: $pnMin\n"; } if($gameMisconductFlag == FALSE){ if ($team eq "home"){ $r[24] = $r[24] + $pnMin; } else { $r[25] = $r[25] + $pnMin; } } if($DBUG){ print "-------ADDING PENS AFTER-------\n"; print "team: $team\n"; print "Home pen min.: $r[24]\n"; print "Away pen min.: $r[25]\n"; print "Game Misconduct Flag: $gameMisconductFlag\n"; print "Pen. min. to add: $pnMin\n"; } if ($gameMisconductFlag > 0){ if ($r[27] eq 0){ $r[27] =~ s/0//; $r[27] = $playerString; }else{ $r[27] = $r[27] . ", " . $playerString; } } } return @r; } ####################################################################### # M A K E T E A M N A M E H A S H ############# ################# # This subroutine opens a configuration file specified in the # first variable. It then checks the teams in the stats files # against the team name config file to make sure every alias has a # name. Then it returns a team alias hash. # # IN: Nothing # OUT: hash (key=alias, value=realname string) # SUBROUTINES NEEDED: openFile(TEAMS_DB) # teamsArray("___") # saveStats(TEAMS_DB, @fileStuff) # EXAMPLE: %teams = makeTeamNameHash(); ####################################################################### sub makeTeamNameHash { my @fileStuff = openFile(TEAMS_DB); my $teamName = "det"; my @teams =teamsArray("___"); my %fileTeams = (); my ($team_name, $owner_info, $address, $contact_info, $arena_name, $seating_cap); # Ask a question and get an answer validated by the operator! sub get_team_info{ my($q)=@_; my($value, $answer); while(1){ print$q; $value = ; chomp $value; $value=saftyFirst($value); print "Are you sure it is \"$value\"? (y or n) "; $answer = ; chomp $answer; if ($answer eq "y" || $answer eq "Y"){ last; } } return $value; } # Read in lines from the config. file############################### foreach my $line (@fileStuff){ my @teamLine = split(/,/, $line); $fileTeams{$teamLine[0]}=$teamLine[1]; } # See if all teams e are in the config file #################### foreach my $team (@teams){ my @team_line = split(/,/, $team); if (!(exists $fileTeams{$team}) && $team_line[0] ne FREE_AGENT){ # If not get the team info and place it in the alias array $team_name = get_team_info("What does $team stand for? "); $owner_info = get_team_info("Who owns $team_name? "); $address = get_team_info("What is the location or ". "address for $team_name? "); $contact_info = get_team_info("What is the e-mail or ". "contact info for $owner_info? "); $arena_name = get_team_info("What is the arena name at ". "$address? "); $seating_cap = get_team_info("What is the seating capacity at ". "$arena_name? "); #Enter info into the teamsDB buffer. push(@fileStuff, "$team,". #[0] = team name abbr. "$team_name,". #[1] = full name ",". #[2] = conference ",". #[3] = division "0,". #[4] = games "0,". #[5] = wins "0,". #[6] = loses "0,". #[7] = ties "0,". #[8] = points "0.0,". #[9] = win% "0,". #[10] = Goals For "0,". #[11] = Goals Against "0,". #[12] = Power Play Goals "0,". #[13] = PPM "0.0,". #[14] = PP% "0,". #[15] = PM "0.0,". #[16] = PK% "$owner_info,". #[10] = Owner Info "$address,". #[11] = Address "$contact_info,". #[12] = Contact Info "$arena_name,". #[13] = Arena Name "$seating_cap,". #[14] = Seating Capacity "0\n"); #[15] = Last Games Attendance } elsif ($team_line[0] eq FREE_AGENT){ push(@fileStuff, "---,". #[0] = team name abbr. "Free Agents,". #[1] = full name "-,". #[2] = conference "-,". #[3] = division "0,". #[4] = games "0,". #[5] = wins "0,". #[6] = loses "0,". #[7] = ties "0,". #[8] = points "0.0,". #[9] = win% "0,". #[10] = Goals For "0,". #[11] = Goals Against "0,". #[12] = Power Play Goals "0,". #[13] = PPM "0.0,". #[14] = PP% "0,". #[15] = PM "0.0,". #[16] = PK% "BHL,". #[10] = Owner Info "-,". #[11] = Address "-,". #[12] = Contact Info "-,". #[13] = Arena Name "-,". #[14] = Seating Capacity "0\n"); #[15] = Last Games Attendance } } # Publish the alias array to the TEAMS_DB saveStats(TEAMS_DB, @fileStuff); # Read in lines from the new config. file######################### foreach my $line (@fileStuff){ my @teamLine = split(/,/, $line); $fileTeams{$teamLine[0]}=$teamLine[1]; } return %fileTeams; } ################## SAFTY FIRST ######################################## # Takes commas out of user input intended for comma delimited files.. # # INPUT: String (line of input to be checkeds/). # OUTPUT: String (fixed) # DEPENDENCES: None # EXAMPLE CALL: saftyFirst($string); # NOTE OF IMPORTANCE: . ####################################################################### sub saftyFirst { my ($input) = @_; $input =~ s|,+| |g; return $input; } ##################GAME ARRAY ZEROER OUTER ############################## # This subroutine takes a game array and zeroes out each field so that # we can keep track of the game statistics. # # Game arrays: # [0 to 17] # line(1-4) # # [18 & 19]*the last two are goalies: # Start(1=start,2=backup) # # INPUT: int (Index to ignore) # array (game array as specified above) # OUTPUT: array (above players with zeroed out stats) # Dependencies: None # EXAMPLE CALL: @hGameStats=gameArrayZeroerOuter(0, @aTeam); ######################################################################## sub gameArrayZeroerOuter { my($LINE_INDEX, @gameArray) = @_; my @arrayToReturn = (); foreach my $line (@gameArray){ #read each line (gm array) my @player = split(/,/,$line); #split line to line array my $i = 0; foreach my $index (@player){ #read every thing in array if ($i <= 1 || $i == $LINE_INDEX) { #is it name, team, line? $player[$i] = $index; #then just copy } else { #or is it a stat $player[$i] = 0; #then set to 0 } $i++; } $line = join (',', @player); #join new array into line $line = $line . "\n"; #add a new line $arrayToReturn[@arrayToReturn] = $line;#put line in new game array } return @arrayToReturn } ################## G E T S T A T ##################################### # This subroutine takes an item that needs to be returned and returns it # # INPUT: string (Index name [name,team,pts,p_m,pen, # ppg,shg,gwg,gtg,line,shts,gls,asts, # s_p,g_ln,w,l,t,sav,ga, gaa, g_gms, gms]), # string (player), # array (game array). # OUTPUT: array (game array updated) # Dependencies: None # EXAMPLE CALL: $stat=getStat($stat_name, $player, @game_array); # NOTE OF IMPORTANCE: # 1) goaliesdb.csv - goalie stats file has the following formatt: # full name, team abbr, save %, line, wins, losses, ties, # saves, goals against, goals against average, games # # 2) players.csv - player stats file has the following form: # full name, team abbr, pts, +/-, pen, ppg, shg, gwg, gtg, # line, shots, goals, assists, games ######################################################################## sub getStat { my($index, $player, @gameArray) = @_; foreach my $line (@gameArray){ #read each line (gm array) my @pLine = split(/,/,$line); #split line to line array if ($pLine[0] eq $player){ if ($index eq "name"){return $pLine[0]; } if ($index eq "team"){return $pLine[1]; } if ($index eq "pts") {return $pLine[2]; } if ($index eq "p_m") {return $pLine[3]; } if ($index eq "pen") {return $pLine[4]; } if ($index eq "ppg") {return $pLine[5]; } if ($index eq "shg") {return $pLine[6]; } if ($index eq "gwg") {return $pLine[7]; } if ($index eq "gtg") {return $pLine[8]; } if ($index eq "line"){return $pLine[9]; } if ($index eq "shts"){return $pLine[10];} if ($index eq "gls") {return $pLine[11];} if ($index eq "asts"){return $pLine[12];} if ($index eq "gms") {return $pLine[13];} if ($index eq "s_p") {return $pLine[2]; } if ($index eq "g_ln"){return $pLine[3]; } if ($index eq "w") {return $pLine[4]; } if ($index eq "l") {return $pLine[5]; } if ($index eq "t") {return $pLine[6]; } if ($index eq "sav") {return $pLine[7]; } if ($index eq "ga") {return $pLine[8]; } if ($index eq "gaa") {return $pLine[9]; } if ($index eq "g_gms"){return $pLine[10];} } } } ##################P O S T S T A T #################################### # This subroutine takes an item that needs to be recorded in the game # stat file and adds it to that file. # # INPUT: string (Index name [name,team,pts,p_m,pen, # ppg,shg,gwg,gtg,line,shts,gls,asts, # s_p,g_ln,w,l,t,sav,ga, gaa, g_gms, gms]), # string (player), # string or integer (thing to post), # string (add, sub, write), # array (game array). # OUTPUT: array (game array updated) # Dependencies: None # EXAMPLE CALL: @aTeam=postStat("p_goal", $player, $thing, # $add_write_flag, @aTeam); # NOTE OF IMPORTANCE: # 1) goaliesdb.csv - goalie stats file has the following formatt: # full name, team abbr, save %, line, wins, losses, ties, # saves, goals against, goals against average, games # # 2) players.csv - player stats file has the following form: # full name, team abbr, pts, +/-, pen, ppg, shg, gwg, gtg, # line, shots, goals, assists, games ######################################################################## sub postStat { my($index, $player, $thing, $f, @gameArray) = @_; my @arrayToReturn = (); foreach my $line (@gameArray){ #read each line (gm array) chomp $line; my @pLine = split(/,/,$line); #split line to line array if ($pLine[0] eq $player){ if ($f eq "add"){ if ($index eq "name"){$pLine[0] = $pLine[0] . $thing; } if ($index eq "team"){print"ERROR: cant change team\n";} if ($index eq "pts") {$pLine[2] = $pLine[2] + $thing; } if ($index eq "p_m") {$pLine[3] = $pLine[3] + $thing; } if ($index eq "pen") {$pLine[4] = $pLine[4] + $thing; } if ($index eq "ppg") {$pLine[5] = $pLine[5] + $thing; } if ($index eq "shg") {$pLine[6] = $pLine[6] + $thing; } if ($index eq "gwg") {$pLine[7] = $pLine[7] + $thing; } if ($index eq "gtg") {$pLine[8] = $pLine[8] + $thing; } if ($index eq "line"){print"ERROR: cant change line\n";} if ($index eq "shts"){$pLine[10] = $pLine[10] + $thing; } if ($index eq "gls") {$pLine[11] = $pLine[11] + $thing; } if ($index eq "asts"){$pLine[12] = $pLine[12] + $thing; } if ($index eq "gms") {$pLine[13] = $pLine[13] + $thing; } if ($index eq "s_p") {print"ERROR: cant add % \n"; } if ($index eq "g_ln"){print"ERROR: cant change line\n";} if ($index eq "w") {$pLine[4] = $pLine[4] + $thing; } if ($index eq "l") {$pLine[5] = $pLine[5] + $thing; } if ($index eq "t") {$pLine[6] = $pLine[6] + $thing; } if ($index eq "sav") {$pLine[7] = $pLine[7] + $thing; } if ($index eq "ga") {$pLine[8] = $pLine[8] + $thing; } if ($index eq "gaa") {$pLine[9] = $pLine[8] / $pLine[10];} if ($index eq "g_gms"){$pLine[10]= $pLine[10]+ $thing; } }elsif($f eq "write"){ if ($index eq "name"){$pLine[0] = $thing;} if ($index eq "team"){$pLine[1] = $thing;} if ($index eq "pts") {$pLine[2] = $thing;} if ($index eq "p_m") {$pLine[3] = $thing;} if ($index eq "pen") {$pLine[4] = $thing;} if ($index eq "ppg") {$pLine[5] = $thing;} if ($index eq "shg") {$pLine[6] = $thing;} if ($index eq "gwg") {$pLine[7] = $thing;} if ($index eq "gtg") {$pLine[8] = $thing;} if ($index eq "line"){$pLine[9] = $thing;} if ($index eq "shts"){$pLine[10] = $thing;} if ($index eq "gls") {$pLine[11] = $thing;} if ($index eq "asts"){$pLine[12] = $thing;} if ($index eq "gms") {$pLine[13] = $thing;} if ($index eq "s_p") {$pLine[2] = $thing;} if ($index eq "g_ln"){$pLine[3] = $thing;} if ($index eq "w") {$pLine[4] = $thing;} if ($index eq "l") {$pLine[5] = $thing;} if ($index eq "t") {$pLine[6] = $thing;} if ($index eq "sav") {$pLine[7] = $thing;} if ($index eq "ga") {$pLine[8] = $thing;} if ($index eq "gaa") {$pLine[9] = $thing;} if ($index eq "g_gms"){$pLine[10]= $thing;} }elsif($f eq "sub"){ if ($index eq "name"){print"ERROR: cant sub name\n";} if ($index eq "team"){print"ERROR: cant sub team\n";} if ($index eq "pts") {$pLine[2] = $pLine[2] - $thing; } if ($index eq "p_m") {$pLine[3] = $pLine[3] - $thing; } if ($index eq "pen") {$pLine[4] = $pLine[4] - $thing; } if ($index eq "ppg") {$pLine[5] = $pLine[5] - $thing; } if ($index eq "shg") {$pLine[6] = $pLine[6] - $thing; } if ($index eq "gwg") {$pLine[7] = $pLine[7] - $thing; } if ($index eq "gtg") {$pLine[8] = $pLine[8] - $thing; } if ($index eq "line"){print"ERROR: cant change line\n";} if ($index eq "shts"){$pLine[10] = $pLine[10] - $thing; } if ($index eq "gls") {$pLine[11] = $pLine[11] - $thing; } if ($index eq "asts"){$pLine[12] = $pLine[12] - $thing; } if ($index eq "gms") {$pLine[13] = $pLine[13] - $thing; } if ($index eq "s_p") {print"ERROR: cant sub % \n"; } if ($index eq "g_ln"){print"ERROR: cant change line\n";} if ($index eq "w") {$pLine[4] = $pLine[4] - $thing; } if ($index eq "l") {$pLine[5] = $pLine[5] - $thing; } if ($index eq "t") {$pLine[6] = $pLine[6] - $thing; } if ($index eq "sav") {$pLine[7] = $pLine[7] - $thing; } if ($index eq "ga") {$pLine[8] = $pLine[8] - $thing; } if ($index eq "gaa") {print"ERROR: cant sub % \n";} if ($index eq "g_gms"){$pLine[10]= $pLine[10]- $thing; } }else{ print "postStat: Error, undefined 4th argument\n"; } } $line = join (',', @pLine); #join new array into line $line = $line . "\n"; #add a new line $arrayToReturn[@arrayToReturn] = $line;#put line in new game array } return @arrayToReturn; } ################## G E T L I N E M A T E S########################### # This subroutine takes a player name and gets all their line mates. # # INPUT: string (players name), # array (teams game array) # OUTPUT: array (5 linemates[0-4]) # Dependencies: getLine($name, @array) # EXAMPLE CALL: @line_mates = getLineMates($player, @team); ######################################################################## sub getLineMates { my($player, @game_array) = @_; my @line_mates = (); my $line_number = getLine($player, @game_array); for (my $i = 0; $i <(@game_array -2); $i++){ my $this_guy = $game_array[$i]; my @this_guys_stats = split (/,/, $this_guy); my $this_guys_line = $this_guys_stats[9]; if ($this_guys_line eq $line_number){ push (@line_mates, $this_guys_stats[0]); } } return @line_mates; } ################## G E T L I N E ##################################### # This subroutine takes a player name and its team array, then will # return the players line number.. # # INPUT: string (players name), # array (teams game array) # OUTPUT: integer (line number) # Dependencies: None # EXAMPLE CALL: $line_number = getLine($player, @team); ######################################################################## sub getLine { my($player, @game_array) = @_; my $line = 1; foreach my $team_mate (@game_array){ #read each line (gm array) my @player_line = split(/,/,$team_mate);#split line to line array if ($player eq $player_line[0]){ return $player_line[9]; } } return $line; } ################# R U N G A M E ########################### # This subroutine runs a bhl game. # # INPUT: two strings that represent teams, an integer # that represents the home ice advantage (1 to 10) # 5 is recommended, a power play advantage # integer (3 is reccommended), and a goalie strength! # OUTPUT: An array of integers: # [0] = 1st period home team points # [1] = 2nd period home team points # [2] = 3rd period home team points # [3] = OT periods home team points # [4] = 1st period away team points # [5] = 2nd period away team points # [6] = 3rd period away team points # [7] = OT periods away team points # [8] = 1st period events list(; seperated) # [9] = 2nd period events list(; seperated) # [10] = 3rd period events list(; seperated) # [11] = OT period events list(; seperated) # [12] = 1st period home team shots # [13] = 2nd period home team shots # [14] = 3rd period home team shots # [15] = OT periods home team shots # [16] = 1st period away team shots # [17] = 2nd period away team shots # [18] = 3rd period away team shots # [19] = OT periods away team ahots # [20] = home power play conversions # [21] = away power play conversions # [22] = home goalie # [23] = away goalie # [24] = home pen minutes # [25] = away pen minutes # [26] = periods # [27] = game misconducts list (, seperated) # [28] = home Full Team Name String # [29] = away Full Team Name String # [30] = game winning goal scorer # DEPENDENCIES: A shit load including: # 1) gameClock($period, $min, $sec); # 2) printClock(@seconds); # 3) randEvent(); # 4) decideOn3(per1, per2, per3); # 5) decider($percentage); # 6) specificPen(); # 7) testGameMis($penalty[1]); # 8) gameSetUp($hTeam); # 9) checkTeam(); # 10) teamsArray("___"); # 11) mkGameArray(); # 12) openFile(); # 13) inspectLines(team); # 14) changeLine(team,m or a[1,0]) # 15) saveStats(PLAYERS_DB, @playersStats); # 16) countLines($teamWanted); # 17) whoScored(4, @home); # 18) puckPosition($homePlusMinus, # $awayPlusMinus, # $PP_FLAG, # $HOME_ADVANTAGE, # $P_P_ADVANTAGE); # 19) percentAdjustTo($percentage); # 20) getValues(3, 0, 17, @home); # 21) getGoalie($GOALIE_STRENGTH, @home); # 22) getValue(3, 18, @a); # 23) updateBox(currentSecond(@timeOfEvent), # %penaltyBox); # 24) currentSecond(@timeOfEvent); # 25) checkTheBox($PEN_INDEX, # $hashReference, # @home); # 26) clockToString(@timeOfEvent); # 27) handleEvent($currentPeriod, # $time, # $EVENT, # $player1, # $player2, # $player3, # $team, # $H_OR_A, # $powerPlayFlag, # $penSec, # $penDesc, # $gameMisconductFlag, # @results); # 28) penBoxOfficial($home, $away, %penaltyBox); # 29) makeTeamNameHash(); # 30) gameArrayZeroerOuter(@aTeam); # 31) @aTeam=postStat("p_goal", $player, $thing, # $add_sub_write_flag, @aTeam); # 32) getLine($name, @array) # 33) getLineMates($player, @team); # 34) addStats(@homeResults); # SAMPLE CALL: @results = runGame("nyr", # "nyi", # $hAdvantage, # $powerPlayAdvantage, # $goalieStrength, # $howManyOvertimes); ############################################################# sub runGame { my($hTeam, $aTeam, $hAdvantage, $ppAdvantage, $gStrength, $ot) = @_; my $d = 1; # debugging if($DBUG){debug($d, "\nRUN GAME:\n");} if($DBUG){debug($d, "In ==> $hTeam, $aTeam, $hAdvantage, ". "$ppAdvantage, $gStrength, $ot\n");} #INITIALIZATIONS my @returnArray = (); #results array for (my $j = 0; $j < 30; $j++){ $returnArray[$j] = 0; #initialize } $returnArray[8] = ""; $returnArray[9] = ""; $returnArray[10] = ""; $returnArray[11] = ""; $returnArray[30] = ""; my @timeOfEvent = gameClock(1, 0, 5); #start 5 seconds into it my $powerPlay = 0; #1=home pp, 2=away pp, 0=none my $P_P_ADVANTAGE = 3; #power play advantage my $event = ""; #score op, stoppage, or pen. my @hScorer = (); my @aScorer = (); my @homePenPerson = (); my @awayPenPerson = (); my @penalty = (); my %teamNameHash = makeTeamNameHash(); my %penaltyBox = (); #Pen. Box Hash my $pBoxHshRef = \%penaltyBox; #Ref. to the Pen. Box Hsh my $prefix = ""; #prefix string for output my $time = 0; #container for clockToString my $periods = 3; my $ht = 0; # Home total points my $at = 0; # Away total points my $hts = 0; # Ho total points for flag below my $ats = 0; # Aw total points for flag below my $poss_game_winner = 1; # to record the next goal my $game_win_scorer = ""; my $h_poss_game_tier = 0; # to record the next goal my $a_poss_game_tier = 0; # to record the next goal my @pler; my @pler2; my $game_win_tier; my $NO_GAME_MISCONDUCT = FALSE; # for handle event my $GAME_MISCONDUCT = TRUE; # for handle event my $GAME_MISCONDUCT_TIME = 9999; # for ever #Make the game arrays my @home = gameSetUp($hTeam); my @away = gameSetUp($aTeam); if($DBUG){debug($d, "RUNGAME: Making refs to game arrays\n");} my $homeGARef = \@home; #Ref. to above game arrays my $awayGARef = \@away; if($DBUG){debug($d, "RUNGAME: Getting names of teams\n");} my $homeName = $teamNameHash{$hTeam}; my $awayName = $teamNameHash{$aTeam}; if($DBUG){debug($d, "RUNGAME: Putting names of teams into". " returnarray\n");} $returnArray[28] = $homeName; $returnArray[29] = $awayName; #Zero out the game array into the stats array if($DBUG){debug($d, "RUNGAME: Zero out the game array into the". " stats array\n");} my @homeResults = gameArrayZeroerOuter(0,@home); my @awayResults = gameArrayZeroerOuter(0,@away); #Get the goalie save percentages and names. if($DBUG){debug($d, "RUNGAME: Get the goalie save percentages and". " names\n");} my @homeGoalie=getGoalie($gStrength, @home); my @awayGoalie=getGoalie($gStrength, @away); $returnArray[22] = $homeGoalie[0]; $returnArray[23] = $awayGoalie[0]; #Add up the plus/minuses for puck position if($DBUG){debug($d, "RUNGAME: Add up the plus/minuses for puck". " position\n");} my $homePlusMinus=getValues(3, 0, 17, @home); my $awayPlusMinus=getValues(3, 0, 17, @away); # M A I N L O O P ################################################# for(my $i = 0; $i <= $periods; $i = $timeOfEvent[0]){ if($DBUG){ print"---------- RUN GAME ----------\n"; } $event=randEvent(); if($DBUG){debug($d, "RUNGAME MAIN: Calling clockToString\n");} $time = clockToString(@timeOfEvent); #Set up game winning/tieing goal possibility $hts = $returnArray[0] + $returnArray[1] + $returnArray[2] + $returnArray[3]; $ats = $returnArray[4] + $returnArray[5] + $returnArray[6] + $returnArray[7]; if ($hts == $ats){ $poss_game_winner = 1; # set flag for recording } $a_poss_game_tier = $hts - $ats; # set flag for recording $h_poss_game_tier = $ats - $hts; # set flag for recording #Set up penalty and scorer section @penalty = specificPen(); my $pen_min = $penalty[1]/60; $prefix = testGameMis($penalty[1]); $powerPlay = penBoxOfficial($homeGARef, $awayGARef, %penaltyBox); #Check the penalty box before we decide they are be involved @homePenPerson = checkTheBox(PENALTY_INDEX, $pBoxHshRef, @home); @awayPenPerson = checkTheBox(PENALTY_INDEX, $pBoxHshRef, @away); @hScorer = checkTheBox(SCORER_INDEX, $pBoxHshRef, @home); @aScorer = checkTheBox(SCORER_INDEX, $pBoxHshRef, @away); my @h_line_mates = getLineMates($hScorer[0], @home); my @a_line_mates = getLineMates($aScorer[0], @away); ################################################################## # AWAY ZONE ###################################################### ################################################################## if (puckPosition($homePlusMinus, $awayPlusMinus, $powerPlay, $hAdvantage, $ppAdvantage)){ if($DBUG){debug($d, "RUNGAME MAIN: AWAY ZONE\n");} #SCORING OPPORTUNITY###################################### if ($event eq "Scoring Opportunity"){ # SHOT ON GOAL ######################################## # Put into results @homeResults = postStat("shts", $hScorer[0], 1, "add", @homeResults); # Put into return array @returnArray = handleEvent($timeOfEvent[0], $time, "shot", "null", "null", "null", $hTeam, "home", $powerPlay, 0, "null", 0, @returnArray); # home shots # GOAL ################################################ if($DBUG){debug($d, "RUNGAME MAIN: AWAY ZONE, GOAL test");} if($DBUG){debug($d, "goalie save % = $awayGoalie[1]\n");} if(!decider($awayGoalie[1])){ # not a save. if($DBUG){debug($d, "RUNGAME MAIN: AWAY ZONE, GOAL = ". "true\n");} # Put into return array @returnArray = handleEvent($timeOfEvent[0], $time, "goal", $hScorer[0], $hScorer[1], $hScorer[2], $hTeam, "home", $powerPlay, 0, "null", 0, @returnArray); # home goal # Put into results ## Goalie section @awayResults = postStat("ga", $returnArray[23], 1, "add", @awayResults); ## Points section @homeResults = postStat("pts", $hScorer[0], 1, "add", @homeResults); @homeResults = postStat("gls", $hScorer[0], 1, "add", @homeResults); if ($hScorer[1] ne "null" && $hScorer[1] ne "unassisted" && $hScorer[1] ne " "){ @homeResults = postStat("pts", $hScorer[1], 1, "add", @homeResults); @homeResults = postStat("asts", $hScorer[1], 1, "add", @homeResults); if ($hScorer[2] ne "null" && $hScorer[2] ne "unassisted" && $hScorer[2] ne " "){ @homeResults = postStat("pts", $hScorer[2], 1, "add", @homeResults); @homeResults = postStat("asts", $hScorer[2], 1, "add", @homeResults); } } ## Plus/Minus section foreach my $linemate (@h_line_mates){ @homeResults = postStat("p_m", $linemate, 1, "add", @homeResults); } foreach my $linemate (@a_line_mates){ @awayResults = postStat("p_m", $linemate, 1, "sub", @awayResults); } ## power play / short handed goal section if ($powerPlay == 1){ @homeResults = postStat("ppg", $hScorer[0], 1, "add", @homeResults); }elsif ($powerPlay == 2){ @homeResults = postStat("shg", $hScorer[0], 1, "add", @homeResults); } ## game winning goal section if ($poss_game_winner){ $game_win_scorer = $hScorer[0]; $poss_game_winner = 0; # reset the flag } ## game tieing goal section if (($h_poss_game_tier == 1) && ($hts < $ats)){ $game_win_tier = $hScorer[0]; @homeResults = postStat("gtg", $hScorer[0], 1, "add", @homeResults); } } # SAVE ################################################ else { @awayResults = postStat("sav", $returnArray[23], 1, "add", @awayResults); } #PLAY WHISTLED DOWN####################################### }elsif($event eq "Stoppage in play"){ #PENALTY################################################## }else{ if ($penalty[2] == 1){ # SINGLE_PEN @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $awayPenPerson[0], "null", "null", $aTeam, "away", $powerPlay, $penalty[1], $penalty[0], $NO_GAME_MISCONDUCT, @returnArray); $penaltyBox{$awayPenPerson[0]} = currentSecond(@timeOfEvent) + $penalty[1];# throw in box @awayResults = postStat("pen", $awayPenPerson[0], $pen_min, "add", @awayResults); # away pen. } elsif ($penalty[2] == 2){ # MATCHING_PEN @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $awayPenPerson[0], "null", "null", $aTeam, "away", $powerPlay, $penalty[1], $penalty[0], $NO_GAME_MISCONDUCT, @returnArray); $penaltyBox{$awayPenPerson[0]} = currentSecond(@timeOfEvent) + $penalty[1];# throw in box @awayResults = postStat("pen", $awayPenPerson[0], $pen_min, "add", @awayResults); # away pen. @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $homePenPerson[0], "null", "null", $hTeam, "home", $powerPlay, $penalty[1], $penalty[0], $NO_GAME_MISCONDUCT, @returnArray); $penaltyBox{$homePenPerson[0]} = currentSecond(@timeOfEvent) + $penalty[1];# throw in box @homeResults = postStat("pen", $homePenPerson[0], $pen_min, "add", @homeResults); # home pen. } elsif ($penalty[2] == 3){ # INSTIGATOR_OTHER_PEN @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $awayPenPerson[0], "null", "null", $aTeam, "away", $powerPlay, $penalty[1], $penalty[0], $NO_GAME_MISCONDUCT, @returnArray); $penaltyBox{$awayPenPerson[0]} = currentSecond(@timeOfEvent) + $penalty[1];# throw in box @awayResults = postStat("pen", $awayPenPerson[0], $pen_min, "add", @awayResults); # away pen. @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $homePenPerson[0], "null", "null", $hTeam, "home", $powerPlay, $GAME_MISCONDUCT_TIME, $penalty[0], $GAME_MISCONDUCT, @returnArray); $penaltyBox{$homePenPerson[0]} = currentSecond(@timeOfEvent) + $GAME_MISCONDUCT_TIME; # throw in box @homeResults = postStat("pen", $homePenPerson[0], $pen_min, "add", @homeResults); # home pen. } elsif ($penalty[2] == 4){ # INSTIGATOR_THIS_PEN @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $awayPenPerson[0], "null", "null", $aTeam, "away", $powerPlay, $GAME_MISCONDUCT_TIME, $penalty[0], $GAME_MISCONDUCT, @returnArray); $penaltyBox{$awayPenPerson[0]} = currentSecond(@timeOfEvent) + $GAME_MISCONDUCT_TIME; # throw in box @awayResults = postStat("pen", $awayPenPerson[0], $pen_min, "add", @awayResults); # away pen. @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $homePenPerson[0], "null", "null", $hTeam, "home", $powerPlay, $penalty[1], $penalty[0], $NO_GAME_MISCONDUCT, @returnArray); $penaltyBox{$homePenPerson[0]} = currentSecond(@timeOfEvent) + $penalty[1];# throw in box @homeResults = postStat("pen", $homePenPerson[0], $pen_min, "add", @homeResults); # home pen. } elsif ($penalty[2] == 5){ # MATCH_MISCONDUCT @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $awayPenPerson[0], "null", "null", $aTeam, "away", $powerPlay, $GAME_MISCONDUCT_TIME, $penalty[0], $GAME_MISCONDUCT, @returnArray); $penaltyBox{$awayPenPerson[0]} = currentSecond(@timeOfEvent) + $GAME_MISCONDUCT_TIME; # throw in box @awayResults = postStat("pen", $awayPenPerson[0], $pen_min, "add", @awayResults); # away pen. @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $homePenPerson[0], "null", "null", $hTeam, "home", $powerPlay, $GAME_MISCONDUCT_TIME, $penalty[0], $GAME_MISCONDUCT, @returnArray); $penaltyBox{$homePenPerson[0]} = currentSecond(@timeOfEvent) + $GAME_MISCONDUCT_TIME; # throw in box @homeResults = postStat("pen", $homePenPerson[0], $pen_min, "add", @homeResults); # home pen. } else { # GAME_MISCONDUCT @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $awayPenPerson[0], "null", "null", $aTeam, "away", $powerPlay, $GAME_MISCONDUCT_TIME, $penalty[0], $GAME_MISCONDUCT, @returnArray); $penaltyBox{$awayPenPerson[0]} = currentSecond(@timeOfEvent) + $GAME_MISCONDUCT_TIME; # throw in box @awayResults = postStat("pen", $awayPenPerson[0], $pen_min, "add", @awayResults); # away pen. } if($DBUG){ print"penalty: $penalty[0]\n"; print"seconds: $penalty[1]\n"; print"code: $penalty[2]\n"; print"timeOfEvent:@timeOfEvent\n"; print"penalty box:\n"; printHash(%penaltyBox); } } ################################################################## # HOME ZONE ###################################################### ################################################################## }else{ if($DBUG){debug($d, "RUNGAME MAIN: HOME ZONE\n");} #SCORING OPPORTUNITY###################################### if ($event eq "Scoring Opportunity"){ # SHOT ON GOAL ######################################## # Put into results @awayResults = postStat("shts", $aScorer[0], 1, "add", @awayResults); # Put into return array @returnArray = handleEvent($timeOfEvent[0], $time, "shot", "null", "null", "null", $aTeam, "away", $powerPlay, 0, "null", 0, @returnArray); # away shots # GOAL ################################################ if($DBUG){debug($d, "RUNGAME MAIN: HOME ZONE, GOAL test\n");} if($DBUG){debug($d, "goalie save % = $homeGoalie[1]\n");} if(!decider($homeGoalie[1])){#not a save if($DBUG){debug($d, "RUNGAME MAIN: HOME ZONE, GOAL = ". "true\n");} # Put into return array @returnArray = handleEvent($timeOfEvent[0], $time, "goal", $aScorer[0], $aScorer[1], $aScorer[2], $aTeam, "away", $powerPlay, 0, "null", 0, @returnArray); # away goal # Put into results ## Goalie section @homeResults = postStat("ga", $returnArray[22], 1, "add", @homeResults); ## Points section @awayResults = postStat("pts", $aScorer[0], 1, "add", @awayResults); @awayResults = postStat("gls", $aScorer[0], 1, "add", @awayResults); if ($aScorer[1] ne "null" && $aScorer[1] ne "unassisted" && $aScorer[1] ne " "){ @awayResults = postStat("pts", $aScorer[1], 1, "add", @awayResults); @awayResults = postStat("asts", $aScorer[1], 1, "add", @awayResults); if ($aScorer[2] ne "null" && $aScorer[2] ne "unassisted" && $aScorer[2] ne " "){ @awayResults = postStat("pts", $aScorer[2], 1, "add", @awayResults); @awayResults = postStat("asts", $aScorer[2], 1, "add", @awayResults); } } ## Plus/Minus section foreach my $linemate (@a_line_mates){ @awayResults = postStat("p_m", $linemate, 1, "add", @awayResults); } foreach my $linemate (@h_line_mates){ @homeResults = postStat("p_m", $linemate, 1, "sub", @homeResults); } ## power play / short handed goal section if ($powerPlay == 1){ @awayResults = postStat("ppg", $aScorer[0], 1, "add", @awayResults); }elsif ($powerPlay == 2){ @awayResults = postStat("shg", $aScorer[0], 1, "add", @awayResults); } ## game winning goal section if ($poss_game_winner){ $game_win_scorer = $aScorer[0]; $poss_game_winner = 0; } ## game tieing goal section if (($a_poss_game_tier == 1) && ($hts > $ats)){ $game_win_tier = $aScorer[0]; @awayResults = postStat("gtg", $aScorer[0], 1, "add", @awayResults); } } # SAVE ################################################ else {@homeResults = postStat("sav", $returnArray[22], 1, "add", @homeResults); } #PLAY WHISTLED DOWN####################################### }elsif($event eq "Stoppage in play"){ #PENALTY################################################## }else{ if($penalty[2] == 1){ # SINGLE_PEN @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $homePenPerson[0], "null", "null", $hTeam, "home", $powerPlay, $penalty[1], $penalty[0], $NO_GAME_MISCONDUCT, @returnArray); $penaltyBox{$homePenPerson[0]} = currentSecond(@timeOfEvent) + $penalty[1];# throw in box @homeResults = postStat("pen", $homePenPerson[0], $pen_min, "add", @homeResults); # home pen. } elsif ($penalty[2] == 2){ # MATCHING_PEN @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $homePenPerson[0], "null", "null", $hTeam, "home", $powerPlay, $penalty[1], $penalty[0], $NO_GAME_MISCONDUCT, @returnArray); $penaltyBox{$homePenPerson[0]} = currentSecond(@timeOfEvent) + $penalty[1];# throw in box @homeResults = postStat("pen", $homePenPerson[0], $pen_min, "add", @homeResults); # home pen. @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $awayPenPerson[0], "null", "null", $aTeam, "away", $powerPlay, $penalty[1], $penalty[0], $NO_GAME_MISCONDUCT, @returnArray); $penaltyBox{$awayPenPerson[0]} = currentSecond(@timeOfEvent) + $penalty[1];# throw in box @awayResults = postStat("pen", $awayPenPerson[0], $pen_min, "add", @awayResults); # away pen. } elsif ($penalty[2] == 3){ # INSTIGATOR_OTHER_PEN @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $homePenPerson[0], "null", "null", $hTeam, "home", $powerPlay, $penalty[1], $penalty[0], $NO_GAME_MISCONDUCT, @returnArray); $penaltyBox{$homePenPerson[0]} = currentSecond(@timeOfEvent) + $penalty[1];# throw in box @homeResults = postStat("pen", $homePenPerson[0], $pen_min, "add", @homeResults); # home pen. @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $awayPenPerson[0], "null", "null", $aTeam, "away", $powerPlay, $GAME_MISCONDUCT_TIME, $penalty[0], $GAME_MISCONDUCT, @returnArray); $penaltyBox{$awayPenPerson[0]} = currentSecond(@timeOfEvent) + $GAME_MISCONDUCT_TIME; # throw in box @awayResults = postStat("pen", $awayPenPerson[0], $pen_min, "add", @awayResults); # away pen. } elsif ($penalty[2] == 4){ # INSTIGATOR_THIS_PEN @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $homePenPerson[0], "null", "null", $hTeam, "home", $powerPlay, $GAME_MISCONDUCT_TIME, $penalty[0], $GAME_MISCONDUCT, @returnArray); $penaltyBox{$homePenPerson[0]} = currentSecond(@timeOfEvent) + $GAME_MISCONDUCT_TIME; # throw in box @homeResults = postStat("pen", $homePenPerson[0], $pen_min, "add", @homeResults); # home pen. @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $awayPenPerson[0], "null", "null", $aTeam, "away", $powerPlay, $penalty[1], $penalty[0], $NO_GAME_MISCONDUCT, @returnArray); $penaltyBox{$awayPenPerson[0]} = currentSecond(@timeOfEvent) + $penalty[1];# throw in box @awayResults = postStat("pen", $awayPenPerson[0], $pen_min, "add", @awayResults); # away pen. } elsif ($penalty[2] == 5){ # MATCH_MISCONDUCT @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $homePenPerson[0], "null", "null", $hTeam, "home", $powerPlay, $GAME_MISCONDUCT_TIME, $penalty[0], $GAME_MISCONDUCT, @returnArray); $penaltyBox{$homePenPerson[0]} = currentSecond(@timeOfEvent) + $GAME_MISCONDUCT_TIME; # throw in box @homeResults = postStat("pen", $homePenPerson[0], $pen_min, "add", @homeResults); # home pen. @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $awayPenPerson[0], "null", "null", $aTeam, "away", $powerPlay, $GAME_MISCONDUCT_TIME, $penalty[0], $GAME_MISCONDUCT, @returnArray); $penaltyBox{$awayPenPerson[0]} = currentSecond(@timeOfEvent) + $GAME_MISCONDUCT_TIME; # throw in box @awayResults = postStat("pen", $awayPenPerson[0], $pen_min, "add", @awayResults); # away pen. } else { # GAME_MISCONDUCT @returnArray = handleEvent($timeOfEvent[0], $time, "pen", $homePenPerson[0], "null", "null", $hTeam, "home", $powerPlay, $GAME_MISCONDUCT_TIME, $penalty[0], $GAME_MISCONDUCT, @returnArray); $penaltyBox{$homePenPerson[0]} = currentSecond(@timeOfEvent) + $GAME_MISCONDUCT_TIME; # throw in box @homeResults = postStat("pen", $homePenPerson[0], $pen_min, "add", @homeResults); # home pen. } if($DBUG){ print"penalty: $penalty[0]\n"; print"seconds: $penalty[1]\n"; print"code: $penalty[2]\n"; print"timeOfEvent:@timeOfEvent\n"; print"penalty box:\n"; printHash(%penaltyBox); } } } #UPDATE PENALTY BOX INHABITANTs & TIME############################ %penaltyBox=updateBox(currentSecond(@timeOfEvent), %penaltyBox); @timeOfEvent=gameClock(@timeOfEvent); # HANDLE OVERTIME OR END OF GAME $ht = $returnArray[0] + $returnArray[1] + $returnArray[2] + $returnArray[3]; $at = $returnArray[4] + $returnArray[5] + $returnArray[6] + $returnArray[7]; if($DBUG){ print"-------------------\n"; print"penalty box:\n"; printHash(%penaltyBox); print"-------------------\n"; } if ($timeOfEvent[0] >= 4){ if($DBUG){ print"--------OT-----------\n"; print"Period: $timeOfEvent[0]\n"; print"Away score: $at\n"; print"Home score: $ht\n"; print"Overtime flag: $ot\n"; print"Allowed periods: $periods\n"; } if ($at != $ht || $ot == 0){ last; } if ($ot == 1){ $periods = 4; } elsif ($periods > 50){ last; } else { $periods++; } } $returnArray[26] = $timeOfEvent[0]; } # HANDLE THE GAME WINNING GOAL and GOALIES if ($ht > $at){ @homeResults = postStat("gwg", $game_win_scorer, 1, "add", @homeResults); @homeResults = postStat("w", $returnArray[22], 1, "add", @homeResults); @awayResults = postStat("l", $returnArray[23], 1, "add", @awayResults); } elsif ($ht < $at){ @awayResults = postStat("w", $returnArray[23], 1, "add", @awayResults); @homeResults = postStat("l", $returnArray[22], 1, "add", @homeResults); @awayResults = postStat("gwg", $game_win_scorer, 1, "add", @awayResults); } elsif ($ht == $at){ @awayResults = postStat("t", $returnArray[23], 1, "add", @awayResults); @homeResults = postStat("t", $returnArray[22], 1, "add", @homeResults); } # GOALIE STATS my $hs = $returnArray[12] + $returnArray[13] + $returnArray[14] + $returnArray[15]; my $as = $returnArray[16] + $returnArray[17] + $returnArray[18] + $returnArray[19]; my $hgsp = getStat("sav",$returnArray[22], @homeResults); $hgsp = rounder(($hgsp / $as), 3); my $agsp = getStat("sav",$returnArray[23], @awayResults); $agsp = rounder(($agsp / $hs), 3); @awayResults = postStat("s_p", $returnArray[23], $agsp, "write", @awayResults); @homeResults = postStat("s_p", $returnArray[22], $hgsp, "write", @homeResults); @awayResults = postStat("gaa", $returnArray[23], $ht, "write", @awayResults); @homeResults = postStat("gaa", $returnArray[22], $at, "write", @homeResults); $returnArray[30] = $game_win_scorer; # Process count everyone that played - for the 'games' stat! for (my $i = 0; $i < (@homeResults - 2); $i++){ my @pler = split (/,/, $homeResults[$i]); @homeResults = postStat("gms", $pler[0], 1, "add", @homeResults); my @pler2 = split (/,/, $awayResults[$i]); @awayResults = postStat("gms", $pler2[0], 1, "add", @awayResults); } for (my $i = (@homeResults - 2); $i < @homeResults; $i++){ @pler = split (/,/, $homeResults[$i]); if ($pler[0] eq $homeGoalie[0]){ @homeResults = postStat("g_gms", $pler[0], 1, "add", @homeResults); } @pler2 = split (/,/, $awayResults[$i]); if ($pler2[0] eq $awayGoalie[0]){ @awayResults = postStat("g_gms", $pler2[0], 1, "add", @awayResults); } } saveStats("homeResults.dat", @homeResults); saveStats("awayResults.dat", @awayResults); addStats(@homeResults); addStats(@awayResults); return @returnArray; # return the results } ###### A D D S T A T S################################################ # This subroutine adds this game stats to the leagues season stats # and to the running total of the base stats. # INPUT: array (results array) # OUTPUT: none - file updates # DEPENDENCIES: # EXAMPLE CALL: addStats(@homeResults); ######################################################################## sub addStats { my (@results) = @_; # results. my @players_db_a = openFile(PLAYERS_DB); # playersdb.csv my @goalies_db_a = openFile(GOALIES_DB); # goaliesdb.csv my @season_p_db_a = openFile(SEASON_P_DB); # season_p_db.csv my @season_g_db_a = openFile(SEASON_G_DB); # season_g_db.csv my @line_array = (); # each line game array my @player_stats = (); # each line stats ## Do the season stats file for (my $i = 0; $i < (@results - 2); $i++){ # foreach results @line_array = split (/,/, $results[$i]); # split into arry foreach my $player (@season_p_db_a){ # foreach db line chomp $player; @player_stats = split (/,/, $player); # split into arry if ($player_stats[0] eq $line_array[0]){ # is it same name for (my $j = 2; $j < @player_stats; $j++){# loop player_stats $player_stats[$j]= $player_stats[$j] # add values + $line_array[$j]; } $player = join (',', @player_stats); # join back up } $player = $player . "\n"; } } saveStats(SEASON_P_DB, @season_p_db_a); ## Do the season db file for (my $i = 0; $i < (@results - 2); $i++){ # foreach results @line_array = split (/,/, $results[$i]); # split into arry foreach my $player (@players_db_a){ # foreach db line chomp $player; @player_stats = split (/,/, $player); # split into arry if ($player_stats[0] eq $line_array[0]){ # is it same name for (my $j = 2; $j < @player_stats; $j++){# loop player_stats $player_stats[$j] = $player_stats[$j] # add values + $line_array[$j]; } $player = join (',', @player_stats); # join back up } $player = $player . "\n"; } } saveStats(PLAYERS_DB, @players_db_a); ## Do the goalie stats file my $save_per = 0; my $goals_ag_av = 0; my $n = @results; for (my $k = ($n-2); $k < $n; $k++){ # foreach results @line_array = split (/,/, $results[$k]); # split into arry foreach my $player (@season_g_db_a){ # foreach db line chomp $player; @player_stats = split (/,/, $player); # split into arry if ($player_stats[0] eq $line_array[0]){ # is it same name for (my $j = 3; $j < (@player_stats - 2); $j++){ # loop p_sts $player_stats[$j] = $player_stats[$j] # add values + $line_array[$j]; } if ($player_stats[10] > 0){ $goals_ag_av = (rounder(($player_stats[8] / ($player_stats[10] + 1)), 3) * 10); # gaa $player_stats[9] = $goals_ag_av; } else { $player_stats[9] = $player_stats[8]; } if (($player_stats[7] + $player_stats[8]) > 0){ $save_per = rounder(($player_stats[7] # save % / ($player_stats[7] # save % + $player_stats[8])), 2); # save % $player_stats[2] = $save_per; # save % } $player_stats[10] = $player_stats[10] + $line_array[10];#$gms $player = join (',', @player_stats); # join back up } chomp $player; $player = "$player\n"; } } saveStats(SEASON_G_DB, @season_g_db_a); ## Do the goalie db file $save_per = 0; $goals_ag_av = 0; $n = @results; for (my $i = ($n-2); $i < $n; $i++){ # foreach results chomp $results[$i]; @line_array = split (/,/, $results[$i]); # split into arry foreach my $player (@goalies_db_a){ # foreach db line chomp $player; @player_stats = split (/,/, $player); # split into arry if ($player_stats[0] eq $line_array[0]){ # is it same name for (my $j = 3; $j < (@player_stats - 2); $j++){ # loop p_sts $player_stats[$j] = $player_stats[$j] # add values + $line_array[$j]; } if ($player_stats[10] > 0){ $goals_ag_av = (rounder(($player_stats[8] / ($player_stats[10] + 1)), 3) * 10); # gaa $player_stats[9] = $goals_ag_av; } else { $player_stats[9] = $player_stats[8]; } if (($player_stats[7] + $player_stats[8]) > 0){ if($line_array[4]){ $save_per = $player_stats[2] - .01; } elsif ($line_array[6]){ $save_per = $player_stats[2]; } else { $save_per = $player_stats[2] + .01; } $player_stats[2] = $save_per; # save % } $player_stats[10] = $player_stats[10] + $line_array[10];#$gms $player = join (',', @player_stats); # join back up $player = "$player\n"; } chomp $player; $player = "$player\n"; } } saveStats(GOALIES_DB, @goalies_db_a); } ###### G E T D A T E ################################################# # This subroutine returns the current date array. # INPUT: none # OUTPUT: array[month,day,year] # DEPENDENCIES: none # EXAMPLE CALL: @today = getDate(); ######################################################################## sub getDate { my @day = (0, 0, 0); my @date = localtime(time); $day[0] = $date[4]+1; $day[1] = $date[3]; $day[2] = $date[5]+1900; return @day; } ###### M A K E H T M L R E S U L T S ############################### # This subroutine makes a html formatted results page from a game # array and a couple of game results file. # INPUT: array (game array) # OUTPUT: file (home_name_waya_name_date.html) # DEPENDENCIES: 2 files (awayResults.dat, homeResults.dat) # getDate() # saveStats($file_name, @page_array) # EXAMPLE CALL: makeHtmlResults(@game); ######################################################################## sub makeHtmlResults { my @game = @_; my $d = 2; my @out = (); my $event; my $hs = $game[0] + $game[1] + $game[2] + $game[3]; my $as = $game[4] + $game[5] + $game[6] + $game[7]; my $hsog = $game[12] + $game[13] + $game[14] + $game[15]; my $asog = $game[16] + $game[17] + $game[18] + $game[19]; my $hgs = $asog - $as; #home goalie saves my $ags = $hsog - $hs; #away goalie saves my $otf = 0; #overtime flag if ($game[26] >= 4){$otf = 1;} #overtime=true # get the teams involved to make the file name my @home_game_results = openFile("homeResults.dat"); my @away_game_results = openFile("awayResults.dat"); my @line = (); @line = split(/,/, $home_game_results[0]); my $home = $line[1]; @line = split(/,/, $away_game_results[0]); my $away = $line[1]; my $head_mess = "FINAL"; if ($game[26] > 3){ $head_mess = "$head_mess IN OVERTIME"; } $out[0]= ' '."\n". 'G A M E R E S U L T S '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". '
'."\n". ' '."\n". '

'."$head_mess".'
'."\n". ' '; $out[1]= "$game[28] $hs, $game[29] $as"; #FINAL SCORE HEADER $out[2]= '
'."\n". '