#!/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". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\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". '

'. '1st

'. '2nd

'. '3rd

'. 'OT

'. 'TOTAL

'; $out[3]= $game[29]; #AWAY TEAM $out[4]= '

'. '

'; $out[5]= $game[4]; # 1ST PERIOD PTS $out[6]= '

'. '

'; $out[7]= $game[5]; # 2ND PERIOD PTS $out[8]= '

'. '

'; $out[9]= $game[6]; # 3RD PERIOD PTS $out[10]='

'. '

'; if ($otf){ $out[11]= $game[7]; # OT PERIOD PTS } else { $out[11]= "-"; } $out[12]='

'. '

'; $out[13]= $as; # AWAY SCORE $out[14]='

'; $out[15]= $game[28]; #HOME TEAM $out[16]= '

'. '

'; $out[17]= $game[0]; # 1ST PERIOD PTS $out[18]= '

'. '

'; $out[19]= $game[1]; # 2ND PERIOD PTS $out[20]= '

'. '

'; $out[21]= $game[2]; # 3RD PERIOD PTS $out[22]='

'. '

'; if ($otf){ $out[23]= $game[3]; # OT PERIOD PTS } else { $out[23]= "-"; } $out[24]='

'. '

'; $out[25]= $hs; # HOME SCORE $out[26]='

'."\n". '

 First Period: '."\n". '

    '."\n"; $game[8] =~ s/;//o; my @events = split(/;/, $game[8]); $out[27] = ""; foreach my $event (@events){ $out[27] = $out[27] . "
  • $event";# EVENTS PER 1 } $out[28]='
'."\n". '

Second Period: '."\n". '

    '."\n"; $game[9] =~ s/;//o; @events = split(/;/, $game[9]); $out[29] = ""; foreach my $event (@events){ $out[29] = $out[29] . "
  • $event";# EVENTS PER 2 } $out[30]='
'."\n". '

Third Period: '."\n". '

    '."\n"; $game[10] =~ s/;//o; @events = split(/;/, $game[10]); $out[31] = ""; foreach my $event (@events){ $out[31] = $out[31] . "
  • $event";# EVENTS PER 3 } $out[32]='
'."\n"; if ($otf){ $out[33]= '

OT Periods: '."\n". '

    '."\n"; @events = ();$game[11] =~ s/;//o; @events = split(/;/, $game[11]); $out[34] = ""; foreach $event (@events){ $out[34] = $out[34] . "
  • $event"; # OT EVENT } $out[35]='
'."\n"; } else {$out[33] = "";$out[34] = "";$out[35] = "";} $out[36]='
'. '

SHOTS ON GOAL '."\n". '

'; $out[37]= $game[29]; #AWAY TEAM $out[38]=' '; $out[39]= $game[16]; ## 1ST PER AWAY TEAM SHOTS $out[40]= ''; $out[41]= $game[17]; ## 2ND PER AWAY TEAM SHOTS $out[42]= ''; $out[43]= $game[18]; ## 3RD PER AWAY TEAM SHOTS $out[44]= ''; if ($otf){ $out[45]= "$game[19]\n"; ## OT PERIOD POINTS FOR AWAY } else { $out[45]= "-\n"; } $out[46]= ''; $out[47]= $asog; ## TOTAL AWAY TEAM SHOTS $out[48]= '
'; $out[49]= $game[28]; #HOME TEAM $out[50]=' '; $out[51]= $game[12]; ## 1ST PER HOME TEAM SHOTS $out[52]= ''; $out[53]= $game[13]; ## 2ND PER HOME TEAM SHOTS $out[54]= ''; $out[55]= $game[14]; ## 3RD PER HOME TEAM SHOTS $out[56]= ''; if ($otf){ $out[57]= "$game[15]\n"; ## OT PERIOD POINTS FOR HOME } else { $out[57]= "-\n"; } $out[58]= ''; $out[59]= $hsog; ## TOTAL HOME TEAM SHOTS $out[60]= '
'."\n". '
Game winner scored by:'."$game[30]". '
Power-play Conversions:'; $out[61]= "$away - $game[21], $home - $game[20]. \n"; $out[62]='
Goalies: '; $out[63]= "$game[29], $game[23] ($hsog shots, $ags saves). ". "$game[28], $game[22] ($asog shots, $hgs saves). \n"; $out[64]='
'."\n". '

INDIVIDUAL PLAYER STATISTICS

'. ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". '
'; $out[65]= $game[29] ; $out[66]='      '; $out[67]= $game[28] ; $out[68]='     
 GA+/-'. 'SHOTS'. ' GA+/-'. 'SHOTS'. '
'; $out[69]=""; for (my $i = 0; $i <(@away_game_results -2); $i++){ my $this_guy = $away_game_results[$i]; my @line = split (/,/, $this_guy); $out[69]=$out[69] . ''. $line[0] . '
' . "\n"; } $out[70]='
'; $out[71]=""; for (my $i = 0; $i <(@away_game_results -2); $i++){ my $this_guy = $away_game_results[$i]; my @line = split (/,/, $this_guy); $out[71]=$out[71] . ''. $line[11] . '
' . "\n"; } $out[72]='
'; $out[73]=""; for (my $i = 0; $i <(@away_game_results -2); $i++){ my $this_guy = $away_game_results[$i]; my @line = split (/,/, $this_guy); $out[73]=$out[73] . ''. $line[12] . '
' . "\n"; } $out[74]='
'; $out[75]=""; for (my $i = 0; $i <(@away_game_results -2); $i++){ my $this_guy = $away_game_results[$i]; my @line = split (/,/, $this_guy); $out[75]=$out[75] . ''. $line[3] . '
' . "\n"; } $out[76]='
'; $out[77]=""; for (my $i = 0; $i <(@away_game_results -2); $i++){ my $this_guy = $away_game_results[$i]; my @line = split (/,/, $this_guy); $out[77]=$out[77] . ''. $line[10] . '
' . "\n"; } $out[78]='
'; $out[79]=""; for (my $i = 0; $i <(@home_game_results -2); $i++){ my $this_guy = $home_game_results[$i]; my @line = split (/,/, $this_guy); $out[79]=$out[79] . ''. $line[0] . '
' . "\n"; } $out[80]='
'; $out[81]=""; for (my $i = 0; $i <(@home_game_results -2); $i++){ my $this_guy = $home_game_results[$i]; my @line = split (/,/, $this_guy); $out[81]=$out[81] . ''. $line[11] . '
' . "\n"; } $out[82]='
'; $out[83]=""; for (my $i = 0; $i <(@home_game_results -2); $i++){ my $this_guy = $home_game_results[$i]; my @line = split (/,/, $this_guy); $out[83]=$out[83] . ''. $line[12] . '
' . "\n"; } $out[84]='
'; $out[85]=""; for (my $i = 0; $i <(@home_game_results -2); $i++){ my $this_guy = $home_game_results[$i]; my @line = split (/,/, $this_guy); $out[85]=$out[85] . ''. $line[3] . '
' . "\n"; } $out[86]='
'; $out[87]=""; for (my $i = 0; $i <(@home_game_results -2); $i++){ my $this_guy = $home_game_results[$i]; my @line = split (/,/, $this_guy); $out[87]=$out[87] . ''. $line[10] . '
' . "\n"; } $out[88]='
'."\n". '
'."\n". ' '; # make the file my @today = getDate(); my $date = "$today[0]/$today[1]/$today[2]"; my $file_name = "$away\_$home\_$today[0]_$today[1]_$today[2].html"; saveGameResults($file_name, $date, $game[28], $game[29], @out); if($DBUG){debug($d, "END OF MAKE HTML RESULTS \n");} } ###### P R I N T S C R E E N R E S U L T S ######################### # This subroutine prints results to the screen. # INPUT: string (home team) # string (away team) # array (game array) # OUTPUT: screen output (results) # DEPENDENCIES: none # EXAMPLE CALL: printScreenResults(@game); # RESULTS ARRAY INDEX: # [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 ######################################################################## sub printScreenResults { my($h, $a, @results) = @_; my $hfs = $results[0] + $results[1] + $results[2] + $results[3]; my $afs = $results[4] + $results[5] + $results[6] + $results[7]; my $hs = $results[12] + $results[13] + $results[14] + $results[15]; my $as = $results[16] + $results[17] + $results[18] + $results[19]; my @events1 = split(/;/,$results[8]); my @events2 = split(/;/,$results[9]); my @events3 = split(/;/,$results[10]); my @events4 = split(/;/,$results[11]); my $hSaves = $as - $afs; my $aSaves = $hs - $hfs; for (my $j = 0; $j < 50; $j++){print"=";} print "\n$a V.S. $h\n"; print "Points\t1st\t2nd\t3rd\tot\ttotal\n"; print "$a\t$results[4]\t$results[5]\t$results[6]\t$results[7]". "\t$afs\n"; print "$h\t$results[0]\t$results[1]\t$results[2]\t$results[3]". "\t$hfs\n"; print "Shots\t1st\t2nd\t3rd\tot\ttotal\n"; print "$a\t$results[16]\t$results[17]\t$results[18]\t$results[19]". "\t$as\n"; print "$h\t$results[12]\t$results[13]\t$results[14]\t$results[15]". "\t$hs\n"; # print "1st Period Events\n"; TO MUCH FOR THE SCREEN! # foreach my $event(@events1){ # print "$event\n"; # } # print "\n2nd Period Events\n"; # foreach my $event(@events2){ # print "$event\n"; # } # print "\n3rd Period Events\n"; # foreach my $event(@events3){ # print "$event\n"; # } # print "\nOT Events\n"; # foreach my $event(@events4){ # print "$event\n"; # } print "\nHome Power Play Conversions = $results[20]\n"; print "Away Power Play Conversions = $results[21]\n\n"; print "Goalies\n$results[22] Shots $as Saves $hSaves\n"; print "$results[23] Shots $hs Saves $aSaves\n\n"; print "Home Pen Minutes = $results[24]\n"; print "Away Pen Minutes = $results[25]\n"; print "Periods = $results[26]\n"; print "Game Misconducts = ($results[27])\n"; print "Game Winning Goal Scored by $results[30]\n"; for (my $j = 0; $j < 50; $j++){print"=";}print "\n"; } #CHECK TEAM SUBROUTINE####################################### # This subroutine checks for a team abr and if it is availabe # in the array supplied. # # IN: (an array of team initials, a team initial) # OUT: Boolean 1=true it exists, 0=false does not exists # DEPENDENCIES: none ############################################################# sub checkTeam{ my($tm, @t) = @_; my %tms=(); foreach(@t){ $tms{$_}=1;#1 is dummy value. } if(exists $tms{$tm}){ return 1; }else{ return 0; } } ######GET TEAM############################################### # This subroutine prompts the user for a team abriviation. # INPUT: a name to be printed as the team identifier # (example "AWAY") # OUTPUT: Team id (abvr) # DEPENDENCIES: teamsArray("___") # EXAMPLE CALL: $homeTeam = getTeam("Home"); ############################################################# sub getTeam { my($t) = @_; my @teams = teamsArray("___"); my $team = ""; print"\n$t team (in abr lowercase)('q' to quit) ==> "; while (1){ $team=; chomp $team; if ($team eq 'q'){ return 1;} if (checkTeam($team, @teams)){ last; } print"\nERROR: team (in abr lowercase)('q' to quit) ==> "; } return $team; } ##################OPENER##################################### # This subroutine opens a specified file and reads it into an # array of lines. You must have global variables ############################################################# sub openFile { my($file) = @_; my $badflag = FALSE; my @fileStuff = (); if ($DBUG){ print "---------- OPEN FILE ENTER----------\n"; print "file = $file\n"; print "badflag = $badflag\n"; print "fileStuff(#) = $#fileStuff\n"; } open(FILE, $file) || ($badflag = 1); if ($badflag){ print"\n$file does not exists....creating...\npush ". "xc to cancel this operation\n"; prompt_clear(1); saveStats($file, @fileStuff); if ($DBUG){ print "---------- OPEN FILE EXIT----------\n"; print "file = $file\n"; print "badflag = $badflag\n"; print "fileStuff(#) = $#fileStuff\n"; } return @fileStuff; } @fileStuff=; close(FILE); if ($DBUG){ print "---------- OPEN FILE EXIT----------\n"; print "file = $file\n"; print "badflag = $badflag\n"; print "fileStuff(#) = $#fileStuff\n"; } return @fileStuff; } ##################OPENER WITH IGNORE######################### # This subroutine opens a specified file and reads it into an # array of lines ignoring a certain line. You must have # global variables ############################################################# sub openFileWIgnore { my($file, $ignore, $i) = @_; my $tabs = 0; if ($DBUG){debug($tabs, "OPEN FILE WITH IGNORE:\n");} if ($DBUG){debug($tabs, "file => $file\n");} if ($DBUG){debug($tabs, "ignore => $ignore\n");} if ($DBUG){debug($tabs, "i => $i\n");} my $badflag = 0 ; my @LineContents = (); my @fileStuff = (); my @returnArray = (); my $index = 0 ; open(FILE, $file) || ($badflag = 1); if ($DBUG){debug($tabs, "bad flag => $badflag\n");} if ($badflag){ print"\n$file does not exists....creating...\npush ". "xc to cancel this operation\n"; prompt_clear(1); if ($DBUG){debug($tabs, "CALLING saveStats\n");} saveStats($file, @fileStuff); return @fileStuff; } @fileStuff=; close(FILE); if ($DBUG){debug($tabs, "file stuff => \n\n@fileStuff\n");} foreach my $line (@fileStuff){ @LineContents = split(/,/,$line ); if ($DBUG){debug($tabs, "line => $line\n");} if ($LineContents[$i] ne $ignore){ $returnArray[$index++] = $line; } } if ($DBUG){debug($tabs, "return array => \n\n@returnArray\n");} return @returnArray; } ##############TEAMS AVAILABLE################################ # This routine constructs an array of the teams involved in a # data base. # # INPUT: None # OUTPUT: The teams that are in the csv files # DPENDENCIES: openFile() ############################################################# sub teamsArray { my($ignoreThisTeam) = @_; my %teams = (); my @player = (); my $playerStat = ""; my @playersStats = openFileWIgnore(PLAYERS_DB, $ignoreThisTeam, 1); if(@playersStats > 0){ foreach my $playerStat (@playersStats){ @player = split(/,/,$playerStat); $teams{$player[1]}=1; } }else{ prompt_clear(0); print "------ t e a m s a r r a y ---------------\n". "\nThere are no teams ... No complete DBs! \n". "There has to be at least two full teams!\n\n"; configFileReadMe(); prompt_clear(1); } my @teamsAvail = keys %teams; return @teamsAvail; } ############# A V A I L A B L E T E A M S ############### #This routine makes an array of specified items in an #existing array and prints them out # # INPUT: None # OUTPUT: The teams that are in the csv files # DPENDENCIES: teamsArray("___"), # openFile() ############################################################# sub teamsAvailable { print"\nHere are the teams available:\n"; my @teams=teamsArray("___"); for (my $i = 0;$i < @teams;$i++){ if ($i % 5 == 0){ print"\n"; } print "$teams[$i]\t"; } print"\n"; } ##################SAVE STATS################################# # This subroutine opens a specified file and reads it into # an array of lines. # # IN: File Path, # Data to be saved in said file # (copied over if file exists) # OUT: A file that contains the data # specified # SUBROUTINES NEEDED: none. # EXAMPLE: saveStats(PLAYERS_DB, @playersStats); ############################################################# sub saveStats { my($file, @stuffToBeFiled) = @_; if($DBUG){ print "----------SAVE STATS BEGIN ----------\n"; print "file = $file\n"; print "stuffToBeFiled(#) = $#stuffToBeFiled\n"; } open(FILE, ">$file") || die "Error opening $file: $!\n"; print FILE @stuffToBeFiled; close(FILE); if($DBUG){ print "----------SAVE STATS BEGIN ----------\n"; print "file = $file\n"; print "stuffToBeFiled(#) = $#stuffToBeFiled\n"; } } #####reinsertPlayer################################## # This subroutine takes a string and a line number # and changes the line number in that string. First # the string is put into an array and then the new # line number is inserted, then the string is returned. # # INPUT: String,number, "index of line in array" # OUTPUT: String # DEPENDENCIES: Just the $player[9] needs changeLines, # comment out if not needed ##################################################### sub reinsertPlayer { my($playerString, $whatLine, $index) = @_; my @thisPlayer = split(/,/,$playerString); $thisPlayer[$index] = $whatLine; my $stat = join(',', @thisPlayer); return $stat; } ##################CHANGE LINES############################### # This subroutine opens a file (NEEDS SUB OPENFILE) and goes # through a roster one player at a time. The user has an # option to change lines. # # IN: Team Wanted, (1 or 0), 1 if manual, # 0 if random line # OUT: A saved file of the db that was edited # NEEDED SUBROUTINES: openFile(filePath), saveStats(filepath, # data), printRunningTotal(lineNumber) # {included} reinsertPlayer(string,number) # {included} ############################################################# sub changeLines{ ##################PRINT RUNNING TOTAL################ # This subroutine keeps and prints a running toatl # of how many players are on each line. This routine # is for subroutine changeLines only and uses global # variables (not portable) # # INPUT: integer (line number) # array (line count array) # # OUTPUT: array (Line count array) ##################################################### sub printRunningTotal { my($lineNumber, @lineCount) = @_; $lineCount[$lineNumber]++; print"Running Total => line 1"; print"[$lineCount[1]],"; print" line 2[$lineCount[2]],"; print" line 3[$lineCount[3]],"; print" line 4[$lineCount[4]],"; print" Not dressed[$lineCount[5]]\n"; return @lineCount; } #CHANGE LINES START################################## my($teamWanted,$manOrRand) = @_; my $clear = "\n" x 100; my $line = "#" x 33; if($manOrRand == 1){ prompt_clear(0); print"\nq to quit\n1 = line 1\n2 = line 2 ". "...etc.\n5 = not dressed\n". "HINT: type p to see the players available\n\n"; print"SKATERS $line\n"; } # First we will do the players###################################### # This section opens a file of players and then # initializes the players number and start a array of # counts of how many players on a given line (has to # be running total due to the sequential nature of the # reading of the file). It then reads each line of # the file and finds the team wanted. Once team # wanted if found the line of that player is reported # and the user inputs the line to be changed or hits # enter to continue. If the random line action is # invoked then the lines are assigned as the players # are encountered in the database. #################################################################### sorter(3, 2, PLAYERS_DB); # Sort by +/- my @playersStats =openFile(PLAYERS_DB) ; my @playersSStats =openFile(SEASON_P_DB) ; my $plyerNumber = 0; my @lineCount = (0,0,0,0,0,0); my @player = (); my $new_line; foreach my $playerStat (@playersStats){ chomp $playerStat; @player = split(/,/, $playerStat); #######################Find each team member. if ($player[1] eq $teamWanted){ $plyerNumber++; ###############Manual or auto? if ($manOrRand == 1){ ## MANUAL! print"\n$plyerNumber. $player[0] is on line $player[9]: ". "change to ==> "; $new_line = ; chomp $new_line; if ($new_line eq "p"){ printPlayersAvailable($teamWanted); print "Change to --> "; $new_line = ;chomp $new_line; } if ($new_line ge 1 && $new_line le 5) { $playerStat = reinsertPlayer($playerStat, $new_line, 9); $player[9] = $new_line; @lineCount = printRunningTotal($player[9], @lineCount); } elsif ($new_line eq "q" || $new_line eq "Q"){ last; } else{ @lineCount = printRunningTotal($player[9], @lineCount); $new_line = $player[9]; } } else { ## AUTO! if ($plyerNumber < 6){ $playerStat = reinsertPlayer($playerStat, 1, 9); $new_line = 1; } elsif ($plyerNumber < 11){ $playerStat = reinsertPlayer($playerStat, 2, 9); $new_line = 2; } elsif ($plyerNumber < 16){ $playerStat = reinsertPlayer($playerStat, 3, 9); $new_line = 3; } elsif ($plyerNumber < 19){ $playerStat = reinsertPlayer ($playerStat, 4, 9); $new_line = 4; } else{ $playerStat = reinsertPlayer ($playerStat, 5, 9); $new_line = 5; } } # Update the season stats page my @p; foreach my $i (@playersSStats) { @p = split (/,/, $i); if ($p[0] eq $player[0]) { $i = reinsertPlayer($i, $new_line, 9); } } } $playerStat = "$playerStat\n"; } # Now for the goalies############################################### # The goalies process is much the same as for the # players except that the goalies are either # 1=starting, 2=backup, or 3+=not dressed. # The arrays and file are goalieStat instead of the # playerStat above. ##################################################################### if($manOrRand == 1){ print"\nGOALIES $line\n"; } sorter(4, 7, GOALIES_DB); # Sort by wins my @goalieStats =openFile(GOALIES_DB) ; my @goalieSStats=openFile(SEASON_G_DB); my $goalieCount = 1; foreach my $goalieStat (@goalieStats){ chomp $goalieStat; @player = split(/,/,$goalieStat); if ($player[1] eq $teamWanted){ ####################MANUAL OR AUTO? if($manOrRand == 1){ if($player[3] eq 1){ print"\n$plyerNumber. $player[0] is starting". "in goal: change to ==> "; }elsif($player[3] eq 2){ print"\n$plyerNumber. $player[0] is backup goalie". ": change to ==> "; }else{ print"\n$plyerNumber. $player[0] is not dressed". ": change to ==> "; } $new_line = ; chomp $new_line; if ($new_line eq "p"){ printPlayersAvailable($teamWanted); print "Change to --> "; $new_line = ;chomp $new_line; } $plyerNumber++; if ($new_line eq "1" || $new_line eq "2" || $new_line eq "3"){ $goalieStat = reinsertPlayer ($goalieStat, $new_line, 3); }elsif ($new_line eq "q" || $new_line eq "Q"){ last; }else{ $goalieStat="$goalieStat\n"; $new_line = $player[3]; next; } } else{ if($goalieCount == 1){ $goalieCount++; $goalieStat = reinsertPlayer ($goalieStat, 1, 3); $new_line = 1; } elsif($goalieCount == 2){ $goalieCount++; $goalieStat = reinsertPlayer ($goalieStat, 2, 3); $new_line = 2; } else{ $goalieStat = reinsertPlayer ($goalieStat, 3, 3); $new_line = 3; } }# END MANUAL OR AUTO! # Update the season stats page my @g; foreach my $j (@goalieSStats) { @g = split (/,/, $j); if ($g[0] eq $player[0]) { $j = reinsertPlayer($j, $new_line, 3); } } } $goalieStat="$goalieStat\n"; } # Save changes####################################### # Now if the user has typed q or the end of the # files has been reached the user is prompted to # save. ##################################################### my $answer = "x"; if($manOrRand == 1){ while ($answer ne "y" && $answer ne "Y" && $answer ne "n" && $answer ne "N"){ print "\nDo you want to save changes? (y or n) -->"; $answer=; chomp $answer; } print $clear; } else{ $answer="y"; } if ($answer eq "y" || $answer eq "Y"){ saveStats(PLAYERS_DB, @playersStats) ; saveStats(GOALIES_DB, @goalieStats) ; saveStats(SEASON_P_DB, @playersSStats); saveStats(SEASON_G_DB, @goalieSStats) ; #update the teams web pages my %teams = makeTeamNameHash(); # Each team and their name delete $teams{FREE_AGENT}; foreach my $t (keys %teams){updateTeamHTML($t);} } } ###############COUNT LINES################################### # This subroutine counts the players that are on each line. # This subroutine NEEDS the subroutine OPEN FILE. # # INPUT: string (team abbr.) # # OUTPUT: array (goalie line count) # # SAMPLE CALL: @array=countGoalies($team); ############################################################# sub countGoalies { my($t) = @_; my @gs =openFile(GOALIES_DB); ###############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 @gc = (0,0,0); foreach my $goalieStat (@gs){ my @goalie = split(/,/,$goalieStat); if ($goalie[1] eq $t && $goalie[3] == 1){ $gc[0]++; }elsif($goalie[1] eq $t && $goalie[3] == 2){ $gc[1]++; }elsif($goalie[1] eq $t && $goalie[3] == 3){ $gc[2]++; } } return @gc; } ###############COUNT LINES################################### # This subroutine counts the players that are on each line. # This subroutine NEEDS the subroutine OPEN FILE. # # INPUT: string (team abbr.) # # OUTPUT: array (line count) # # SAMPLE CALL: @array=countGoalies($team); ############################################################# sub countPlayers { my($teamWanted) = @_; my @playersStats=openFile(PLAYERS_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); ##################################################### 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]++; } } return @lineCount; } ######REPORT LINES########################################### # his subroutine prints a report of the lines of a hockey # team and more specifically the number dressed for each line. # # INPUT: a team example 'nyr' # OUTPUT: printed report # DEPENDENCIES: countGoalies(team) # countPlayers(team) ############################################################# sub reportLines { my($t) = @_; my @glcount = countGoalies($t); my @plcount = countPlayers($t); print"There are $plcount[0] player(s) on line 1\n"; print"There are $plcount[1] player(s) on line 2\n"; print"There are $plcount[2] player(s) on line 3\n"; print"There are $plcount[3] player(s) on line 4\n"; print"There are $plcount[4] player(s) not dressed\n"; print"There are $glcount[0] goalie(s) starting\n"; print"There are $glcount[1] goalie(s) starting "; print"as backup\nThere are $glcount[2]"; print" goalie(s) not dressed\n"; } ######INSPECT LINES########################################## # This subroutine prints out a warning if the lines on the # team are not set - aka 5 per line 1-3 and 3 for line 4. # INPUT: team abr. # OUTPUT: 0 if ok - 1 if line errors exists:BOOLEAN # # DEPENDENCIES: countGoalies(team) # countPlayers(team) ############################################################# sub inspectLines { my($t) = @_; my $d = 3; #debug indent if($DBUG){debug ($d, "\nINSPECT LINES:\n");} if($DBUG){debug ($d, "Incoming => $t\n");} my @glcount = countGoalies($t); if($DBUG){debug ($d, "glcount => @glcount\n");} my @plcount = countPlayers($t); if($DBUG){debug ($d, "plcount => @plcount\n");} my $lineErrorFlag = 0; if($DBUG){debug ($d, "Going in player count Error flag => ". "$lineErrorFlag\n");} for (my $i = 0; $i < 3; $i++){ if ($plcount[$i] > 5 || $plcount[$i] < 5){ $lineErrorFlag=1; } } if($DBUG){debug ($d, "Comming out Error flag => $lineErrorFlag\n");} if($DBUG){debug ($d, "Going in goalie count Error flag => ". "$lineErrorFlag\n");} for (my $i = 0; $i < 2; $i++){ if ($glcount[$i] > 1 || $glcount[$i] < 1){ $lineErrorFlag=1; } } if($DBUG){debug ($d, "Comming out Error flag => $lineErrorFlag\n");} if($DBUG){debug ($d, "Going in ".'$plcount[3] > 3'." Error flag => ". "$lineErrorFlag\n");} if ($plcount[3] > 3 || $plcount[3] < 3){ $lineErrorFlag=1; } if($DBUG){debug ($d, "Comming out Error flag => $lineErrorFlag\n");} if($DBUG){debug ($d, "returning => $lineErrorFlag\n");} return $lineErrorFlag; } # P R I N T B H L ######################################### # Prints to the screena BHL banner. # # INPUT: None # OUTPUT: output to screen # DEPENDENCIES: None ############################################################# sub printBHL { my $miniLine="-" x 55; print" ______ _ _ _ \n"; print" |######||#| |#||#| \n"; print" |##| |#||#| |#||#| \n"; print" |######||#####||#| \n"; print" |##| |#||#| |#||#|_ \n"; print" |######||#| |#||###| \n"; print"$miniLine \n"; print" $SEASON_NAME Season \n"; print"$miniLine \n"; } #GET EDITOR ANSWER########################################### # getEAnswer subroutine prints a list of options and gets # from the user an answer which is returned (for editor). # # INPUT: None # OUTPUT: A answer (letter) # DEPENDENCIES: None ############################################################# sub getEAnswer { my $miniLine="-" x 55; printBHL(); print"Type 'quit'............................to quit this menu.\n"; print"Type 'exit'......................................to exit.\n"; print"Type 'teams'.........................for available teams.\n"; print"Type 'edit teams'.....................to edit teams info.\n"; print"Type 'players'.....................for available players.\n"; print"Type 'edit'................................to edit lines.\n"; print"Type 'team inspect'................for a line inspection.\n"; print"Type 'league inspect'.....to inspect all teams in league.\n"; print"Type 'create player'..................to create a player.\n"; print"Type 'create team'......................to create a team.\n"; print"Type 'delete player'..................to delete a player.\n"; print"Type 'gig' ................................. to log a bug\n"; print"Type 'trade'............................to trade players.\n"; print"Type 'sign'..to sign or release players from free agency.\n"; print"$miniLine\n"; print"$SEASON_NAME LEAGUE EDITOR --> "; my $a=; chomp $a; return $a; } #GET SEASON ANSWER##################################################### # getSAnswer subroutine prints a list of options and gets # from the user an answer which is returned (for season). # # INPUT: None # OUTPUT: A answer (letter) # DEPENDENCIES: None ####################################################################### sub getSAnswer { my $miniLine="-" x 55; printBHL(); print" 'e' ................................. edit league\n". " 'r' ................................... run games\n". " 'n' ........................ run league navagator\n". " 'stand' .......................... view standings\n". " 'sched' ........................... view schedule\n". " 'player' ...................... view player stats\n". " 'goalie' ...................... view goalie stats\n". " 'trades' ............................ view trades\n". " 'p' ................... sort stats page by points\n". " 'gig' .............................. to log a bug\n". " 'q' ........................................ quit\n"; print"$miniLine\n"; print"$SEASON_NAME MAIN MENU --> "; my $a=; chomp $a; return $a; } #GET PLAYOFFS ANSWER##################################################### # getSAnswer subroutine prints a list of options and gets # from the user an answer which is returned (for playoffs). # # INPUT: None # OUTPUT: A answer (letter) # DEPENDENCIES: None ####################################################################### sub getPAnswer { my $miniLine="-" x 55; printBHL(); print" P L A Y O F F M O D E \n". "=======================================================\n". "Type 'p'........................for available players.\n". " 'e'................................to edit lines.\n". " 'r' ................................... run games\n". " 'n' ........................ run league navagator\n". " 'stand' .......................... view standings\n". " 'sched' ........................... view schedule\n". " 'player' ...................... view player stats\n". " 'goalie' ...................... view goalie stats\n". " 'trades' ............................ view trades\n". " 'gig' .............................. to log a bug\n". " 'q' ........................................ quit\n"; print"$miniLine\n"; print"BHL PLAYOFFS --> "; my $a=; chomp $a; return $a; } #GET SEASON STARTER ANSWER ############################################ # getSAnswer subroutine prints a list of options and gets # from the user an answer which is returned (for playoffs). # # INPUT: None # OUTPUT: A answer (letter) # DEPENDENCIES: None ####################################################################### sub getSSAnswer { my $miniLine="-" x 55; printBHL(); print" STARTUP LEAGUE \n". "=======================================================\n". "Type 'q'.......................................to quit\n". " 'gig' .............................. to log a bug\n". " 's' .............................. start a season\n"; print"$miniLine\n"; print"START HERE --> "; my $a=; chomp $a; return $a; } #GET EDITOR ANSWER########################################### # getTAnswer subroutine prints a list of options and gets # from the user an answer which is returned (for editor). # # INPUT: None # OUTPUT: A answer (letter) # DEPENDENCIES: None ############################################################# sub getTAnswer { my $miniLine="-" x 55; printBHL(); print"Type 'q'.............................to quit this menu.\n"; print"Type 'e'.......................................to exit.\n"; print"Type 'n'.............................to edit team name.\n"; print"Type 'o'............................to edit team owner.\n"; print"Type 'a'..........................to edit team address.\n"; print"Type 'c'..........................to edit contact info.\n"; print"Type 'v'............................to edit arena name.\n"; print"Type 'f'........................to edit arena capicity.\n"; print"Type 'i'................................see teams info.\n"; print"Type 's'...............................to save changes.\n"; print"$miniLine\n"; print"$SEASON_NAME TEAMS DB EDITOR --> "; my $a=; chomp $a; return $a; } ############### TEAMS DB EDIT ######################################## # Edits the Teams db file. # # INPUT: none # # OUTPUT: none # # DEPEND: openFile($file); # getTAnswer(); # prompt_clear(); # getTeam (); # teamsAvailable(); # teamsArray("___"); # getTeam(); # checkTeam(); # # SAMPLE CALL: teamsDbEdit(); ######################################################################## sub teamsDbEdit{ ##################################################################### sub change_this { my($id, $value, $index, @a) = @_; foreach my $team (@a){ my @line = split(/,/,$team); if ($id eq $line[0]){ $line[$index] = $value; } $team = join(',', @line); } return @a; } ##################################################################### sub get_line { my ($team_name, @db) = @_; my @this_lines_stuff = (); foreach my $line (@db){ @this_lines_stuff = split (/,/, $line); if ($team_name eq $this_lines_stuff[0]){ return @this_lines_stuff; } } return 1; } ##################################################################### sub edit_cap { my (@db) = @_; my $INDEX = 21; prompt_clear(0); teamsAvailable(); my $flg = 0; my $team = getTeam("Name of"); if($team eq '1'){ return @db; }else{ my @teams_data = get_line($team, @db); print "The arena of $team is named $teams_data[$INDEX],\n". "What do you want to change it to => "; my $new_name = ; chomp $new_name; $new_name = saftyFirst($new_name); print "Do you want to continue? This action will be saved \n". "and cannot be reversed. ('y' or 'n') => "; my $answer = ;chomp $answer; if ($answer ne 'y'){return ($flg, @db);} ## Edit the schedule html page my $f = ""; if ($PLAYOFF_MODE){ $f = PLAYOFF_DIR."/schedule.html"; } else { $f = SEASON_DIR."/schedule.html"; } my @fc = openFile($f); foreach (@fc){ s/$teams_data[$INDEX]/$new_name/g; } saveStats($f, @fc); $flg = 1; return ($flg, (change_this($team, $new_name, $INDEX, @db))); } } ##################################################################### sub edit_arena { my (@db) = @_; my $INDEX = 20; prompt_clear(0); teamsAvailable(); my $flg = 0; my $team = getTeam("Name of"); if($team eq '1'){ return @db; }else{ my @teams_data = get_line($team, @db); print "The arena of $team is named $teams_data[$INDEX],\n". "What do you want to change it to => "; my $new_name = ; chomp $new_name; $new_name = saftyFirst($new_name); print "Do you want to continue? This action will be saved \n". "and cannot be reversed. ('y' or 'n') => "; my $answer = ;chomp $answer; if ($answer ne 'y'){return ($flg, @db);} ## Edit the schedule html page my $f = ""; if ($PLAYOFF_MODE){ $f = PLAYOFF_DIR."/schedule.html"; } else { $f = SEASON_DIR."/schedule.html"; } my @fc = openFile($f); foreach (@fc){ s/$teams_data[$INDEX]/$new_name/g; } saveStats($f, @fc); $flg = 1; return ($flg, (change_this($team, $new_name, $INDEX, @db))); } } ##################################################################### sub edit_address { my (@db) = @_; my $INDEX = 18; prompt_clear(0); teamsAvailable(); my $flg = 0; my $team = getTeam("Name of"); if($team eq '1'){ return @db; }else{ my @teams_data = get_line($team, @db); print "The address of $team is $teams_data[$INDEX],\n". "What do you want to change it to => "; my $new_name = ; chomp $new_name; $new_name = saftyFirst($new_name); print "Do you want to continue? This action will be saved \n". "and cannot be reversed. ('y' or 'n') => "; my $answer = ;chomp $answer; if ($answer ne 'y'){return ($flg, @db);} ## Edit the schedule html page my $f = ""; if ($PLAYOFF_MODE){ $f = PLAYOFF_DIR."/schedule.html"; } else { $f = SEASON_DIR."/schedule.html"; } my @fc = openFile($f); foreach (@fc){ s/$teams_data[$INDEX]/$new_name/g; } saveStats($f, @fc); $flg = 1; return ($flg, (change_this($team, $new_name, $INDEX, @db))); } } ##################################################################### sub edit_email { my (@db) = @_; my $INDEX = 19; prompt_clear(0); teamsAvailable(); my $flg = 0; my $team = getTeam("Name of"); if($team eq '1'){ return @db; }else{ my @teams_data = get_line($team, @db); print "The contact info for $team is $teams_data[$INDEX],\n". "What do you want to change it to => "; my $new_name = ; chomp $new_name; $new_name = saftyFirst($new_name); print "Do you want to continue? This action will be saved \n". "and cannot be reversed. ('y' or 'n') => "; my $answer = ;chomp $answer; if ($answer ne 'y'){return ($flg, @db);} ## Edit the schedule html page my $f = ""; if ($PLAYOFF_MODE){ $f = PLAYOFF_DIR."/schedule.html"; } else { $f = SEASON_DIR."/schedule.html"; } my @fc = openFile($f); foreach (@fc){ s/$teams_data[$INDEX]/$new_name/g; } saveStats($f, @fc); $flg = 1; return ($flg, (change_this($team, $new_name, $INDEX, @db))); } } ##################################################################### sub edit_owner { my (@db) = @_; my $OWNER = 17; prompt_clear(0); teamsAvailable(); my $flg = 0; my $team = getTeam("Name of"); if($team eq '1'){ return @db; }else{ my @teams_data = get_line($team, @db); print "$team owner is $teams_data[$OWNER],\n". "What do you want to change it to => "; my $new_name = ; chomp $new_name; $new_name = saftyFirst($new_name); print "Do you want to continue? This action will be saved \n". "and cannot be reversed. ('y' or 'n') => "; my $answer = ;chomp $answer; if ($answer ne 'y'){return ($flg, @db);} ## Edit the schedule html page my $f = ""; if ($PLAYOFF_MODE){ $f = PLAYOFF_DIR."/schedule.html"; } else { $f = SEASON_DIR."/schedule.html"; } my @fc = openFile($f); foreach (@fc){ s/$teams_data[$OWNER]/$new_name/g; } saveStats($f, @fc); $flg = 1; return ($flg, (change_this($team, $new_name, $OWNER, @db))); } } ##################################################################### sub edit_name { my (@db) = @_; prompt_clear(0); teamsAvailable(); my $flg = 0; my $team = getTeam("Name of"); if($team eq '1'){ return @db; }else{ my @teams_data = get_line($team, @db); print "$team is $teams_data[1],\n". "What do you want to change it to => "; my $new_name = ;chomp $new_name; print "Do you want to continue? This action will be saved \n". "and cannot be reversed. ('y' or 'n') => "; my $answer = ;chomp $answer; if ($answer ne 'y'){return ($flg, @db);} ## Edit the schedule html page my $f = ""; if ($PLAYOFF_MODE){ $f = PLAYOFF_DIR."/schedule.html"; } else { $f = SEASON_DIR."/schedule.html"; } my @fc = openFile($f); foreach (@fc){ s/$teams_data[1]/$new_name/g; } saveStats($f, @fc); $flg = 1; return ($flg, (change_this($team, $new_name, 1, @db))); } } ##################################################################### sub info { my (@db) = @_; prompt_clear(0); teamsAvailable(); my $team = getTeam("Name of"); my @teams_data = get_line($team, @db); print "\nTeam Abreviation => $teams_data[0]\n". "Team Name => $teams_data[1]\n". "Arena => $teams_data[20]\n". "Capicity => $teams_data[21]\n". "Owner => $teams_data[17]\n". "Address => $teams_data[18]\n". "Contact => $teams_data[19]\n"; if($teams_data[2] ne ''){ print "Conference => $teams_data[2]\n"; } if($teams_data[3] ne ''){ print "Division => $teams_data[3]\n"; } prompt_clear(1); } ##################################################################### my @db_file = openFile(TEAMS_DB); my $flg = 0; while(1){ prompt_clear(0); my $thing_to_do = getTAnswer(); if ($thing_to_do eq 'q'){ last; } elsif ($thing_to_do eq 'e'){ exit; } elsif ($thing_to_do eq 'n'){ ($flg, @db_file) = edit_name(@db_file); if ($flg){ saveStats(TEAMS_DB, @db_file); } } elsif ($thing_to_do eq 'i'){ info(@db_file); } elsif ($thing_to_do eq 's'){ saveStats(TEAMS_DB, @db_file); } elsif ($thing_to_do eq 'o'){ ($flg, @db_file) = edit_owner(@db_file); if ($flg){saveStats(TEAMS_DB, @db_file);} } elsif ($thing_to_do eq 'a'){ ($flg, @db_file) = edit_address(@db_file); if ($flg){saveStats(TEAMS_DB, @db_file);} } elsif ($thing_to_do eq 'c'){ ($flg, @db_file) = edit_email(@db_file); if ($flg){saveStats(TEAMS_DB, @db_file);} } elsif ($thing_to_do eq 'v'){ ($flg, @db_file) = edit_arena(@db_file); if ($flg){saveStats(TEAMS_DB, @db_file);} } elsif ($thing_to_do eq 'f'){ ($flg, @db_file) = edit_cap(@db_file); if ($flg){saveStats(TEAMS_DB, @db_file);} } else { print"What ?\n"; prompt_clear(1); } #update the teams web pages my %ts = makeTeamNameHash(); # Each team and their name delete $ts{FREE_AGENT}; foreach my $t (keys %ts){updateTeamHTML($t);} } prompt_clear(0); } ############### TEAMS DB EDIT ######################################## ############### p r o m p t c l e a r s c r e e n ################ # Prompts for a enter key then clears screen for the next screen. # # INPUT: flag (1=with prompt, 0=without) # # OUTPUT: none # # SAMPLE CALL: prompt_clear(); ######################################################################## sub prompt_clear { my($prompt) = @_; my $cs="\n" x 30; if ($prompt){ print "\nPress ENTER to continue\n"; my $bogus=;print"$bogus"; } print $cs; } sub pc { # Simple one for debugging my $cs="\n" x 25; print "\nPress ENTER to continue\n"; my $bogus=;print"$bogus"; print $cs; } ############### l e a g u e e d i t ################################## # Edits the leagues database files. # # INPUT: none # # OUTPUT: none # # DEPENDENCIES: teamsArray("___"); # prompt_clear(0); # getEAnswer(); # teamsAvailable(); # getTeam("Name of"); # changeLines($team, 1); # reportLines($team); # inspectLines($team) # checkTeam($team); # openFile($file); # countGoalies($team); # countPlayers($team); # updateNavHeader($type_flag); # # SAMPLE CALL: leagueEdit(); ######################################################################## sub leagueEdit { my @teams=teamsArray("___"); my $team = ""; my $ln="-" x 45; my $cs="\n" x 100; while(1){ prompt_clear(0); my $answer=getEAnswer(); prompt_clear(0); if($answer eq "t" || $answer eq "teams"){ prompt_clear(0); teamsAvailable(); prompt_clear(1); }elsif($answer eq "q" || $answer eq "quit") { prompt_clear(0); last; }elsif($answer eq "e" || $answer eq "edit"){ $team = getTeam("Name of"); if($team eq '1'){last}; print"\nType 'manual' for manual edit or 'auto' ". "for auto line set ==> "; my $editAnswer=; chomp $editAnswer; if ($editAnswer eq "m" || $editAnswer eq "manual"){ changeLines($team, 1); }elsif($editAnswer eq "a" || $editAnswer eq "auto"){ changeLines($team, 0); }else{ print"INVALID ANSWER\n"; } updateTeamHTML($team); prompt_clear(0); }elsif($answer eq "r" || $answer eq "report") { $team=getTeam("Name of"); if($team eq '1'){last}; print"$ln\n"; reportLines($team); prompt_clear(1); }elsif($answer eq "i" || $answer eq "team inspect") { print $cs; $team = getTeam("Inspect this"); if($team eq '1'){last}; if(inspectLines($team) == 1){ print"$ln \nThe lines are not set\n$ln\n"; reportLines($team); }else{ print"$ ln \nLines are set correctly!\n"; } prompt_clear(1); }elsif ($answer eq "exit"){ exit; }elsif ($answer eq "gig"){ print"\nLog bug and press enter to save into a bug.txt file ==> "; my @bug = openFile("bug.txt"); my $b = ; push(@bug, $b); saveStats("bug.txt", @bug); }elsif($answer eq "l" || $answer eq "league inspect") { prompt_clear(0); foreach my $team(@teams){ print "Inspecting $team ... "; if(inspectLines($team) == 1){ print "Inspected ... WARNING: LINES ARE NOT SET\n"; } else { print "Inspected ... OK\n"; } } prompt_clear(1); }elsif($answer eq "cp" || $answer eq "create player") { prompt_clear(0); createPlayer(); prompt_clear(1); }elsif($answer eq "ct" || $answer eq "create team") { prompt_clear(0); createTeam(); prompt_clear(1); }elsif($answer eq "dp" || $answer eq "delete player") { prompt_clear(0); deletePlayer(); prompt_clear(1); }elsif($answer eq "tr" || $answer eq "trade") { prompt_clear(0); trade(); updateNavHeader("rtd"); makeHtmltodayPage(); }elsif($answer eq "et" ||$answer eq "edit teams") { teamsDbEdit(); }elsif($answer eq "p" || $answer eq "players") { prompt_clear(0); print "What team?\n". "(enter 't' for a list of available teams) --> "; my $team = ;chomp $team; # get team if ($team eq "t"){ teamsAvailable(); print "What team --> "; $team = ;chomp $team; } if (!checkTeam($team, teamsArray("___"))){ # Does team exist? print "\n\nleagueEdit:Team $team does not exist!\n\n"; prompt_clear(1); last; } printPlayersAvailable($team); prompt_clear(1); }elsif ($answer eq "s" || $answer eq "sign") { freeAgents(); updateNavHeader("rtd"); makeHtmltodayPage(); }else{print"INCORRECT REPLY\n";prompt_clear(1);} } } ############### C H E C K D I R ################################# # OPEN DIR, IF IT OPENS FINE ... THEN CLOSE IT. IF NOT... WELL THEN # MAKE IT CLOSE IT. # # INPUT: string (dir to be checked) # # OUTPUT: none # # SAMPLE CALL: checkDir($dir); ######################################################################## sub checkDir { my ($dir) = @_; my $badflag = 0; opendir(DIR, $dir) || mkdir($dir, 0755) || ($badflag = 1); if ($badflag){ my $problem = "Error making dir -->'$dir'"; (my $package, my $filename, my $line) = caller; print"\n$filename:subroutine $package,$problem,line $line\n"; prompt_clear(1); } close(DIR); } ############### s a v e g a m e r e s u l t s ################# # Saves the html game results in a /games dir. # # INPUT: string (file name) # array (stuff to be made into a file) # # OUTPUT: none # # SAMPLE CALL: saveGameResults($file); ######################################################################## sub saveGameResults { my($file, $d, $hn, $an, @stuffToBeFiled) = @_; my $context = ""; my $dir = ""; if ($PLAYOFF_MODE){ checkDir(PLAYOFF_DIR); $dir = PLAYOFF_DIR . "/games"; $context = "Playoff"; } else { checkDir(SEASON_DIR); $dir = SEASON_DIR . "/games"; $context = "Season"; } my $f = 0; #Does index exist flag my $tag = ''; my $index_line = '
  • ' . "$d $an at $hn" . '

  • '; checkDir($dir); # if there is no index...create it and start it as a html page open(IFILE, "$dir/index.html") || ($f = 1); if ($f){ open(IFILE, ">$dir/index.html") || die "SAVEGAMERESULTS: can not create an index!"; print IFILE "$context Games Index ". "
      \n$tag\n
    "; } close (IFILE); my @file_lines = openFile("$dir/index.html"); foreach my $line (@file_lines){ if ($line =~ m/$tag/g){ $line = $index_line . "\n$tag\n"; } } saveStats("$dir/index.html", @file_lines); # File the reuslts into its own page! open(FILE, ">$dir/$file") || die "Error opening $dir/$file: $!\n"; print FILE @stuffToBeFiled; close(FILE); } ############### c r e a t e p l a y e r ################ # Creates a player. # # INPUT: none # # OUTPUT: none # # DEPENDENCIES: teamsAvailable(); # openFile(GOALIES_DB); # saveStats(GOALIES_DB, @goalieStats); # teamsArray("___"), # # SAMPLE CALL: createPlayer(); ######################################################################## sub createPlayer { print "What is the players full name --> "; # GET THE NAME my $player = ;chomp $player; my $pos; my @temp; while(1){ # GET POSITION print "Is the player a goalie or skater --> "; $pos = ;chomp $pos; if ($pos eq "skater" || $pos eq "goalie"){ last; } } print "What team (enter 't' for a list of available teams)--> "; my $t = ;chomp $t; # GET THE TEAM if ($t eq "t"){ teamsAvailable(); print "What team --> "; $t = ;chomp $t; } if (!checkTeam($t, teamsArray("___"))){ # Does team exist? print "\n\nGAMESETUP:Team $t does not exist!\n\n"; prompt_clear(1); last; } print "What is the players line (1-5) --> "; # GET THE LINE my $ln = ;chomp $ln; if ($pos eq "goalie"){ print "What is the goalies save % --> "; # GET THE SAVE % my $sp = ;chomp $sp; $sp = $sp/100; print "How many wins does this goalie have --> ";# GET THE WINS my $wns = ;chomp $wns; print "How many loses does this goalie have --> ";# GET THE LOSES my $los = ;chomp $los; print "How many ties does this goalie have --> ";# GET THE TIES my $tie = ;chomp $tie; print "How many saves does this goalie have --> ";# GET THE SAVES my $saves = ;chomp $saves; #GET THE GA print "How many goals against does this goalie have --> "; my $ga = ;chomp $ga; # GET GAA print "What is the goals against average for this goalie --> "; my $gaa = ;chomp $gaa; my @goalieStats =openFile(GOALIES_DB); my $new_player = "$player,$t,$sp,$ln,$wns,$los,$tie,$saves,". "$ga,$gaa,0\n"; push (@goalieStats, $new_player); print "Save ? (y or n) --> ";#SAVE ??? my $sa = ;chomp $sa; if ($sa eq "y" || $sa eq "Y"){ saveStats(GOALIES_DB, @goalieStats); @temp = openFile(SEASON_G_DB); $new_player = "$player,$t,$sp,0,0,0,0,0,0,0,0\n"; push (@temp, $new_player); saveStats(SEASON_G_DB, @temp); } } else { print "How many points does this player have --> "; #GET POINTS my $points = ;chomp $points; print "What +/- does this player have --> "; # GET THE +/- my $plusminus = ;chomp $plusminus; # GET PEN MIN print "How many pen. minutes does this player have --> "; my $penmin = ;chomp $penmin; # GET PP GOALS print "How many power play goals does this player have --> "; my $ppgoals = ;chomp $ppgoals; # GET SH GOALS print "How many short handed goals does this player have --> "; my $shgoals = ;chomp $shgoals; # GET GW GOALS print "How many game winning goals does this player have --> "; my $gwgoals = ;chomp $gwgoals; # GET GT GOALS print "How many game tieing goals does this player have --> "; my $gtgoals = ;chomp $gtgoals; print "How many shots does this player have --> "; #GET SHOTS my $shots = ;chomp $shots; print "How many goals does this player have --> "; #GET GOALS my $goals = ;chomp $goals; print "How many assists does this player have --> ";#GET ASSISTS my $assists = ;chomp $assists; my @pStats =openFile(PLAYERS_DB); my $new_player = "$player,$t,$points,$plusminus,$penmin,". "$ppgoals,$shgoals,$gwgoals,$gtgoals,$ln,". "$shots,$goals,$assists,0\n"; push (@pStats, $new_player); print "Save ? (y or n) --> ";#SAVE ??? my $sa = ;chomp $sa; if ($sa eq "y" || $sa eq "Y"){ saveStats(PLAYERS_DB, @pStats); @temp = openFile(SEASON_P_DB); $new_player = "$player,$t,0,0,0,0,0,0,0,0,0,0,0,0\n"; push (@temp, $new_player); saveStats(SEASON_P_DB, @temp); updateTeamHTML($t); } } } ############### d e l e t e p l a y e r ################ # Deletes a player fom the database. # # INPUT: none # # OUTPUT: none # # DEPENDENCIES: teamsAvailable(); # openFile(GOALIES_DB); # saveStats(GOALIES_DB, @goalieStats); # teamsArray("___"), # prompt_clear(1); # printPlayersAvailable($team); # # SAMPLE CALL: createPlayer(); ######################################################################## sub deletePlayer { print "What team is this player on \n". "(enter 't' for a list of available teams) --> "; my $team = ;chomp $team; # get team if ($team eq "t"){ teamsAvailable(); print "What team --> "; $team = ;chomp $team; } if (!checkTeam($team, teamsArray("___"))){ # Does team exist? print "\n\nGAMESETUP:Team $team does not exist!\n\n"; prompt_clear(1); last; } print "What is this players full name \n". "(enter 'p' for a list of available players) --> "; my $player = ;chomp $player; # get name if ($player eq "p"){ printPlayersAvailable($team); print "What player --> "; $player = ;chomp $player; } my @playersStats=openFile(PLAYERS_DB); my @goalieStats =openFile(GOALIES_DB); my @p = (); foreach my $playerStat (@playersStats){ @p = split(/,/, $playerStat); if ($p[1] eq $team && $p[0] eq $player){ $playerStat = ""; } } foreach my $playerStat (@goalieStats){ @p = split(/,/, $playerStat); if ($p[1] eq $team && $p[0] eq $player){ $playerStat = ""; } } saveStats(PLAYERS_DB, @playersStats); saveStats(GOALIES_DB, @goalieStats); updateTeamHTML($team); } ##################P R I N T P L A Y E R S A V A I L A B L E ######## # This subroutine lists players and their lines on a specific team: # # INPUT: string (team abrv.) # OUTPUT: screen output (name, line) # Dependencies: openFile(fileName) # # EXAMPLE CALL: printPlayersAvail($team); ######################################################################## sub printPlayersAvailable{ my($t) = @_; my @array=("\n"); my $i = 1; my $tab = ""; my $tab2 = ""; my @stats=openFile(PLAYERS_DB); foreach my $teamMembers (@stats){ my @member = split(/,/,$teamMembers); if ($member[1] eq $t){ $tab = tabber($member[0], 15); if ($i % 2 == 0){ push (@array, "$member[0],$tab line $member[9] \n"); } else { push (@array, "$member[0],$tab line $member[9] "); } $i++; } } @stats=openFile(GOALIES_DB); foreach my $teamMembers (@stats){ my @member = split(/,/,$teamMembers); if ($member[1] eq $t){ $tab = tabber($member[0], 15); if ($i % 2 == 0){ push (@array, "$member[0],$tab line $member[3] \n"); } else { push (@array, "$member[0],$tab line $member[3] "); } $i++; } } push (@array, "\n"); print @array; } ##################S T A R T S E A S O N ############################## # This subroutine starts a new season. If there has been a backup then # replace the existing db files with the backups. If there is no backup # dir. then it is assumed that the foulder and league is new an the db # files are backed up. # # INPUT: none. # OUTPUT: files created. # Dependencies: openFile(fileName) # makePlayerHtmlStats(); # makeGoalieHtmlStats(); # makeSchedule(); # makeTradeHtml(); # resetStandDB(); # makeStandingsFile(); # setMode("PLAYOFF_MODE", 0); # makeNavHeader(); # makeLeagueNavagator(); # # EXAMPLE CALL: startSeason(); ######################################################################## sub startSeason{ my $dir1 = "backups"; my $dir2 = "carreer"; my $dir3 = $SEASON_NAME; my $dir4 = TEAM_DIR; my $f1 = 0; my $f2 = 0; my $f3 = 0; # Create backup of db opendir(DIR, $dir1) || ($f1 = 1) || die "Error opening $dir1 directory:". " $!\n"; close(DIR); if ($f1 || $START){ mkdir($dir1, 0755); backErUpper(PLAYERS_DB, $dir1); backErUpper(GOALIES_DB, $dir1); } # Set overtime flag if ($START){ addToConfig("OT", 1); } # Create a carreer db opendir(DIR, $dir2) || ($f2 = 1) || die "Error opening $dir2 directory:". " $!\n"; close(DIR); if ($f2 || $START){ mkdir($dir2, 0755); backErUpper(PLAYERS_DB, $dir2); backErUpper(GOALIES_DB, $dir2); } # Create a players dir opendir(DIR, $dir4) || ($f3 = 1) || die "Error opening $dir4 directory:". " $!\n"; close(DIR); if ($f3 || $START){ mkdir($dir4, 0755); } # Creating the season tally databases my @players = openFile(PLAYERS_DB); my @goalies = openFile(GOALIES_DB); my @new_player_stuff = gameArrayZeroerOuter(9, @players); my @new_goalie_stuff = gameArrayZeroerOuter(3, @goalies); saveStats(SEASON_P_DB, @new_player_stuff); saveStats(SEASON_G_DB, @new_goalie_stuff); # Back up season db tally's to current seasonName dir if (!$START){ $dir3 =~ s/ //g; backErUpper(SEASON_P_DB, $dir3); backErUpper(SEASON_G_DB, $dir3); } # Add up season to carreer db. if (!$START){ my @pdb = addDB(SEASON_P_DB, "$dir2/" . PLAYERS_DB , 1); my @gdb = addDB(SEASON_G_DB, "$dir2/" . GOALIES_DB , 0); saveStats("$dir2/" . PLAYERS_DB , @pdb); saveStats("$dir2/" . GOALIES_DB , @gdb); } ## here I will remove the games directory...to start over sub erase{ my ($gms_dir) = @_; opendir(DIRR, $gms_dir) || print "Well, I guess $gms_dir isnt here!\n"; while (defined(my $file = readdir(DIRR))){ unlink("$gms_dir/$file"); } close(DIRR); rmdir($gms_dir); } if ($PLAYOFF_MODE){ erase(PLAYOFF_DIR . "/games"); } else{ print"Setting up the League Structure.\n"; my %h = makeTeamNameHash(); my @teamsDB = openFile(TEAMS_DB); @teamsDB=setDivisions(@teamsDB); saveStats(TEAMS_DB, @teamsDB); print"Erasing Files.\n"; erase(PLAYOFF_DIR . "/games"); erase(SEASON_DIR . "/games"); erase(SEASON_DIR); erase(PLAYOFF_DIR); print"\nMaking Player Stats Web Page\n"; makePlayerHtmlStats(); print"\nMaking Goalie Stats Web Page\n"; makeGoalieHtmlStats(); print"\nMaking The Schedule .dat file\n"; makeSchedule(); print"Making Player Trades Web Page\n"; makeTradeHtml(); print"Re-setting the teams DB\n"; resetStandDB(); print"Making Team Standings Web Page\n"; makeStandingsFile(); makeStandingsFile(); # Making sure damn it! print"Making the Today Web Page\n"; $SEASON_OVER_FLAG = 0; setMode("SEASON_OVER_FLAG", 0); addToConfig("SEASON_OVER_FLAG", 0); makeHtmltodayPage(); print"Making the The Team Web Pages ... Please stand by!\n"; makeTeamHTML(); print"Resetting playoff mode to false\n"; $PLAYOFF_MODE = 0; setMode("PLAYOFF_MODE", 0); if ($START){ print"Establishing a presence\n"; $START = 0; addToConfig("START", 0); } print"Making League Navagator Web Page\n"; makeNavHeader(); makeLeagueNavagator(); print"setMode OT to only 1 period sudden death!"; setMode("OT", 1); print".........................Done\n"; } } ############### m a k e p l a y e r h t m l s t a t s ######### # Saves the html season results in a /season dir. # # INPUT: none # # OUTPUT: html updated page # # SAMPLE CALL: makePlayerHtmlStats(); ######################################################################## sub makePlayerHtmlStats { my $file = "player_stats.html"; my $f = 0; #Does index exist flag my $tag = ''; my $index_line = ""; my $player = ""; my $dir = ""; my $context = ""; print"Making player stats page, Checking for playoff mode.\n"; if ($PLAYOFF_MODE){ $dir = PLAYOFF_DIR; $context = "Playoff"; } else { $dir = SEASON_DIR; $context = "Season"; } checkDir($dir); # if there is no season...create it and start it as a html page print"Making player stats page, no season creating new page.\n"; open(IFILE, "$dir/$file") || ($f = 1); if ($f){ open(IFILE, ">$dir/$file") || die ": can not create an index!"; print IFILE "$SEASON_NAME $context Statistics". '

    '."\n". ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n". "$tag\n
    '."\n". '

    Name
    '."\n". '

    Team
    '."\n". '

    Games
    '."\n". '

    Points
    '."\n". '

    +/-
    '."\n". '

    Pen
    '."\n". '

    PP Goals
    '."\n". '

    SH Goals
    '."\n". '

    GW Goals
    '."\n". '

    GT Goals
    '."\n". '

    Shots
    '."\n". '

    Goals
    '."\n". '

    Assists
    "; } close (IFILE); my @season = openFile(SEASON_P_DB); print"Making player stats page, SORTING ... Stand by.\n"; @season = arraySorter(2, 11, ',', @season); my @file_lines = openFile("$dir/$file"); my $flag = 0; print"Making player stats page, looking for the html tag.\n"; foreach my $line (@file_lines){ if ($line =~ m/$tag/g){ $line = "$tag\n"; $flag = 1; } elsif ($flag){ $line = " "; } } print"Making player stats page, PRINTING ... Stand by.\n"; foreach my $line (@season){ my @player = split(/,/, $line); $index_line=''."\n". ' '."\n". '

    '."$player[0]".''."\n". ' '."\n". '

    '."$player[1]".'
    '."\n". ' '."\n". '

    '."$player[13]".'
    '."\n". ' '."\n". '

    '."$player[2]".'
    '."\n". ' '."\n". '

    '."$player[3]".'
    '."\n". ' '."\n". '

    '."$player[4]".'
    '."\n". ' '."\n". '

    '."$player[5]".'
    '."\n". ' '."\n". '

    '."$player[6]".'
    '."\n". ' '."\n". '

    '."$player[7]".'
    '."\n". ' '."\n". '

    '."$player[8]".'
    '."\n". ' '."\n". '

    '."$player[10]".'
    '."\n". ' '."\n". '

    '."$player[11]".'
    '."\n". ' '."\n". '

    '."$player[12]".'
    '."\n". ''."\n"; push(@file_lines, $index_line); } push(@file_lines, "\n"); print"Making player stats page, we are done ... SAVING.\n"; saveStats("$dir/$file", @file_lines); } ############### m a k e g o a l i e h t m l s t a t s ######### # Saves the html season results in a /season dir. # # INPUT: none # # OUTPUT: html updated page # # SAMPLE CALL: makeGoalieHtmlStats(); ######################################################################## sub makeGoalieHtmlStats { my $file = "goalie_stats.html"; my $f = 0; #Does index exist flag my $tag = ''; my $index_line = ""; my $player = ""; my $dir = ""; my $context = ""; if ($PLAYOFF_MODE){ $dir = PLAYOFF_DIR; checkDir($dir); $context = "Playoff"; } else { $dir = SEASON_DIR; checkDir($dir); $context = "Season"; } # if there is no season...create it and start it as a html page open(IFILE, "$dir/$file") || ($f = 1); if ($f){ open(IFILE, ">$dir/$file") || die "makeGoalieHtmlStats: can not create $dir/$file!"; print IFILE "$SEASON_NAME $context Goalie ". 'Statistics

    '. "\n". ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n". "$tag\n
    '."\n". '

    Name
    '."\n". '

    Team
    '."\n". '

    Games
    '."\n". '

    W
    '."\n". '

    L
    '."\n". '

    T
    '."\n". '

    Save%
    '."\n". '

    S
    '."\n". '

    GA
    '."\n". '

    GAA
    "; } close (IFILE); my @season = openFile(SEASON_G_DB); @season = arraySorter(2, 4, ',', @season); my @file_lines = openFile("$dir/$file"); my $flag = 0; foreach my $line (@file_lines){ if ($line =~ m/$tag/g){ $line = "$tag\n"; $flag = 1; } elsif ($flag){ $line = " "; } } my $slvalue = 0; foreach my $line (@season){ my @player = split(/,/, $line); $slvalue = @player; if (@player > 9){ $index_line=''."\n". ' '."\n". '

    '."$player[0]".''."\n". ' '."\n". '

    '."$player[1]".'
    '."\n". ' '."\n". '

    '."$player[10]".'
    '."\n". ' '."\n". '

    '."$player[4]".'
    '."\n". ' '."\n". '

    '."$player[5]".'
    '."\n". ' '."\n". '

    '."$player[6]".'
    '."\n". ' '."\n". '

    '."$player[2]".'
    '."\n". ' '."\n". '

    '."$player[7]".'
    '."\n". ' '."\n". '

    '."$player[8]".'
    '."\n". ' '."\n". '

    '."$player[9]".'
    '."\n". ''."\n"; push(@file_lines, $index_line); } else { print "\n\nERROR in make goalie htmlstats: stat line is only $slvalue\n\n"; } } push(@file_lines, "\n"); saveStats("$dir/$file", @file_lines); } ############### s o r t e r ########################################### # Sorts a season db file. # # INPUT: integer (index of the db to be sorted) # integer (pre sort index, in case of ties) # string (db file path) # # OUTPUT: array (sorted by index) # # DEPEND: openFile($file) # # SAMPLE CALL: sorter(2, 11, PLAYERS_DB); ######################################################################## sub sorter { my ($i, $si, $file) = @_; my @sorted = (); my $largest = 0; my $smallest = 0; my $sorted_count = 0; my @stuff_to_sort = openFile($file); sub ERROR { print "\nSORTER ERROR: The data base that this program is using ". "is not formatted \ncorrectly. The fields requested are no". "t there, lines too short. \nThis program will now exit, c". "heck the readme's in this foulder\n"; prompt_clear(1); exit; } ## Pre - Find the largest to start with. foreach my $element (@stuff_to_sort){ my @line = split (/,/, $element); if (@line < $si){ERROR();} if((@line >= $si) && $line[$si] > $largest){ $largest = $line[$si]; } if($line[$si] < $smallest){ $smallest = $line[$si]; } } ## Pre - Start with the largest and work down for (my $j = $largest; $j >= $smallest; $j--){ foreach my $element (@stuff_to_sort){ my @line = split (/,/, $element); if (@line < $si){ERROR();} if ((@line >= $si) && $line[$si] == $j){ $sorted[$sorted_count] = $element; $sorted_count++; } } } # PRE #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # POST my @final_sorted = (); $largest = 0; $smallest = 0; my $final_sorted_count = 0; ## Find the largest to start with. foreach my $element (@sorted){ my @line = split (/,/, $element); if (@line < $i){ERROR();} if($line[$i] > $largest){ $largest = $line[$i]; } if($line[$i] < $smallest){ $smallest = $line[$i]; } } ## Start with the largest and work down for (my $j = $largest; $j >= $smallest; $j--){ foreach my $element (@sorted){ my @line = split (/,/, $element); if (@line < $i){ERROR();} if ($line[$i] == $j){ $final_sorted[$final_sorted_count] = $element; $final_sorted_count++; } } } saveStats($file, @final_sorted); } ############### b a c k e r u p e r ############################### # Backs up a file # # INPUT: string (file path) # string (directory) # # OUTPUT: backed up file in /backups # # DEPEND: openFile($file) # saveStats($file, @array); # # SAMPLE CALL: backErUpper($file, $dir); ######################################################################## sub backErUpper { my ($file, $dir) = @_; checkDir($dir); ## if directory dosent exists...then make it! my $badflag = 0; open(FILEBEU, $file) || ($badflag = 1); if ($badflag){ print"\nbackErUpper: $file does not exist\n"; return; } my @stuff = ; close(FILEBEU); if ($dir eq "."){ my @path = split ('/', $file); $file = $path[@path-1]; } saveStats("$dir/$file", @stuff); } ############### r o u n d e r ########################################## # formatts to the given percision a float # # INPUT: float # integer (percision) # # OUTPUT: float (adjusted to the given percision) # # DEPEND: none # # SAMPLE CALL: $save_percentage = rounder(.23456789, 3); ######################################################################## sub rounder { my ($value, $this_many_places) = @_; my $percision = 0; my @future_number = (1); for (my $i = 0; $i < $this_many_places; $i++){ $future_number[@future_number] = 0; } $percision = int(join('', @future_number)); return ((int(($value*100)+.5))/$percision); } ############### M A K E S C H E D U L E ############################## # CONSTRUCTS A SEASON SCHEDULE DATA FILE # # INPUT: none # # OUTPUT: file # # DEPEND: teamsArray("___"); # saveStats(SCHED_DAT, @teams); # getDate() # makeTeamNameHash(); # # SAMPLE CALL: makeSchedule(); ######################################################################## sub makeSchedule { ## Set the variables my $opponents = ""; my $this_team = ""; my @teams = teamsArray(FREE_AGENT); my @schedule = (); my $i = 0; my $dat_file = SCHED_DAT; ## Randomize the teams array!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ sub randomize{ my $array = shift; my $j; for (my $j=@$array; --$j;){ my $k = int rand ($j+1); next if $j == $k; @$array[$j,$k] = @$array[$k,$j]; } } ## End Randomize the teams array!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ## Make HTML page! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ sub makeHtmlSched{ my ($file, $ctxt, @season) = @_; my $f = 0; # Does index exist flag my $index_line = ""; my $player = ""; my @date = getDate(); # For dates my $day = 0; # For dates my @buffer =(); my $ag_number = 0; # away games number if ($PLAYOFF_MODE){ $ag_number = 1; checkDir(PLAYOFF_DIR); } else { $ag_number = (@season - 1); checkDir(SEASON_DIR); } # Create it and start it as a html page $buffer[0] = "$SEASON_NAME $ctxt Schedule". '

    '. "$SEASON_NAME $ctxt".' Schedule

    '. ''; ######################################################## sub scheduler{ my ($tdy, $buff, @szn) = @_; my @team = (); my $home = ""; my $away = ""; my $homeName = ""; my $awayName = ""; my @buffr = @$buff; my %tnhash = makeTeamNameHash(); my $flag = 0; my %teams_played = (); foreach my $line (@szn){ chomp $line; @team = split(/,/, $line); if((!(exists $teams_played{$team[0]} )) &&(!(exists $teams_played{$team[@team-1]})) &&(@team > 1)){ $home = pop(@team); $away = $team[0]; $awayName = $tnhash{$away}; $homeName = $tnhash{$home}; chomp $awayName; chomp $homeName; push (@buffr, "\n".' '."\n". ' '."\n". ' ' ."\n". ' '."\n". ' ' ."\n". ' '."\n". ' '."\n". ' '); $teams_played{$home}=$away; $teams_played{$away}=$home; $flag = 1; } $line = join(',', @team); $line = "$line\n"; } $buff = \@buffr; return ($flag, $buff, @szn); } ######################################################## my $today = "$date[0]/$date[1]/$date[2]"; my $games_have_run = 1; while ($games_have_run){ my $bffr = \@buffer; ($games_have_run, $bffr, @season) = scheduler($today, $bffr, @season); @buffer = @$bffr; ## Increment day if ($date[0] == 2 && $date[1] == 28){ $date[0]++; $date[1] = 1; }elsif (($date[0] == 4 || $date[0] == 6 || $date[0] == 9 || $date[0] == 11) && $date[1] == 30){ $date[1] = 1; $date[0]++; }elsif ($date[1] == 31 && $date[0] == 12){ $date[1] = 1; $date[0] = 1; $date[2]++; }elsif ($date[1] == 31){ $date[1] = 1; $date[0]++; }else{ $date[1]++; } $today = "$date[0]/$date[1]/$date[2]"; ## END Increment day my $top_o_array = shift(@season); push(@season, $top_o_array); } push (@buffer, "\n
    '."$tdy".''."$awayName".''."at".''."$homeName".''."-".''."-".'
    "); saveStats($file, @buffer); } ## End Make HTML page! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ## Make the context and do stuff in each case my $context = ""; my $f = ""; if ($PLAYOFF_MODE){ $f = PLAYOFF_DIR."/schedule.html"; $context = "Playoff"; @schedule = openFile(SCHED_DAT); } else { ## Randomize the teams array! if (@teams > 1){ randomize(\@teams); } else { print "ERROR: Making schedule ... teams array is empty\n"; prompt_clear(1); exit; } $context = "Season"; $f = SEASON_DIR."/schedule.html"; ## for each team in the team array ... apend the other teams to ## its Q. Make an array of Qs! Then save it to a file. my @t = @teams; # going to try to randomize the schedule foreach my $team1(@teams){ chomp $team1; $this_team = $team1; $opponents = ""; if (@t > 1){ randomize(\@t); } else { print "ERROR: Making schedule ... t array is empty\n"; prompt_clear(1); exit; } if (@t > 1){ randomize(\@t); } else { print "ERROR: Making schedule ... 2nd t array is empty\n"; prompt_clear(1); exit; } foreach my $team2(@t){ if($team1 ne $team2){ $opponents = $opponents . "," . $team2; } } $schedule[$i] = "$this_team$opponents\n"; $i++; } saveStats($dat_file, @schedule); } makeHtmlSched($f, $context, @schedule); } ############### u p d a t e H t m l S c h e d ####################### # updates the season page with the new scores of games just played # # INPUT: integer (home score) # integer (away score) # string (home team) # string (away team) # # OUTPUT: html page (schedule.html) # # DEPEND: none # # SAMPLE CALL: updateHtmlSched($hscore, $ascore); ######################################################################## sub updateHtmlSched { my ($hs, $as, $htn, $atn) = @_; my @line1; my @line2; my @line3; my $updated = 0; chomp $htn; chomp $atn; my $dir = ""; if ($PLAYOFF_MODE){ $dir = PLAYOFF_DIR; } else { $dir = SEASON_DIR; } my @page = openFile("$dir/schedule.html"); # for (my $i = 0; $i < @page; $i++){ # Loop thr. page @line1 = split(/[<>]/, $page[$i]); # foreach my $item (@line1){ # if ($item eq $atn){ # is it away @line2 = split(/[<>]/, $page[$i+2]); # foreach my $item (@line2){ # if ($item eq $htn){ # is it home @line3 = split(/[<>]/, $page[$i+3]); # foreach my $item (@line3){ # if ($item eq "-" && !($updated)){ # is it unplayed $page[$i+3] =~ s/-/$as/g; # rep. w/ score $page[$i+4] =~ s/-/$hs/g; # rep. w/ score $updated = 1; # lets go now! } } } } } } } saveStats("$dir/schedule.html", @page); } ############### c h e c k d b ###################################### # checks the db files for correctness and attempts to fix bad data # # INPUT: none # # OUTPUT: none # # DEPEND: prompt_clear(1); # # SAMPLE CALL: checkDB(); ######################################################################## sub checkDB { my @p_file=openFile(PLAYERS_DB); my @g_file=openFile(GOALIES_DB); # Test the config file. my $f = 0; open(SPFILE, CONFIG_FILE) || ($f = 1); close (SPFILE); if ($f){setUpSimCfg();} sub check{ my @array = @_; my $total = 0; foreach my $line (@array){ my @elements = split(/,/, $line); if ($total == 0){ $total = @elements; next; }elsif ($total != @elements){ print "CHECKDB: ERROR...bad db files!\n"; prompt_clear(1); exit; } } } check(@p_file); check(@g_file); } ############### r u n g a m e s ##################################### # Using the schedule queues, run todays games. # # INPUT: none # # OUTPUT: array (results) # # DEPEND: openFile(SCHED_DAT); # runGame($h, $a, $HOME_ADVANTAGE, $P_P_ADVANTAGE, # $GOALIE_STRENGTH, $OT); # updateNavHeader($type_flag); # setMode("PLAYOFF_MODE", 1); # # SAMPLE CALL: runGames(); ######################################################################## sub runGames { my $no_dat = 0; my $d = 0; open(FILE, SCHED_DAT) || ($no_dat = 1); if($no_dat){startSeason();prompt_clear(1);next;} my @schedule = openFile(SCHED_DAT); my $team = ""; my $home = ""; my $away = ""; my $games_have_run = 0; my %teams_played = (); $teams_played{'a'} = 'b'; # JUST INITIALIZING my @results = (); my $hs = 0; #HOME SCORE my $as = 0; #AWAY SCORE my @oponents = (); my $still_no_champ = 0; if($DBUG){debug ($d, "\nRUN GAMES:\n");} if($DBUG){debug ($d, "RUN GAMES:foreach my $team (@schedule)\n");} foreach my $team (@schedule){ chomp $team; @oponents = split(/,/, $team); if((!(exists $teams_played{$oponents[0]} )) &&(!(exists $teams_played{$oponents[@oponents-1]})) &&(@oponents > 1)){ print"Getting teams off the schedule.dat file.......\n"; $home = pop(@oponents); $away = $oponents[0]; print"Hashing teams played today....................\n"; $teams_played{$home}=$away; $teams_played{$away}=$home; print"Running the game now..........................\n"; @results = runGame($home, $away, $HOME_ADVANTAGE, $P_P_ADVANTAGE, $GOALIE_STRENGTH, $OT); print"Game over updating home db files..............\n"; updateTeamDB(@results); print"Obtaining a score.............................\n"; $hs = $results[0] + $results[1] + $results[2] + $results[3]; $as = $results[4] + $results[5] + $results[6] + $results[7]; print"Updating HTML pages...........................\n"; updateHtmlSched($hs, $as, $results[28], $results[29]); print"Game over updating away db files..............\n"; updateTeamHTML($away); print"Game over updating team web files.............\n"; updateTeamHTML($home); print"Putting results to the screen please stand by.\n"; prompt_clear(); printScreenResults($home, $away, @results); prompt_clear(1); print"Making HTML results pages.....................\n"; makeHtmlResults(@results); print"Counting this game as played..................\n"; $games_have_run++; } $team = join(',', @oponents); $team = "$team\n"; } print"Updating standings............................\n"; makeStandingsFile(); print"Making todays headlines.......................\n"; makeHtmltodayPage(); print"Sorting the DBs...............................\n"; sorter(2, 11, SEASON_P_DB); # sort print"Making player stats............PLEASE STAND BY\n"; makePlayerHtmlStats(); # update page print"Making player stats............PLEASE STAND BY\n"; makeGoalieHtmlStats(); # update page my $next_round_flag = isThereAChampion(); if($DBUG){debug ($d, "RUN GAMES: $next_round_flag = isThereAChampio". "n()\n");} if($DBUG){debug ($d, "RUN GAMES: if(!$games_have_run && !". "($PLAYOFF_MODE))\n");} if(!$games_have_run && !($PLAYOFF_MODE)){ print"S E A S O N O V E R - E N T E R I N G P L A Y O ". "F F S\n\n"; prompt_clear(1); $PLAYOFF_MODE = 1; $ROUND = 1; setMode("PLAYOFF_MODE", 1); addToConfig("ROUND", 1); updateNavHeader("pfs"); $OT = 2; # Play forever! addToConfig("OT", 2); setUpPlayoffs(); } elsif(!$games_have_run && ($PLAYOFF_MODE) && (!$next_round_flag)){ print"T H I S R O U N D I S O V E R - E N T E R I N G ". " N E X T R O U N D\n\n"; $ROUND ++; setMode("ROUND", $ROUND); prompt_clear(1); setUpNextRound(); } elsif(!$games_have_run && ($PLAYOFF_MODE)){ $SEASON_OVER_FLAG = 1; makeHtmltodayPage(); setMode("SEASON_OVER_FLAG", 1); addToConfig("SEASON_OVER_FLAG", 1); $SEASON_NUM++; setMode("SEASON_NUM", $SEASON_NUM); my $winner = printLeader(); print"S E A S O N O V E R\n\n$winner is the champion "; print"of the $SEASON_NAME Season.\n\n"; print"Would you like to start a new season? (y or n) ==> "; my $answer = ; chomp $answer; if ($answer eq 'y' || $answer eq 'Y'){ # Make sure season name is in dir. formatt then save season. my $snme = $SEASON_NAME; $snme =~ s/ //g; saveSeason($snme); $PLAYOFF_MODE = 0; startSeason(); }elsif($answer eq 'n' || $answer eq 'N'){ print "Ok, fine\n" }else{ print "Your answer '$answer' dosent make sense\n"; } prompt_clear(1); } elsif($PLAYOFF_MODE){ my @tdb = openFileWIgnore(TEAMS_DB, FREE_AGENT, 0); my $lines = ""; my $lines2 = ""; my @line = (); my $tout = ""; foreach my $lines (@tdb){ if($DBUG){debug ($d, "RUN GAMES: Lines = $lines\n");} my @line = split (/,/, $lines); if($DBUG){debug ($d, "RUN GAMES: line array = @line\n");} if ($line[5] > (($ROUND*4)-1)){ $tout = $line[0]; foreach my $lines2 (@schedule){ if ($lines2 =~ m/$tout/g){ $lines2 = ""; } } } } saveStats(SCHED_DAT, @schedule); updateNavHeader("pgm"); } else { my $top_o_array = shift(@schedule); push(@schedule, $top_o_array); saveStats(SCHED_DAT, @schedule); } if($DBUG){debug ($d, "RUN GAMES: END\n");} } ############### trade ################################################# # Trades players in the league. # # INPUT: none # # OUTPUT: changed files and an html page. # # DEPEND: openFile, prompt_clear, saveStats, teamsAvailable, # checkteam, teamsArray, printPlayersAvailable, # doesPlayerExist, updateTradesWebPage, openFileWIgnore, # debug, tabber, reinsertPlayer, makeTeamNameHash, # checkDir. # # SAMPLE CALL: trade(); ######################################################################## sub trade { my @player_db = openFile(PLAYERS_DB); #Data Base Files my @goalie_db = openFile(GOALIES_DB); #Data Base Files my @player_ss = openFile(SEASON_P_DB);#Season Stats Files my @goalie_ss = openFile(SEASON_G_DB);#Season Stats Files my $team = EMPTY; #For interaction my $flag = FALSE; #flags that a trade finish my $answer = EMPTY; #For interaction my $p_db; my $g_db; my $p_ss; my $g_ss; ######################################################################## sub fudgepacker { my ($f, $tm, $pdb, $gdb, $pss, $gss) = @_; my $player = EMPTY; #For interaction my $trade_to = EMPTY; #For interaction my @playerdatabase = @$pdb; my @goaliedatabase = @$gdb; my @playerseasonbase = @$pss; my @goalieseasonbase = @$gss; while(1){ prompt_clear(0); printPlayersAvailable($tm); print "\nWhat is the players name --> "; $player = ; chomp $player; if ($DBUG) { print"player = $player\n"; print"pdb = $#playerdatabase\n"; print"gdb(#) = $#goaliedatabase\n"; } if ((doesPlayerExist($player, @playerdatabase)) ||(doesPlayerExist($player, @goaliedatabase))){ while(1){ prompt_clear(0); teamsAvailable(); print "\nWhat team is $player going to --> "; $trade_to = ; chomp $trade_to; if (checkTeam($trade_to, (teamsArray("___")))){ ### THE ACTUAL TRADE ############################# sub checkThese{ my ($tem, $plr, $tt, @argument) = @_; my @p = (); # For each line below my $ps = ""; # For the lines below foreach my $ps (@argument){ chomp $ps; @p = split(/,/, $ps); if ($p[0] eq $plr && $p[1] eq $tem){ $ps = reinsertPlayer($ps, $tt, 1); } $ps = "$ps\n"; } return @argument; } @playerdatabase = checkThese($tm, $player, $trade_to, @playerdatabase); @goaliedatabase = checkThese($tm, $player, $trade_to, @goaliedatabase); @playerseasonbase = checkThese($tm, $player, $trade_to, @playerseasonbase); @goalieseasonbase = checkThese($tm, $player, $trade_to, @goalieseasonbase); updateTradesWebPage($player, $tm, $trade_to); ################################################## #prompt_clear(1); $f = TRUE; return($f, $tm, \@playerdatabase, \@goaliedatabase, \@playerseasonbase, \@goalieseasonbase);#TO THE OUTSIDE print "\n$trade_to does not exist!\n"; prompt_clear(1); } } } else { print "\n$player does not exist!\n"; prompt_clear(1); } } } ######################################################################## while(1){ prompt_clear(0); if($flag){ print "\nDo you want to trade another (y or n) --> "; $answer = ; chomp $answer; if ($answer ne 'y'){ print "\nDo you want to save your trades (y or n) --> "; $answer = ; chomp $answer; if ($answer eq 'y'){ saveStats(PLAYERS_DB, @player_db); #Data Base Files saveStats(GOALIES_DB, @goalie_db); #Data Base Files saveStats(SEASON_P_DB, @player_ss); #Season Stats Files saveStats(SEASON_G_DB, @goalie_ss); #Season Stats Files #update the teams web pages my %teams = makeTeamNameHash(); # Each team and their name delete $teams{FREE_AGENT}; foreach my $t (keys %teams){updateTeamHTML($t);} last; } else { last; } } } prompt_clear(0); teamsAvailable(); print "\nWhat is the team the player plays on --> "; $team= ; chomp $team; if (checkTeam($team, (teamsArray("___")))){ if ($DBUG) { my ($package, $filename, $line) = caller; print"-------- TRADE: ------------\n"; print"package = $package\n"; print"filename = $filename\n"; print"line = $line\n"; print"-----------------------------\n"; print"flag = $flag\n"; print"team = $team\n"; print"player_d(#) = $#player_db\n"; print"goalie_db(#) = $#goalie_db\n"; print"player_ss(#) = $#player_ss\n"; print"goalie_ss(#) = $#goalie_ss\n"; } ($flag, $team, $p_db, $g_db, $p_ss, $g_ss) = fudgepacker($flag, $team, \@player_db, \@goalie_db, \@player_ss, \@goalie_ss); @player_db = @$p_db; @goalie_db = @$g_db; @player_ss = @$p_ss; @goalie_ss = @$g_ss; if ($DBUG) { print"\nAFTER FUDGEPACKER:\n"; print"flag = $flag\n"; print"team = $team\n"; print"player_d(#) = $#player_db\n"; print"goalie_db(#) = $#goalie_db\n"; print"player_ss(#) = $#player_ss\n"; print"goalie_ss(#) = $#goalie_ss\n"; } } else { print "\n$team does not exist!\n"; prompt_clear(1); } } } ############### M A K E T R A D E H T M L ######################## # Makes a fresh trade page. # # INPUT: none # # OUTPUT: An html page. # # DEPEND: # # SAMPLE CALL: makeTradeHtml(); ######################################################################## sub makeTradeHtml{ my $dir = ""; my $context = ""; checkDir(SEASON_DIR); my $file = SEASON_DIR."/trade.html"; my @buffer = (); my $tag = ""; $buffer[0] = ''."$SEASON_NAME".' Trades'. '

    '."$SEASON_NAME". ' Trades

    '."\n"; $buffer[1] = $tag; $buffer[2] = "\n
    "; saveStats($file, @buffer); } ############### U P D A T E T R A D E P A G E ##################### # Updates the trade web page. # # INPUT: string (player) # string (from) # # # OUTPUT: file # # DEPEND: makeTeamNameHash(); # getDate(); # openFile($html_file); # saveStats($html_file, @file_lines); # # SAMPLE CALL: updateTradesWebPage($player_name, # $from_team_abr, # $to_team_abr); ######################################################################## sub updateTradesWebPage { my ($player_name, $from_team_abr, $to_team_abr) = @_; ## Set the variables my %teams = makeTeamNameHash(); my $from_team_name = $teams{$from_team_abr}; my $to_team_name = $teams{$to_team_abr}; checkDir(SEASON_DIR); my $html_file = SEASON_DIR."/trade.html"; my @date = getDate(); # For dates my $today = "$date[0]/$date[1]/$date[2]"; my $tag = ""; my @file_lines = openFile($html_file); my $file_line = ""; my $new_file_line = ""; if ($from_team_abr ne FREE_AGENT && $to_team_abr ne FREE_AGENT){ ############################ H T M L ################################## $new_file_line = "\n".' '."\n".# ' '."$today".' '."\n".# '  '."$player_name".''."\n".# ' '." traded from ".'' ."\n".# ' '."$from_team_name ".' '."\n".# ' '." to ". ' '."\n".# ' '."$to_team_name".' '."\n".# ' '; # ############################ H T M L ################################## } elsif ($from_team_abr eq FREE_AGENT) { ############################ H T M L ################################## $new_file_line = "\n".' '."\n".# ' '."$today".' '."\n".# '  '."$player_name".''."\n".# ' '." signed from ".'' ."\n".# ' '."free agency ".' '."\n".# ' '." to ". ' '."\n".# ' '."$to_team_name".' '."\n".# ' '; # ############################ H T M L ################################## } else { ############################ H T M L ################################## $new_file_line = "\n".' '."\n".# ' '."$today".' '."\n".# '  '."$player_name".''."\n".# ' '." released to ".'' ."\n".# ' '."free agency ".' '."\n".# ' '." from ". ' '."\n".# ' '." $from_team_name".' '."\n".# ' '; # ############################ H T M L ################################## } foreach my $file_line (@file_lines){ if ($file_line =~ m/$tag/g){ $file_line = $new_file_line . "\n$tag\n"; } } saveStats($html_file, @file_lines); } ############### a r r a y s o r t e r ################################ # Sorts a season db file. # # INPUT: integer (index of the db to be sorted) # integer (pre sort index, in case of ties) # character(delimiter); # array (db) # # OUTPUT: array (sorted by index) # # DEPEND: none # # SAMPLE CALL: arraySorter(2, 1, $delimiter, @file_contents); ######################################################################## sub arraySorter { my ($i, $si, $delimiter, @array) = @_; my @sorted = (); my $largest = 0; my $this = 0; ## Find the largest to start with. print"Pre Sorter, find the largest to start with.\n"; foreach my $element (@array){ my @line = split ($delimiter, $element); $this = $line[$si]; $this = int($this * 100); if($this > $largest){ $largest = $this; } } ## Start with the largest and work down print"Pre Sorter, start with the largest and work down.\n"; for (my $j = $largest; $j >= 0; $j--){ foreach my $element (@array){ my @line = split ($delimiter, $element); $this = $line[$si]; $this = int($this * 100); if ($this == $j){ push(@sorted, $element); } } } # PRE #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # POST $largest = 0; $this = 0; my @final_sorted = (); ## Find the largest to start with. print"Post Sorter, find the largest to start with.\n"; foreach my $element (@sorted){ my @line = split ($delimiter, $element); $this = $line[$i]; $this = int($this * 100); if($this > $largest){ $largest = $this; } } ## Start with the largest and work down print"Post Sorter, start with the largest and work down.\n"; for (my $j = $largest; $j >= 0; $j--){ foreach my $element (@sorted){ my @line = split ($delimiter, $element); if(@line >= $i){ $this = $line[$i]; $this = int($this * 100); if ($this == $j){ push(@final_sorted, $element); } } else{ print "\nERROR: in sorter: array is not $i big!\n"; } } } return @final_sorted; } # M A K E S T A N D I N G S F I L E ############################# # standings file. If the config fil does not cantain he conference # an division names then the user is prompted and the config file # constructed. # # IN, none # # OUT, a formatted html file # # SUBROUTINES NEEDED, openFile($file); # # EXAMPLE, makeStandingsFile(); ####################################################################### sub makeStandingsFile { #################################################################### # To make the html page header #################################################################### sub makeStandingsHeadHtml{ my $context = ""; my $file = ""; my @buffer = (); my $tag = ""; if ($PLAYOFF_MODE){ checkDir(PLAYOFF_DIR); $file = PLAYOFF_DIR."/standings.html"; $context = "Playoffs"; } else { checkDir(SEASON_DIR); $file = SEASON_DIR."/standings.html"; $context = "Season"; } ###################### H T M L ################################### $buffer[0] = "$context Standings". # '

    '."$SEASON_NAME ". # "$context Standings


    \n"; # $buffer[1] = $tag; # $buffer[2] = "\n"; # ###################### H T M L ################################### saveStats($file, @buffer); } ##################################################################### ##################################################################### # To make the html conference header #################################################################### sub makeStandingsConfHtml{ my ($conference) = @_; my $file = ""; if ($PLAYOFF_MODE){ checkDir(PLAYOFF_DIR); $file = PLAYOFF_DIR."/standings.html"; } else { checkDir(SEASON_DIR); $file = SEASON_DIR."/standings.html"; } my @file_lines = openFile($file); my $new_file_line = ""; my $tag = ""; ###################### H T M L ################################## $new_file_line = "

    $conference

    "; # ##################### H T M L ################################### foreach my $file_line (@file_lines){ if ($file_line =~ m/$tag/g){ $file_line = $new_file_line . "\n$tag\n"; } } saveStats($file, @file_lines); } #################################################################### ##################################################################### # To make the html division header #################################################################### sub makeStandingsDivHtml{ my ($div) = @_; my $file = ""; if ($PLAYOFF_MODE){ checkDir(PLAYOFF_DIR); $file = PLAYOFF_DIR."/standings.html"; } else { checkDir(SEASON_DIR); $file = SEASON_DIR."/standings.html"; } my @file_lines = openFile($file); my $new_file_line = ""; my $tag = ""; ###################### H T M L ################################## $new_file_line = "

    $div

    '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ''."\n"; # ##################### H T M L ################################## foreach my $file_line (@file_lines){ if ($file_line =~ m/$tag/g){ $file_line = $new_file_line . "\n$tag\n"; } } saveStats($file, @file_lines); } #################################################################### ##################################################################### # To make the html stats lines #################################################################### sub makeStandingsLineHtml{ my ($rank, @stats) = @_; my $file = ""; if ($PLAYOFF_MODE){ checkDir(PLAYOFF_DIR); $file = PLAYOFF_DIR."/standings.html"; } else { checkDir(SEASON_DIR); $file = SEASON_DIR."/standings.html"; } my @file_lines = openFile($file); my $new_file_line = ""; my $tag = ""; ###################### H T M L ################################## $new_file_line = ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ' '."\n".# ''."\n"; # ##################### H T M L ################################## foreach my $file_line (@file_lines){ if ($file_line =~ m/$tag/g){ $file_line = $new_file_line . "\n$tag\n"; } } saveStats($file, @file_lines); } ################################################################### #################################################################### # To make the html stats lines finish (insert html flag to end table #################################################################### sub makeEndDivisionHtml{ my $file = ""; if ($PLAYOFF_MODE){ checkDir(PLAYOFF_DIR); $file = PLAYOFF_DIR."/standings.html"; } else { checkDir(SEASON_DIR); $file = SEASON_DIR."/standings.html"; } my @file_lines = openFile($file); my $tag = ""; foreach my $file_line (@file_lines){ if ($file_line =~ m/$tag/g){ $file_line = "
    '."G".''."W".''."L". ''."T".''."Pts".''."W%". ''."GF".''."GA".''."PPG". ''."PPM".''."PP%".''."PM". ''."PK%". '
    '."$rank".''."$stats[1]".''."$stats[4]".''."$stats[5]".''."$stats[6]". ''."$stats[7]".''."$stats[8]".''."$stats[9]". ''."$stats[10]".''."$stats[11]".''."$stats[12]". ''."$stats[13]".''."$stats[14]".''."$stats[15]". ''."$stats[16]". '
    \n$tag\n"; } } saveStats($file, @file_lines); } ####################################################################### # V A R I A B L E S S E C T I O N ####################################################################### my @config_file = openFile(TEAMS_DB); my @line = (); my $team = ""; #in the config file my %teams = makeTeamNameHash();#Just initialize cnf file my $conference = ""; #to hold conf. value my $division = ""; #to hold div. value my @conferences = ""; #conferences stack my %seen_conferences = (); #holding all the c's my %seen_divisions = (); #holding all the d's my $temp = ""; #to hold all teams inconf my $hashed = ""; #foreach valuein hash my $new_seson_flag = 0 ; my @confs; my $num_confs; ############################ M ################################## ############################ A ################################## ############################ I ################################## ############################ N ################################## # Read in $config_file_lines from the config. file foreach my $config_file_line (@config_file){ chomp $config_file_line; @line = split(/,/, $config_file_line); if ($line[0] ne FREE_AGENT){ # Dont include free agents! $team = $line[1]; if (@line < 3){ $config_file_line = "$line[0],$line[1],,,0,0,0,0,0,0,0,0,0,0,0,0,0\n"; $new_seson_flag = 1; } else { # Get the conferences/div as keys in a hash $conference = $line[2]; # if there is no division then we will temporaraly assign the # same name as the conference for standings file set up # purposes. if ($line[3] eq ''){ $division = $line[2]; $line[3] = $line[2]; }else{ $division = $line[3]; } } } $seen_conferences{$conference}=""; $seen_divisions{$division}=""; $config_file_line = join (',', @line); $config_file_line = "$config_file_line\n"; } @confs = keys %seen_conferences; $num_confs = @confs; saveStats(TEAMS_DB, @config_file); if ($new_seson_flag){}else{ # Make a templist and fill it with all divisions in n conferece foreach my $hashed (keys %seen_conferences){ $temp = ""; foreach my $config_file_line (@config_file){ my @line = split(/,/, $config_file_line); if ($line[0] ne FREE_AGENT){ # Dont include free agents! if ($hashed eq $line[2]){ $temp = "$temp,$line[1]"; } } } $seen_conferences{$hashed}=$temp; } # Make a templist and fill it with all teams in n divisions foreach my $hashed (keys %seen_divisions){ $temp = ""; foreach my $config_file_line (@config_file){ my @line = split(/,/, $config_file_line); if ($line[0] ne FREE_AGENT){ # Dont include free agents! if ($hashed eq $line[3]){ $temp = "$temp,$line[1]"; } } } $seen_divisions{$hashed}=$temp; } #Make a hash of divisions and as their key what conf. they belong my %divs = %seen_divisions; foreach my $config_file_line (@config_file){ my @line = split(/,/, $config_file_line); if ($line[0] ne FREE_AGENT){ # Dont include free agents! foreach my $hashed (keys %divs) { if ($hashed eq $line[3]){ $divs{$hashed} = $line[2]; } } } } makeStandingsHeadHtml(); if ($num_confs <= 1){ foreach my $division (keys %seen_divisions){ # Leave out if there are no Divisions if ($division eq $conference){ makeStandingsDivHtml(""); }else{ makeStandingsDivHtml($division); } my @this_div_ts = split (/,/, $seen_divisions{$division}); my @temp; foreach my $team (@this_div_ts){ foreach my $line (@config_file){ my @cfg_line = split (/,/, $line); if ($cfg_line[0] ne FREE_AGENT){ # No fre agnts if ($cfg_line[1] eq $team && $cfg_line[3] eq $division){ push (@temp, $line); } } } } @temp = arraySorter(8, 10, ',', @temp); my $rank = 1; my $div_flag; foreach my $line (@temp){ my @this_line = split (/,/, $line); makeStandingsLineHtml($rank, @this_line); $rank++; $div_flag = 1; } if ($div_flag){makeEndDivisionHtml();} } }else{ #Make the page looping through the conference then the divisions foreach my $conference (keys %seen_conferences){ # CONFERENCE makeStandingsConfHtml($conference); my $div_flag = 0; my @temp = (); foreach my $division (keys %seen_divisions){ # DIVISION if ($divs{$division} eq $conference){ # Leave out if there are no Divisions if ($division eq $conference){ makeStandingsDivHtml(""); }else{ makeStandingsDivHtml($division); } my @this_div_ts = split (/,/, $seen_divisions{$division}); foreach my $team (@this_div_ts){ foreach my $line (@config_file){ my @cfg_line = split (/,/, $line); if ($cfg_line[0] ne FREE_AGENT){ # No fre agnts if ($cfg_line[1] eq $team && $cfg_line[3] eq $division){ push (@temp, $line); } } } } @temp = arraySorter(8, 10, ',', @temp); my $rank = 1; foreach my $line (@temp){ my @this_line = split (/,/, $line); makeStandingsLineHtml($rank, @this_line); $rank++; $div_flag = 1; } if ($div_flag){makeEndDivisionHtml();} } } # END DIVISION } # END CONFERENCE } } saveStats(TEAMS_DB, @config_file); } ####################################################################### # U P D A T E T E A M S T A N D I N G S ######################### # Open team dbase file and add to it the game results to provide stats # # IN, none # # OUT, a formatted html file # # SUBROUTINES NEEDED, openFile($file); # # EXAMPLE, updateTeamDB(@results); ####################################################################### sub updateTeamDB { my (@results) = @_; # results. my @teams_db_a = openFile(TEAMS_DB); # teamssdb.csv my @team_stats = (); # each line stats my $hfs = $results[0] + $results[1] + $results[2] + $results[3]; my $afs = $results[4] + $results[5] + $results[6] + $results[7]; my $hs = $results[12] + $results[13] + $results[14] + $results[15]; my $as = $results[16] + $results[17] + $results[18] + $results[19]; ## Do the teams file foreach my $team (@teams_db_a){ # foreach db line chomp $team; @team_stats = split (/,/, $team); # split into arry if ($team_stats[1] eq $results[28] && $team_stats[0] ne FREE_AGENT){ # HOME # Games $team_stats[4]++; # Wins if ($hfs > $afs){ $team_stats[5]++; } elsif ($hfs < $afs){ $team_stats[6]++; } else { $team_stats[7]++; } # Points $team_stats[8] = (($team_stats[5]*2)+$team_stats[7]); # Win Percentage $team_stats[9] = rounder(($team_stats[5]/$team_stats[4]), 2); # Goals For $team_stats[10] = $hfs + $team_stats[10]; # Goals Against $team_stats[11] = $afs + $team_stats[11]; # Power Play Goals $team_stats[12] = $team_stats[12] + $results[20]; # Power Play Minutes $team_stats[13] = $team_stats[13] + $results[25]; # Power Play Percentage if($team_stats[13] > 0){ $team_stats[14] = rounder((($team_stats[12] + (int(rand(5)))) /$team_stats[13]), 2); } # Penalty Minutes $team_stats[15] = $team_stats[15] + $results[24]; # Penalty Kill Percentage if($results[25] > 0){ $team_stats[16] = rounder((($results[21] + (int(rand(5)))) /$results[25]), 2); } } elsif ($team_stats[1] eq $results[29] && $team_stats[0] ne FREE_AGENT){ # AWAY # Games $team_stats[4]++; # Wins if ($hfs < $afs){ $team_stats[5]++; } elsif ($hfs > $afs){ $team_stats[6]++; } else { $team_stats[7]++; } # Points $team_stats[8] = (($team_stats[5]*2)+$team_stats[7]); # Win Percentage $team_stats[9] = rounder(($team_stats[5]/$team_stats[4]), 2); # Goals For $team_stats[10] = $afs + $team_stats[10]; # Goals Against $team_stats[11] = $hfs + $team_stats[11]; # Power Play Goals $team_stats[12] = $team_stats[12] + $results[21]; # Power Play Minutes $team_stats[13] = $team_stats[13] + $results[24]; # Power Play Percentage if($results[25] > 0){ $team_stats[14] = rounder((($results[21] + (int(rand(5)))) /$results[25]), 2); } # Penalty Minutes $team_stats[15] = $team_stats[15] + $results[25]; # Penalty Kill Percentage if($team_stats[13] > 0){ $team_stats[16] = rounder((($team_stats[12] + (int(rand(5)))) /$team_stats[13]), 2); } } $team = join (',', @team_stats); # join back up $team = $team . "\n"; } saveStats(TEAMS_DB, @teams_db_a); } ############### R E S E T S T A N D I N G S D B ################### # Resets the teamdb.csv file. # # INPUT: none # # # OUTPUT: file # # DEPEND: # # SAMPLE CALL: resetStandDB(); ######################################################################## sub resetStandDB { my @config_file = openFile(TEAMS_DB); my $END = 16; # End of ints in db file. foreach my $line (@config_file){ chomp $line; my @values = split (/,/, $line); if ($values[0] ne FREE_AGENT){ # No fre agnts for (my $i = 4; $i <= $END; $i++){ $values[$i]= 0; } } $line = join (',', @values); $line = "$line\n"; } saveStats(TEAMS_DB, @config_file); } ############### SET UP PLAYOFFS SCHEDULE ############################# # Set up a playoff schedule. # # INPUT: none # # OUTPUT: playoff_sched.dat # # DEPEND: openFile(TEAMS_DB); # looper(2,0); Which is internal!! # # SAMPLE CALL: setUpPlayoffsSchedule(); ####################################################################### sub setUpPlayoffsSchedule { my %seen_confs = ();# Hash of conferences and their teams. # Sort the teamsdb.csv file my @teamsdb = openFileWIgnore(TEAMS_DB, FREE_AGENT, 0); @teamsdb = arraySorter(8, 10, ',', @teamsdb); # Find out how many teams in the league. my $tms_i_lg = @teamsdb; # Find out the number 'n' of teams to involve in the playoffs my $n = 0; # teams going to the playoffs my $two_power = 1; # two to the power of loop iritiation for (my $i = 1; $two_power <= $tms_i_lg; $i++){ $n = $two_power; $two_power = 2**$i; } # Lets check for not enough teams. if ($n < 2){ my $problem = "Not enough teams"; (my $package, my $filename, my $line) = caller; print"\n$filename:subroutine $package,$problem,line $line\n"; prompt_clear(1); return 1; } # Set n to reflect array indexes. Keep n in a safe place. $n--; # Make a hash of conferences. foreach my $teamsdb_line (@teamsdb){ my @line = split(/,/, $teamsdb_line); if (@line < 3){ my $problem = "Db file not set up right"; (my $package, my $filename, my $line) = caller; print"\n$filename:subroutine $package,$problem,line $line\n"; prompt_clear(1); return 1; } # Get the conf as keys in a hash $seen_confs{$line[2]}=""; } # Make a hash that has conferences in the key and the playoff teams # delimited with ',' as the values. foreach my $hashed (keys %seen_confs){ my $temp = ""; foreach my $teamsdb_line (@teamsdb){ my @line = split(/,/, $teamsdb_line); if ($hashed eq $line[2]){ $temp = "$temp,$line[0]"; } } $seen_confs{$hashed}=$temp; } # L O O P E R ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ sub looper { # uses varables global to outer sub!!! #~ my ($hg, $f, $n, $confs, @a) = @_; #~ my $reset = $n; #~ my %seen_confs = %$confs; #~ # Loop through the conferences and make games at home. #~ for (my $i = $hg; $i > 0; $i--){ #~ for (my $s = 0; $s <= $n; $s++){ #~ foreach my $conf (keys %seen_confs){ #~ my @c = split (/,/, $seen_confs{$conf}); #~ my $garbage = shift (@c); #~ push (@a, "$c[$s],$c[$n]\n"); #~ } #~ $n--; #~ } #~ $n = $reset; #~ } #~ #~ if($f){ #~ # Loop through the conferences and make games at away. #~ for (my $i = $hg; $i > 0; $i--){ #~ for (my $s = 0; $s <= $n; $s++){ #~ foreach my $conf (keys %seen_confs){ #~ my @c = split (/,/, $seen_confs{$conf}); #~ my $garbage = shift (@c); #~ push (@a, "$c[$n],$c[$s]\n"); #~ } #~ $n--; #~ } #~ $n = $reset; #~ } #~ } #~ return @a; #~ } #~ # L O O P E R ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Loop through the conferences and make 2 games at home then away. my $confs = \%seen_confs; # Create a reference my @out = (); @out = looper(2,1, $n, $confs, @out); # Loop through the conferences and make 1 game at home then away. @out = looper(1,1, $n, $confs, @out); # Loop through the conferences and make 1 game at home (7th game). @out = looper(1,0, $n, $confs, @out); saveStats(SCHED_DAT, @out); } ############### SET UP PLAYOFFS ###################################### # Set up playoffs. # # INPUT: none # # OUTPUT: none # # DEPEND: startSeason(); # setUpPlayoffsSchedule(); # makeSchedule(); # makePlayerHtmlStats(); # makeGoalieHtmlStats(); # resetStandDB(); # makeStandingsFile(); # # SAMPLE CALL: setUpPlayoffs(); ######################################################################## sub setUpPlayoffs { print"startSeason\n"; startSeason(); print"setUpPlayoffsSchedule\n"; setUpPlayoffsSchedule(); print"makeSchedule\n"; makeSchedule(); print"makePlayerHtmlStats\n"; makePlayerHtmlStats(); print"makeGoalieHtmlStats\n"; makeGoalieHtmlStats(); print"resetStandDB\n"; resetStandDB(); print"makeStandingsFile\n"; print"Getting a team array to set up team pages.\n"; my @teams=teamsArray(FREE_AGENT); print"Seing up team pages.\n"; foreach my $team (@teams){ print"Setting up $team\n"; updateTeamHTML($team); } makeStandingsFile(); print"setMode\n"; setMode('OT', 2); prompt_clear(1); } ############ SET UP PLAYOFFS ######################################## ############### SET UP SIM.CFG ###################################### # Set up the sim.cfg file. # # INPUT: none # # OUTPUT: sim.cfg # # DEPEND: saveStats(file, array); # # SAMPLE CALL: setUpSimCfg(); ######################################################################## sub setUpSimCfg { my $file_contents = ""; my $answer = ""; open(FILEC, CONFIG_FILE) || ( my $badflag = 1); close (FILEC); if ($badflag){ print "\nWhat is the Name of this league ==> ";#<==Put all my $lname = ; chomp $lname; #startup stuff print "\nWhat is the Name of this season ==> ";#for the config my $sname = ; chomp $sname; #file here. print "\nWhat browser is installed on your system?\n". "Type 'e' for Microsoft Explorer or 'n' for ". "Netscape Navagator == > "; my $bname = ; chomp $bname; if ($bname eq 'n'){ $bname = "netscape"; } elsif ($bname eq 'e'){ $bname = "explorer"; } else { print "Bad input, going with Explorer....\n"; $bname = "explorer"; } $file_contents = "PLAYOFF_MODE,0\n". "SEASON_NAME,$sname\n". "LEAGUE_NAME,$lname\n". "BROWSER,$bname\n". "OT,1\n". "SEASON_NUM,1\n"; } else { $file_contents = "PLAYOFF_MODE,$PLAYOFF_MODE\n". "SEASON_NAME,$SEASON_NAME\n". "LEAGUE_NAME,$LEAGUE_NAME\n". "BROWSER,$BROWSER\n". "OT,$OT\n". "SEASON_NUM,$SEASON_NUM\n"; } saveStats(CONFIG_FILE, $file_contents); } ############### U P D A T E N A V H E A D E R #################### # Updates the navagator header web page. # # INPUT: string (update type # [rgm] => regular season games # [rtd] => regular season trades # [pfs] => playoffs # [pgm] => playoffs games) # # # OUTPUT: html file # # DEPEND: openFile($html_file); # saveStats($html_file, @file_lines); # prompt_clear(1); # # SAMPLE CALL: updateNavHeader($type_flag); ######################################################################## sub updateNavHeader { my ($update_type) = @_; ## Set the variables my $html_file = "nav_bar.html"; my $tag = ""; $ps = "|"; $link = "season/games/index.html"; $lable = "Games"; } elsif ($update_type eq "rtd"){ $flag = "$tag trades-->"; $ps = "|"; $link = "season/trade.html"; $lable = "Trades"; } elsif ($update_type eq "pfs"){ $flag = "$tag playoffs-->"; $ps = "
    "; $link = "playoffs/schedule.html"; $lable = "Playoff Schedule"; $oc = ' |'."Playoff Standings".''."\n". ' |'."Playoff Stats".''."\n". ' |'."Playoff Goalie Stats".''."\n"; } elsif ($update_type eq "pgm"){ $flag = "$tag playoffgames-->"; $ps = "|"; $link = "playoffs/games/index.html"; $lable = "Playoff Games"; } else { my $problem = "$update_type is not defined"; (my $package, my $filename, my $line) = caller; print"\n$filename:subroutine $package,$problem,line $line\n"; prompt_clear(1); return 1; } ######################### H T M L ################################## my $new_file_line = "$ps".' '."$lable".''."\n$oc"; # ######################### H T M L ################################## foreach my $file_line (@file_lines){ if ($file_line =~ m/$flag/g){ $file_line = $new_file_line; } } saveStats($html_file, @file_lines); } ############### U P D A T E N A V H E A D E R #################### ############### M A K E N A V H E A D E R ######################## # Constructs the navagator header web page. # # INPUT: none # # # OUTPUT: html file # # DEPEND: saveStats($html_file, @file_lines); # # SAMPLE CALL: makeNavHeader(); ######################################################################## sub makeNavHeader { my $font = ''; my $pre_head = '

    '."$font"; my $post_head = '

    '; my $nbsp = '  '; my $html_file = '.html'; my $pre_ahref = ''."$font"; my $post1_ahref = ''."$font"; my $post2_ahref = ''; my $game_tag = ''; my $trade_tag = ''; my $p_off_tag = ''; my $p_o_g_tag = ''; my $end = '
    '; my $buffer = 'Navagation Bar'."\n". ''."\n". "$pre_head $LEAGUE_NAME $post_head\n". "$pre_ahref"."season/schedule$html_file$mid_ahref Schedule". " $post1_ahref\n". "$game_tag\n". " | $pre_ahref"."season/standings$html_file$mid_ahref Standings". " $post2_ahref\n" . " | $pre_ahref"."season/player_stats$html_file$mid_ahref ". "Player Stats $post2_ahref\n" . " | $pre_ahref"."season/goalie_stats$html_file$mid_ahref ". "Goalie Stats $post2_ahref\n" . "$trade_tag\n$p_off_tag\n$p_o_g_tag\n$end"; saveStats("nav_bar.html", $buffer); } ############### M A K E N A V H E A D E R ######################## ############### M A K E L E A G U E N A V A G A T O R ############ # Makes the League Navigator Web Page. # # INPUT: none # # # OUTPUT: html file # # DEPEND: saveStats($html_file, @file_lines); # # SAMPLE CALL: makeLeagueNavagator(); ######################################################################## sub makeLeagueNavagator { my $buffer = ''. 'Current Navagator'."\n". ''."\n". ''."\n". ''."\n". ''."\n". ''. '<BODY>'."\n". "Dude, you need a frame inabled browser\n". '</BODY>'; saveStats("main.html", $buffer); my $buffer2 ="League Navagator\n". ''."\n". ''."\n". ''."\n". '<BODY>'."\n". 'Viewing this page requires a browser capable of displaying frames.'. "\n". '</BODY>'; saveStats("index.html", $buffer2); my $pre = ''."\n". "$nbs$nbs$nbs$pr_h"."Seasons"."$po_h". "$pre$main$post$l$oc\n". ''."\n". "$nbs$pr_h"."Teams"."$po_h\n". ''."\n". ''."\n". ''; saveStats("season_bar.html", $buffer3); } addTeamsToHtml(); } ############### M A K E L E A G U E N A V A G A T O R ############ ############### S E T M O D E ######################################### # Sets a constant in the config file. # # INPUT: string (constant name) # string or int (valut to change to); # # OUTPUT: array (results) # # DEPEND: openFile(SCHED_DAT); # saveStats(CONFIG_FILE, @configuration); # # SAMPLE CALL: setMode("PLAYOFF_MODE", 1); ######################################################################## sub setMode{ my ($label, $value) = @_; my @configuration = openFile(CONFIG_FILE); foreach my $config (@configuration){ my @config_array = split(/,/, $config); if ($config_array[0] eq $label){ $config_array[1] = $value; } $config = join(',', @config_array); $config = "$config\n"; } saveStats(CONFIG_FILE, @configuration); } ############### r u n g a m e s ##################################### ############### P R I N T L E A D E R ################################ # Gets and returns to the screen the winner or leader at the moment. # This sub program can be expanded to return an array of the leaders # stats. # # INPUT: # # OUTPUT: string (winner or leader); # arraySorter(5, ',', @file); # # DEPEND: @file = openFile(SEASON_DIR); # # SAMPLE CALL: $winner = printLeader(); ######################################################################## sub printLeader{ my @file = openFileWIgnore(TEAMS_DB, FREE_AGENT, 0); arraySorter(8, 10, ',', @file); my $winner_line = $file[0]; my @winner_array = split(/,/, $winner_line); return $winner_array[1]; } ############### P R I N T L E A D E R ################################ ############### S A V E S E A S O N ################################# # Puts Season, Playpoffs, and Backup foulders into the season named dir. # # INPUT: string (foulder name); # # OUTPUT: foulder (containing season elements) # # DEPEND: @file = openFile(SEASON_DIR); # # SAMPLE CALL: saveSeason($season_name); ######################################################################## sub saveSeason{ my ($folder) = @_; my $f = 0; ################################################################## sub change{ my ($dir, $f) = @_; my $file = ""; my @this_file = (); mkdir("$f/$dir", 0755) || die ": can not make $f/$dir!"; opendir(DIRR, $dir); while (defined($file = readdir(DIRR))){ if (($file ne "games") && ($file ne ".") && ($file ne "..")){ @this_file = openFile("$dir/$file"); saveStats("$f/$dir/$file", @this_file); } } close(DIRR); } ################################################################## mkdir($folder, 0755) || print "mkdir in saveSeason didnt make"; change(SEASON_DIR, $folder); change(SEASON_DIR . "/games", $folder); change(PLAYOFF_DIR, $folder); change(PLAYOFF_DIR . "/games", $folder); change("backups", $folder); my @this_file = openFile("main.html"); saveStats("$folder/index.html", @this_file); @this_file = openFile("nav_bar.html"); updateSeasonHeader($folder); saveStats("$folder/nav_bar.html", @this_file); @this_file = openFile("today.html"); saveStats("$folder/today.html", @this_file); print"\nResetting Season Name\n"; print"What will be the new Season's name ==> "; my $name = ; chomp $name; $SEASON_NAME = $name; setMode("SEASON_NAME", $name); } ############### S A V E S E A S O N ################################# ############### U P D A T E S E A S O N S H E A D E R ############## # Updates the navagator header web page. # # INPUT: string (Season name) # # OUTPUT: html file # # DEPEND: openFile($html_file); # saveStats($html_file, @file_lines); # # SAMPLE CALL: updateSeasonHeader($seasn); ######################################################################## sub updateSeasonHeader { my ($season_name) = @_; ## Set the variables my $main = "main.html"; my $html_file = 'season_bar.html'; my $tag = ""; my $tags = ""; my $pre = '

    team name value=>abr my @teamDB_contents = openFile(TEAMS_DB); my @DB_line_content = (); my %teams = (); foreach my $DB_line (@teamDB_contents){ @DB_line_content = split(/,/, $DB_line); $teams{$DB_line_content[1]}=$DB_line_content[0]; } # Search find tag and insert teams. foreach my $file_line (@file_lines){ if ($file_line =~ m/$tage/g){ $erase = FALSE; }elsif ($erase){ $file_line = ''; }elsif ($file_line =~ m/$tagp/g){ $file_line = "$tagp\n"; foreach my $team (keys %teams){ $file_line = "$file_line$pre$teams_folder/$teams{$team}". '.html'. "$post$team$oc\n"; } $erase = TRUE; } } saveStats($html_file, @file_lines); } ############### ST A R T N A V A G A T O R ######################### # Starts a browser with a html file as its argument # # INPUT: string ($file) # # OUTPUT: action # # DEPEND: # # SAMPLE CALL: startNav($htmlfilepath); ######################################################################## sub startNav { my ($file) = @_; if ($BROWSER eq "explorer"){ $file =~ s|/|\\|g; } system("$BROWSER $file"); } ############### ST A R T N A V A G A T O R ######################### ############### P R I N T S T A N D I N G S ######################## # PRINTS LEAGUE STANDINGS TO THE SCREEN. # # INPUT: # # OUTPUT: screen output # # DEPEND: checkDir(PLAYOFF_DIR); # @temp = arraySorter(8, ',', @temp); # makeTeamNameHash # openFile # prompt_clear # # SAMPLE CALL: printStandings(); ######################################################################## sub printStandings { my $context; if ($PLAYOFF_MODE){ $context = "Playoffs"; } else { $context = "Season"; } ##################################################################### # To make the html conference header ##################################################################### sub makeStandingsConf{ my ($conference) = @_; print " $conference \n"; } ##################################################################### # To make the html division header ##################################################################### sub makeStandingsDiv{ my ($div) = @_; print "$div \n"; print "\tW\tL\tT\tP\tGF\tGA\tPM\n"; print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~". "~~\n"; } ##################################################################### # To make the html stats lines ##################################################################### sub makeStandingsLine{ my ($rank, @stats) = @_; print "$rank.$stats[0]\t$stats[5]\t$stats[6]\t$stats[7]\t". "$stats[8]\t$stats[10]\t$stats[11]\t$stats[15]\n"; } #################################################################### # V A R I A B L E S S E C T I O N #################################################################### my @config_file = openFile(TEAMS_DB); my @line = (); my $team = ""; #in the config file my %teams = makeTeamNameHash();#Just initialize cnf file my $conference = ""; #to hold conf. value my $division = ""; #to hold div. value my @conferences = ""; #conferences stack my %seen_conferences = (); #holding all the c's my %seen_divisions = (); #holding all the d's my $temp = ""; #to hold all teams inconf my $hashed = ""; #foreach valuein hash my $new_seson_flag = 0; ############################ M ################################ ############################ A ################################ ############################ I ################################ ############################ N ################################ prompt_clear(0); print " $SEASON_NAME $context Standings \n"; print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; # Read in $config_file_lines from the config. file foreach my $config_file_line (@config_file){ chomp $config_file_line; @line = split(/,/, $config_file_line); if($line[0] ne FREE_AGENT){ $team = $line[1]; if (@line < 3){ print "\nWhat Conference is $team in --> "; $conference = ; chomp $conference; $line[2] = $conference; print "\nWhat Division is $team in --> "; $division = ; chomp $division; $line[3] = "$division,0,0,0,0,0,0,0,0,0,0,0,0,0"; $new_seson_flag = 1; } else { # Get the conferences/div as keys in a hash $conference = $line[2]; $division = $line[3]; } } $config_file_line = join (',', @line); $config_file_line = "$config_file_line\n"; $seen_conferences{$conference}=""; $seen_divisions{$division}=""; } saveStats(TEAMS_DB, @config_file); if ($new_seson_flag){}else{ # Make a templist and fill it with all divisions in n conferece foreach my $hashed (keys %seen_conferences){ $temp = ""; foreach my $config_file_line (@config_file){ @line = split(/,/, $config_file_line); if($line[0] ne FREE_AGENT){ if ($hashed eq $line[2]){ $temp = "$temp,$line[1]"; } } } $seen_conferences{$hashed}=$temp; } # Make a templist and fill it with all teams in n divisions foreach my $hashed (keys %seen_divisions){ $temp = ""; foreach my $config_file_line (@config_file){ my @line = split(/,/, $config_file_line); if($line[0] ne FREE_AGENT){ if ($hashed eq $line[3]){ $temp = "$temp,$line[1]"; } } } $seen_divisions{$hashed}=$temp; } #Make a hash of divisions and as their key what conf. they belong my %divs = %seen_divisions; foreach my $config_file_line (@config_file){ my @line = split(/,/, $config_file_line); if($line[0] ne FREE_AGENT){ foreach my $hashed (keys %divs) { if ($hashed eq $line[3]){ $divs{$hashed} = $line[2]; } } } } #Make the page looping through the conference then the divisions foreach my $conference (keys %seen_conferences){ makeStandingsConf($conference); my $div_flag = 0; foreach my $division (keys %seen_divisions){ if ($divs{$division} eq $conference){ makeStandingsDiv($division); my @this_div_ts = split (/,/, $seen_divisions{$division}); my @temp = (); foreach my $team (@this_div_ts){ foreach my $line (@config_file){ my @cfg_line = split (/,/, $line); if($cfg_line[0] ne FREE_AGENT){ if ($cfg_line[1] eq $team && $cfg_line[3] eq $division){ push (@temp, $line); } } } } @temp = arraySorter(8, 10, ',', @temp); my $rank = 1; foreach my $line (@temp){ my @this_line = split (/,/, $line); makeStandingsLine($rank, @this_line); $rank++; $div_flag = 1; } print"\n"; #if ($div_flag){makeEndDivision();} } } } } } ############### P R I N T S T A N D I N G S ######################## ############### P R I N T S C H E D U L E ########################## # PRINTS schedule to the screen. # # INPUT: # # OUTPUT: screen output # # DEPEND: openFile # prompt_clear # # SAMPLE CALL: printSchedule(); ######################################################################## sub printSchedule { my $foulder = SEASON_DIR; if ($PLAYOFF_MODE){ $foulder = PLAYOFF_DIR; } else { $foulder = SEASON_DIR; } my @filecontents=openFile("$foulder/schedule.html"); my $date = ''; my $awayt = ''; my $homet = ''; my $ascore = ''; my $hscore = ''; my $endtag = ''; my $tab1 = ''; my $tab2 = ''; prompt_clear(0); for(my $i = 0; $i < (@filecontents - 1); $i++){ if ($filecontents[$i] =~ m//g){ $date = $filecontents[$i + 1]; $date =~ s/\n//g; $date =~ s/ //g; my $ignore = ''; $date =~ s/$ignore//g; $date =~ s/$endtag//g; $awayt = $filecontents[$i + 2]; $awayt =~ s/\n//g; $awayt =~ s/ //g; $awayt =~ s/$endtag//g; $homet = $filecontents[$i + 4]; $homet =~ s/\n//g; $homet =~ s/ //g; $homet =~ s/$endtag//g; $ascore = $filecontents[$i + 5]; $ascore =~ s/\n//g; $ascore =~ s/ //g; $ascore =~ s/$endtag//g; $ascore =~ s/ //g; $hscore = $filecontents[$i + 6]; $hscore =~ s/\n//g; $hscore =~ s/ //g; $hscore =~ s/$endtag//g; $hscore =~ s/ //g; $tab1 = tabber($awayt, 25); $tab2 = tabber($homet, 25); print "$date $awayt$tab1 at $homet$tab2$ascore $hscore\n"; } } } ############### P R I N T S C H E D U L E ########################## ############### P R I N T S C O R I N G L E A D E R S ############ # PRINTS the tem scoring leaders to the screen. # # INPUT: # # OUTPUT: screen output # # DEPEND: sorter # prompt_clear # openFile # # SAMPLE CALL: printScoringLeaders(); ######################################################################## sub printScoringLeaders { sorter(2, 11, SEASON_P_DB); my @statsfile = openFile(SEASON_P_DB); my $place = ''; my $line = ''; my @stats = (); my $tab = ""; prompt_clear(0); print" gmes pts goals assists +/- \n"; print"____________________________________________________________\n"; for (my $i = 0; $i < 10; $i++){ $line = $statsfile[$i]; @stats = split(/,/, $line); $place = $i+1; $tab = tabber($stats[0], 20); chomp $stats[13]; print"$place.\t$stats[0]$tab$stats[13]\t$stats[2]\t$stats[11]\t". "$stats[12]\t$stats[3]\t\n"; } } ############### P R I N T S C O R I N G L E A D E R S ############ ############### T A B B E R ##############################S############## # Returns a tab or set of spaces based on the argument; # # INPUT: string (previous argument) # integer (available spaces) # # OUTPUT: string (tab) # # DEPEND: # # SAMPLE CALL: tabber($prev_arg, $spaces); ######################################################################## sub tabber { my ($prev_arg, $avalspaces) = @_; my @chars = split(//, $prev_arg ); my @tab = (); my $garb = ""; my $t = ""; my $char = ""; for (my $i = 0; $i < $avalspaces; $i++){ push(@tab, " "); } foreach my $char (@chars){ $garb = pop(@tab); } foreach my $char (@tab){ $t = "$t " } return $t; } ############### T A B B E R ##############################S############## ############### P R I N T G O A L I E L E A D E R S ################ # PRINTS the goalies save% leaders to the screen. # # INPUT: # # OUTPUT: screen output # # DEPEND: sorter # prompt_clear # openFile # # SAMPLE CALL: printGoalieLeaders(); ######################################################################## sub printGoalieLeaders { my @statsfile = openFile(SEASON_G_DB); @statsfile = arraySorter(2, 4, ',', @statsfile); my $place = ''; my $line = ''; my @stats = (); my $tab = ""; prompt_clear(0); print" gmes Wins Save% GAA Saves \n"; print"____________________________________________________________\n"; for (my $i = 0; $i < 5; $i++){ $line = $statsfile[$i]; @stats = split(/,/, $line); $place = $i+1; $tab = tabber($stats[0], 20); chomp $stats[10]; print"$place.\t$stats[0]$tab$stats[10]\t$stats[4]\t$stats[2]\t". "$stats[9]\t$stats[7]\t\n"; } } ############### P R I N T G O A L I E L E A D E R S ################ ############### P R I N T T R A D E S ################################ # PRINTS trades to the screen. # # INPUT: # # OUTPUT: screen output # # DEPEND: openFile # prompt_clear # # SAMPLE CALL: printTrades(); ######################################################################## sub printTrades { my @filecontents=openFile(SEASON_DIR."/trade.html"); my $date = ''; my $name = ''; my $fname = ''; my $tname = ''; my $endtag = ''; my $tab1 = ''; my $tab2 = ''; my @temp = (); prompt_clear(0); for(my $i = 0; $i < (@filecontents - 1); $i++){ if ($filecontents[$i] =~ m//g){ $date = $filecontents[$i + 1]; $date =~ s/\n//g; $date =~ s/ //g; $date =~ s/$endtag//g; $date =~ s/ //g; @temp = split(/\//, $date); $date = "$temp[0]/$temp[1]"; $name = $filecontents[$i + 2]; $name =~ s/\n//g; $name =~ s/  //g; $name =~ s/$endtag//g; $name =~ s/ //g; $fname = $filecontents[$i + 4]; $fname =~ s/\n//g; $fname =~ s/ //g; $fname =~ s/$endtag//g; $fname =~ s/ //g; @temp = split(/ /, $fname); $fname = $temp[@temp-1]; $tname = $filecontents[$i + 6]; $tname =~ s/\n//g; $tname =~ s/ //g; $tname =~ s/$endtag//g; $tname =~ s/ //g; @temp = split(/ /, $tname); $tname = $temp[@temp-1]; $tab1 = tabber($name, 15); $tab2 = tabber($fname,10); print "$date $fname$tab2 -> $name$tab1 -> $tname\n"; } } } ############### P R I N T T R A D E S ################################ ###### A D D D B ###################################################### # This subroutine adds two db stats files together and returns an array # that can then be saved into a total file. Make sure the most recent is # the first arg. # INPUT: string (db 1 file path) # string (db 2 file path) # integer (1=player db, 0=goalie db) # OUTPUT: array - the two db files added together. # DEPENDENCIES: # EXAMPLE CALL: addDB($recentDB, $otherDB, 1); ######################################################################## sub addDB { my ($f1, $f2, $player_db) = @_; my @dba = openFile($f1); my @dbb = openFile($f2); my $this_line = ""; my @return_array = (); my @eachline_outer = (); my @eachline_inner = (); if($player_db){ my $pts = 0; my $p_m = 0; my $pen = 0; my $ppg = 0; my $shg = 0; my $gwg = 0; my $gtg = 0; my $sht = 0; my $gls = 0; my $ast = 0; my $gms = 0; foreach my $dbaline (@dba){ chomp $dbaline; @eachline_outer = split(/,/, $dbaline); foreach my $dbbline (@dbb){ chomp $dbbline; @eachline_inner = split(/,/, $dbbline); if ($eachline_outer[0] eq $eachline_inner[0]){ # Same name $pts = $eachline_outer[2] + $eachline_inner[2]; $p_m = $eachline_outer[3] + $eachline_inner[3]; $pen = $eachline_outer[4] + $eachline_inner[4]; $ppg = $eachline_outer[5] + $eachline_inner[5]; $shg = $eachline_outer[6] + $eachline_inner[6]; $gwg = $eachline_outer[7] + $eachline_inner[7]; $gtg = $eachline_outer[8] + $eachline_inner[8]; $sht = $eachline_outer[10] + $eachline_inner[10]; $gls = $eachline_outer[11] + $eachline_inner[11]; $ast = $eachline_outer[12] + $eachline_inner[12]; $gms = $eachline_outer[13] + $eachline_inner[13]; $this_line = "$eachline_outer[0],$eachline_outer[1],". "$pts,$p_m,$pen,$ppg,$shg,$gwg,$gtg,". "$eachline_outer[9],$sht,$gls,$ast,$gms\n"; push(@return_array, $this_line); } } } } else { my $sp = 0; my $wi = 0; my $lo = 0; my $ti = 0; my $sa = 0; my $ga = 0; my $gaa = 0; my $gms = 0; foreach my $dbaline (@dba){ chomp $dbaline; @eachline_outer = split(/,/, $dbaline); foreach my $dbbline (@dbb){ chomp $dbbline; @eachline_inner = split(/,/, $dbbline); if ($eachline_outer[0] eq $eachline_inner[0]){ # Same team $sp = ($eachline_outer[2] + $eachline_inner[2])/2; $wi = $eachline_outer[4] + $eachline_inner[4]; $lo = $eachline_outer[5] + $eachline_inner[5]; $ti = $eachline_outer[6] + $eachline_inner[6]; $sa = $eachline_outer[7] + $eachline_inner[7]; $ga = $eachline_outer[8] + $eachline_inner[8]; $gaa = $eachline_outer[9] + $eachline_inner[9]; $gms = $eachline_outer[10] + $eachline_inner[10]; $this_line = "$eachline_outer[0],$eachline_outer[1],". "$sp,$eachline_outer[3],$wi,$lo,$ti,$sa,". "$ga,$gaa,$gms\n"; push(@return_array, $this_line); } } } } return @return_array; } ################## K I L L S E A S O N ################################# # This subroutine erases all files but the ones needed to start over # from the begining. Then when done kills the program. # # INPUT: none. # OUTPUT: files created. # Dependencies: backErUpper($file, $dir); # openFile(); # checkDir($dir); # saveStats(PLAYERS_DB, @playersStats); # prompt_clear(); # # EXAMPLE CALL: killseason(); ######################################################################## sub killseason{ my $dir1 = "backups"; print"Opening a backup directory....."; # Create backup of db opendir(DIR, $dir1) || (my $f1 = 1) || die "Error opening $dir1 directory:". " $!\n"; close(DIR); if ($f1){ print"dosent exist so now making one!"; mkdir($dir1, 0755); backErUpper(PLAYERS_DB, $dir1); # if the dir isnt here than we backErUpper(GOALIES_DB, $dir1); # better make sure and back up } # the data bases. print"\n"; # Back up files print"Backing up bhl.pl..."; backErUpper("bhl.pl", $dir1); print"backing up ".TEAMS_DB."\n"; backErUpper(TEAMS_DB, $dir1); ## here I will remove the xxx directory...to start over sub delete_it{ my ($gms_dir) = @_; print"Deleting $gms_dir\n"; opendir(DIRR, $gms_dir) || print "Well, I guess $gms_dir isnt here!\n"; while (defined(my $file = readdir(DIRR))){ unlink("$gms_dir/$file"); } close(DIRR); rmdir($gms_dir); } delete_it(PLAYOFF_DIR . "/games"); delete_it(TEAM_DIR); delete_it(SEASON_DIR . "/games"); delete_it(SEASON_DIR); delete_it(PLAYOFF_DIR); delete_it("carreer"); delete_it("."); print"Bringing back bhl.pl..."; backErUpper("$dir1/bhl.pl", "."); print"bringing back ".TEAMS_DB."\n"; backErUpper("$dir1/ ".TEAMS_DB, "."); print"Bringing back ".GOALIES_DB."..."; backErUpper("$dir1/ ".GOALIES_DB, "."); print"bringing back ".PLAYERS_DB."\n"; backErUpper("$dir1/ ".PLAYERS_DB, "."); print".........................Done\n"; exit; } ################## K I L L ############################################# ############### M A K E H T M L T O D A Y P A G E ############# # Creates a html page that is the start page for the leaguwe navagator.. # # INPUT: # # OUTPUT: html file output # # DEPEND: saveStats(PLAYERS_DB, @playersStats); # openFile($name); # @today = getDate(); # prompt_clear(); # sorter(2, PLAYERS_DB); # %teams = makeTeamNameHash(); # my @teams =teamsArray("___"); # arraySorter(2, $delimiter, @file_contents); # # SAMPLE CALL: makeHtmltodayPage(); ######################################################################## sub makeHtmltodayPage { my $file = "today.html"; my $buffer = ""; if ($SEASON_OVER_FLAG){ $buffer = '' . '' ."\n". '<!--BHL seasonnameheader-->' ."\n". '

    ' . '' ."\n". '' ."\n". '

    ' ."\n". '' ."\n". '

    ' ."\n". '' ."\n". '

    ' ; } else { $buffer = '' . '' ."\n". '<!--BHL pageheader-->' ."\n". '

    ' . '' ."\n". '' ."\n". '

    Todays Games

    '."\n". '' ."\n". '

    Yesterdays Games

    ' ."\n". '' ."\n". '

    Todays Top Team

    ' ."\n". '' ."\n". '

    Todays Top Player

    ' ."\n". '' ."\n". '

    Todays Top Goalie

    ' ."\n". '' ."\n". '

    Todays Trades

    ' ."\n". '' ."\n". '

    ' ; } print"Saving stats to $file\n"; saveStats($file, $buffer); print"Calling Update HTML Today Page routine\n"; prompt_clear(); updateHtmltodayPage(); } ############### M A K E H T M L T O D A Y P A G E ############# ############### U P D A T E H T M L T O D A Y P A G E ######## # Updates the today page. # # INPUT: # # OUTPUT: html file output # # DEPEND: saveStats(PLAYERS_DB, @playersStats); # openFile($name); # @today = getDate(); # prompt_clear(); # sorter(2, PLAYERS_DB); # %teams = makeTeamNameHash(); # my @teams =teamsArray("___"); # arraySorter(2, $delimiter, @file_contents); # # SAMPLE CALL: updateHtmltodayPage(); ######################################################################## sub updateHtmltodayPage { my $file = "today.html"; my @file_stuff = openFile($file); my $foulder = SEASON_DIR; my @today = getDate(); my $today_string = "$today[0]/$today[1]/$today[2]"; my %teams = makeTeamNameHash(); my $context = ""; if ($PLAYOFF_MODE){ $foulder = PLAYOFF_DIR; $context = "Playoffs"; } else { $foulder = SEASON_DIR; $context = "Regular Season"; } ## Decrement day my @d = @today; if ($d[0] == 3 && $d[1] == 1){ $d[0]--; $d[1] = 28; }elsif (($d[0] == 5 || $d[0] == 7 || $d[0] == 10 || $d[0] == 12) && $d[1] == 1){ $d[1] = 30; $d[0]--; }elsif ($d[1] == 1 && $d[0] == 1){ $d[1] = 31; $d[0] = 12; $d[2]--; }elsif ($d[1] == 1){ $d[1] = 31; $d[0]--; }else{ $d[1]--; } my $yesterday_string = "$d[0]/$d[1]/$d[2]"; ## END Increment day #> Getting the top goalie. my @gconfig_file = openFile(SEASON_G_DB); if(@gconfig_file <= 0){ print "There are no goalies ... Something is wrong with DB files!\n"; exit; } @gconfig_file = arraySorter(2, 4, ',', @gconfig_file); my $gconfig_file_line = $gconfig_file[0]; my @gttl = split(/,/, $gconfig_file_line); my $gteam_name = $teams{$gttl[1]}; my @gname = split (/ /, $gttl[0]); my $savep = $gttl[2] * 100; my $plurl = ""; my $plurl2 = ""; my $plurl3 = ""; if ($gttl[10] != 1){$plurl = "s";} #set plurl handler if ($gttl[7] != 1){$plurl2 = "s";} #set plurl handler if ($gttl[4] != 1){$plurl3 = "s";} #set plurl handler my $top_goalie = "\ \ \ ". "$gttl[0] of the $gteam_name,". " is the top goalie in the $LEAGUE_NAME.". "\  This player has an impressive ". "$gttl[9] goals against average and leads ". "the league with a $savep% save percentage.". "\  In $gttl[10] game$plurl $gname[0] ". "has $gttl[7] save$plurl2 and $gttl[4] ". "win$plurl3.\n"; #> Getting the top team. my @config_file = openFileWIgnore(TEAMS_DB, FREE_AGENT, 0); @config_file = arraySorter(8, 10, ',', @config_file); my $config_file_line = $config_file[0]; my @ttl = split(/,/, $config_file_line); $plurl = ""; $plurl2 = "s"; $plurl3 = ""; my $plurl4 = ""; if ($ttl[5] != 1){$plurl = "s";} #set plurl handler if ($ttl[6] != 1){$plurl2 = "es";} #set plurl handler if ($ttl[10] != 1){$plurl3 = "s";} #set plurl handler if ($ttl[11] != 1){$plurl4 = "s";} #set plurl handler my $top_team = "   ". "The $ttl[1] is the top team with ". "$ttl[5] win$plurl and only $ttl[6] ". "los$plurl2.  The $ttl[2] conference ". "leader has scored $ttl[10] goal$plurl3 ". "while allowing $ttl[11] goal$plurl4 ". "against.\n"; #> Getting the top team at end of year. my @confi_file = openFileWIgnore(TEAMS_DB, FREE_AGENT, 0); @confi_file = arraySorter(8, 10, ',', @confi_file); my $confi_file_line = $confi_file[0]; my @tttl = split(/,/, $confi_file_line); my $tt = "

    $tttl[1]

    \n"; #> Getting the top player. sorter(2, 11, SEASON_P_DB); # sort my @pconfig_file = openFile(SEASON_P_DB); if (@pconfig_file <= 0){ @pconfig_file = openFile(PLAYERS_DB); } my $pconfig_file_line = $pconfig_file[0]; my @pttl = split(/,/, $pconfig_file_line); my $pteam_name = $teams{$pttl[1]}; my @pname = split (/ /, $pttl[0]); $plurl = ""; $plurl2 = ""; $plurl3 = ""; $plurl4 = ""; if ($pttl[2] != 1){$plurl = "s";} #set plurl handler if ($pttl[13] != 1){$plurl2 = "s";} #set plurl handler if ($pttl[11] != 1){$plurl3 = "s";} #set plurl handler if ($pttl[12] != 1){$plurl4 = "s";} #set plurl handler my $top_player = "   ". "$pttl[0] of the $pteam_name,". " is the top player in the $LEAGUE_NAME.". "  This player has an impressive ". "$pttl[3] +/- and leads the league with ". "$pttl[2] point$plurl.  In $pttl[13] ". "game$plurl2 $pname[0] has $pttl[11] ". "goal$plurl3 and $pttl[12] assist$plurl4.\n"; #> Getting the schedule - an array of games. my @filecontents=openFile("$foulder/schedule.html"); my @games = (); my $date = ''; my $awayt = ''; my $homet = ''; my $ascore = ''; my $hscore = ''; my $endtag = ''; my $ignore = ""; for(my $i = 0; $i < (@filecontents - 1); $i++){ if ($filecontents[$i] =~ m//g){ $date = $filecontents[$i + 1]; $date =~ s/\n//g; $date =~ s/ //g; $ignore = ''; $date =~ s/$ignore//g; $date =~ s/$endtag//g; $awayt = $filecontents[$i + 2]; $awayt =~ s/\n//g; $awayt =~ s/ //g; $awayt =~ s/$endtag//g; $homet = $filecontents[$i + 4]; $homet =~ s/\n//g; $homet =~ s/ //g; $homet =~ s/$endtag//g; $ascore = $filecontents[$i + 5]; $ascore =~ s/\n//g; $ascore =~ s/ //g; $ascore =~ s/$endtag//g; $ascore =~ s/ //g; $hscore = $filecontents[$i + 6]; $hscore =~ s/\n//g; $hscore =~ s/ //g; $hscore =~ s/$endtag//g; $hscore =~ s/ //g; #print "Going to push $date,$awayt,$homet,$ascore,$hscore\n"; #prompt_clear(1); push (@games, "$date,$awayt,$homet,$ascore,$hscore"); } } my @f_contents = (); #> Getting the trades - an array of trades. @f_contents=openFile("$foulder/trade.html"); my @trades = (); my $tdate = ''; my $name = ''; my $fname = ''; my $tname = ''; my $end_tag = ''; my @temp; my $signed = FALSE; my $released = FALSE; for(my $i = 0; $i < (@f_contents - 1); $i++){ if ($f_contents[$i] =~ m//g){ $tdate = $f_contents[$i + 1]; $tdate =~ s/\n//g; $tdate =~ s/ //g; $ignore = ''; $tdate =~ s/$ignore//g; $tdate =~ s/$end_tag//g; $name = $f_contents[$i + 2]; $name =~ s/\n//g; $name =~ s/  //g; $name =~ s/$end_tag//g; $name =~ s/ //g; $fname = $f_contents[$i + 4]; $fname =~ s/\n//g; $fname =~ s/ //g; $fname =~ s/$end_tag//g; $fname =~ s/ //g; @temp = split(/ /, $fname); $fname = $temp[@temp-1]; $tname = $f_contents[$i + 6]; $tname =~ s/\n//g; $tname =~ s/ //g; $tname =~ s/$end_tag//g; $tname =~ s/ //g; @temp = split(/ /, $tname); $tname = $temp[@temp-1]; push (@trades, "$tdate,$name,$fname,$tname"); } elsif ($f_contents[$i] =~ m/signed/g){ $signed = TRUE; } elsif ($f_contents[$i] =~ m/released/g) { $released = TRUE; } } @f_contents = (); if($DBUG){ my ($p, $f, $l) = caller; print"---------- UPDATE HTML TODAY PAGE ----------\n"; print"$f line $l\n"; print"--------------------------------------------\n"; print"trades array: \n@trades\n"; print"trades array(#) = $#trades\n"; } #> Finding Trades today my @trade_data = (); my $tflag = 1; my $t_trades = EMPTY; foreach my $trade (@trades){ @trade_data = split (/,/, $trade); if($DBUG){ print"--------------------------------------------\n"; print"t_trades = $t_trades\n"; print"trade_data[0] = $trade_data[0]\n"; print"trade_data[1] = $trade_data[1]\n"; print"trade_data[2] = $trade_data[2]\n"; print"trade_data[3] = $trade_data[3]\n"; print"--------------------------------------------\n"; } if ($signed){ $t_trades = $t_trades."   $trade_data[1]". " was signed today by $trade_data[3]
    \n"; $tflag = 0; } elsif ($released){ $t_trades = $t_trades."   $trade_data[1]". " was released today from". " $trade_data[2]
    \n"; $tflag = 0; } elsif ($trade_data[0] =~ m/$today_string/g) { $t_trades = $t_trades."   $trade_data[1]". " was traded today from $trade_data[2]". " to $trade_data[3]
    \n"; $tflag = 0; } $signed = FALSE; $released = FALSE; } if ($tflag){ $t_trades = "   No trades today!
    \n"; } @trade_data = (); @trades = (); #> Finding Games today, yesterday my @game_specs = (); my $games_today = ""; my $games_yesterday = ""; my $new_season = 0; my $flag = 1; #Now it is getting dirty foreach my $game (@games){ @game_specs = split (/,/, $game); if ($game_specs[0] =~ m/$today_string/g){ if ($game_specs[3] =~ m/-/g){ $games_today = $games_today . "   $game_specs[1] at". " $game_specs[2]
    \n"; if ($flag){$new_season = 1;} } else { $games_today = $games_today . "   $game_specs[1] $game_specs[3]". "  $game_specs[2] $game_specs[4]
    \n"; } } elsif ($game_specs[0] =~ m/$yesterday_string/g){ $games_yesterday = $games_yesterday . "   $game_specs[1] $game_specs[3]". "  $game_specs[2] $game_specs[4]
    \n"; } if ($new_season){ $games_yesterday = "Not Yet Available"; $top_team = "Not Yet Available"; $top_player = "Not Yet Available"; $top_goalie = "Not Yet Available"; $t_trades = "Not Yet Available"; } $flag = 0; } my $header = "$LEAGUE_NAME $context Today $today_string"; #> Tags my $pageheader = ''; my $todaysgames = ''; my $yesterdaysgames = ''; my $topteam = ''; my $topplayer = ''; my $topgoalie = ''; my $todaystrades = ''; my $seasonnameheader = ''; my $leaguenameheader = ''; my $teamname = ''; sub insertThis { my ($tag, $new_file_line, @file_lines) = @_; foreach my $file_line (@file_lines){ if ($file_line =~ m/$tag/g){ $file_line = $new_file_line; } } return @file_lines; } @file_stuff = insertThis($pageheader, $header, @file_stuff); @file_stuff = insertThis($todaysgames, $games_today, @file_stuff); @file_stuff = insertThis($yesterdaysgames, $games_yesterday, @file_stuff); @file_stuff = insertThis($topteam, $top_team, @file_stuff); @file_stuff = insertThis($topplayer, $top_player, @file_stuff); @file_stuff = insertThis($topgoalie, $top_goalie, @file_stuff); @file_stuff = insertThis($todaystrades, $t_trades, @file_stuff); # End of Season Stuff @file_stuff = insertThis($seasonnameheader, "

    Season $SEASON_NAME". "

    ", @file_stuff); @file_stuff = insertThis($leaguenameheader, "

    $LEAGUE_NAME". " Champion

    ", @file_stuff); @file_stuff = insertThis($teamname, $tt, @file_stuff); saveStats($file, @file_stuff); } ############### U P D A T E H T M L T O D A Y P A G E ######## ############### A D D T O C O N F I G ########################### # Updates the today page. # # INPUT: string (Constant) # string,int, char (value) # # OUTPUT: line added to file # # DEPEND: openFile($name); # saveStats(CONFIG_FILE, @f); # # SAMPLE CALL: addToConfig($constant, $value); ######################################################################## sub addToConfig { my ($constant, $value) = @_; my @f = openFile(CONFIG_FILE); push(@f, "$constant,$value\n"); saveStats(CONFIG_FILE, @f); } ############### A D D T O C O N F I G ########################### ############### i s T h e r e A C h a m p i o n################## # Sorts a season db file then finds out if there is a true champion. # # INPUT: none # # OUTPUT: boolean (Is there a champion yet?) # # DEPEND: openFile(TEAMS_DB); # arraySorter(5, 8, ',', @schedule); # # SAMPLE CALL: isThereAChampion(); ######################################################################## sub isThereAChampion{ my @schedule = openFileWIgnore(TEAMS_DB, FREE_AGENT, 0); @schedule = arraySorter(5, 8, ',', @schedule); my @first_place = split(/,/, $schedule[0]); my @second_place = split(/,/, $schedule[1]); if($first_place[5] == $second_place[5]){ return 0; } else { return 1; } } ############### SET UP PLAYOFFS ###################################### # Set up the next round in the playoffs. # # INPUT: none # # OUTPUT: none # # DEPEND: openFile(TEAMS_DB); # arraySorter(8, 10, ',', @teamsdb); # prompt_clear(1); # saveStats(SCHED_DAT, @out); # getDate(); # makeTeamNameHash(); # # # SAMPLE CALL: setUpNextRound(); ######################################################################## sub setUpNextRound{ my %seen_confs = ();# Hash of conferences and their teams. # Sort the teamsdb.csv file my @teamsdb = openFileWIgnore(TEAMS_DB, FREE_AGENT, 0); @teamsdb = arraySorter(8, 10, ',', @teamsdb); # Find out the number 'n' of teams to involve in the playoffs my $n = 0; # teams going to the playoffs my @ts = (); #team stats @ts = split (/,/, $teamsdb[0]); my $b = $ts[5]; #best wins foreach my $t (@teamsdb){ @ts = split (/,/, $t); if ($ts[5] eq $b){$n++;} } # Set n to reflect array indexes. Keep n in a safe place. $n--; # Make a hash of conferences. foreach my $teamsdb_line (@teamsdb){ my @line = split(/,/, $teamsdb_line); if (@line < 3){ my $problem = "Db file not set up right"; (my $package, my $filename, my $line) = caller; print"\n$filename:subroutine $package,$problem,line $line\n"; prompt_clear(1); return 1; } # Get the conf as keys in a hash $seen_confs{$line[2]}=""; } # Make a hash that has conferences in the key and the playoff teams # delimited with ',' as the values. foreach my $hashed (keys %seen_confs){ my $temp = ""; foreach my $teamsdb_line (@teamsdb){ my @line = split(/,/, $teamsdb_line); if ($hashed eq $line[2]){ $temp = "$temp,$line[0]"; } } $seen_confs{$hashed}=$temp; } # L O O P E R 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ sub looper2 { # uses varables global to outer sub!!! #~ my ($hg, $f, $n, $confs, @a) = @_; #~ my $reset = $n; #~ my %seen_confs = %$confs; #~ # Loop through the conferences and make games at home. #~ for (my $i = $hg; $i > 0; $i--){ #~ for (my $s = 0; $s <= $n; $s++){ #~ foreach my $conf (keys %seen_confs){ #~ my @c = split (/,/, $seen_confs{$conf}); #~ my $garbage = shift (@c); #~ push (@a, "$c[$s],$c[$n]\n"); #~ } #~ $n--; #~ } #~ $n = $reset; #~ } #~ #~ if($f){ #~ # Loop through the conferences and make games at away. #~ for (my $i = $hg; $i > 0; $i--){ #~ for (my $s = 0; $s <= $n; $s++){ #~ foreach my $conf (keys %seen_confs){ #~ my @c = split (/,/, $seen_confs{$conf}); #~ my $garbage = shift (@c); #~ push (@a, "$c[$n],$c[$s]\n"); #~ } #~ $n--; #~ } #~ $n = $reset; #~ } #~ } #~ return @a; #~ } #~ # L O O P E R ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Loop through the conferences and make 2 games at home then away. my $confs = \%seen_confs; # Create a reference my @out = (); @out = looper2(2,1, $n, $confs, @out); # Loop through the conferences and make 1 game at home then away. @out = looper2(1,1, $n, $confs, @out); # Loop through the conferences and make 1 game at home (7th game). @out = looper2(1,0, $n, $confs, @out); saveStats(SCHED_DAT, @out); ## Make HTML page! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ my @season = @out; # From above my $file = PLAYOFF_DIR."/schedule.html"; my @date = getDate(); # For dates my @buffer =(); # search for ...then insert my @file_contents = openFile($file); my $last_line =''; foreach my $fc_line (@file_contents){ if ($fc_line =~ m/$last_line/g){ #NADA } else { push (@buffer, $fc_line); } } ##################################################################### sub scheduler2{ my ($tdy, $buff, @szn) = @_; my @team = (); my $home = ""; my $away = ""; my $homeName = ""; my $awayName = ""; my @buffr = @$buff; my %tnhash = makeTeamNameHash(); my $flag = 0; my %teams_played = (); foreach my $line (@szn){ chomp $line; @team = split(/,/, $line); if((!(exists $teams_played{$team[0]} )) &&(!(exists $teams_played{$team[@team-1]})) &&(@team > 1)){ $home = pop(@team); $away = $team[0]; $awayName = $tnhash{$away}; $homeName = $tnhash{$home}; chomp $awayName; chomp $homeName; push (@buffr, "\n".' '."\n". ' '."$tdy".' '."\n". ' '."$awayName".'' ."\n". ' '."at".' '."\n". ' '."$homeName".'' ."\n". ' '."-".' '."\n". ' '."-".' '."\n". ' '); $teams_played{$home}=$away; $teams_played{$away}=$home; $flag = 1; } $line = join(',', @team); $line = "$line\n"; } $buff = \@buffr; return ($flag, $buff, @szn); } #######end scheduler2################################################ my $today = "$date[0]/$date[1]/$date[2]"; my $games_have_run = 1; while ($games_have_run){ my $bffr = \@buffer; ($games_have_run, $bffr, @season) = scheduler2($today, $bffr, @season); @buffer = @$bffr; ## Increment day if ($date[0] == 2 && $date[1] == 28){ $date[0]++; $date[1] = 1; }elsif (($date[0] == 4 || $date[0] == 6 || $date[0] == 9 || $date[0] == 11) && $date[1] == 30){ $date[1] = 1; $date[0]++; }elsif ($date[1] == 31 && $date[0] == 12){ $date[1] = 1; $date[0] = 1; $date[2]++; }elsif ($date[1] == 31){ $date[1] = 1; $date[0]++; }else{ $date[1]++; } $today = "$date[0]/$date[1]/$date[2]"; ## END Increment day my $top_o_array = shift(@season); push(@season, $top_o_array); } push (@buffer, "\n"); saveStats($file, @buffer); ## End Make HTML page! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ } ############### SET UP PLAYOFFS ###################################### ############### print config file readme ############################### # Sorts a season db file then finds out if there is a true champion. # # INPUT: none # # OUTPUT: command line output # # DEPEND: none # # SAMPLE CALL: configFileReadMe(); ######################################################################## sub configFileReadMe{ print "The following files are needed for the hockey sim to work:\n"; print "\n"; print " 1) goaliesdb.csv - goalie stats file has the following fo". "rmatt:\n"; print " full name, team abbr, save %, line, wins, losses, ties,". " saves, goals\n"; print " against, goals against average, games\n"; print "\n"; print " 2) playersdb.csv - player stats file has the following for". "matt:\n"; print " full name, team abbr, pts, +/-, pen, ppg, shg, gwg, gtg". ", line, shots,\n"; print " goals, assists, games\n"; print "\n"; print " 3) teamsdb.csv - team name file has the following formatt". ":\n"; print " abbr, full name, conference, division, games, wins, los". "es, ties, points\n"; print " win%, Goals For, Goals Against, Power Play Goals, PPM, ". "PP%, Pen.Min.,\n"; print " PK%, Owner, Address, Contact( e-mail ), Arena, Seat ". "Capacity, and Last \n"; print " games attendance.\n"; } ############### print config file readme ############################### ############### Create Team ############################################ # This subprogram creats a team and inserts it into the teams db. This # team will probably not play untill next season. # # INPUT: none. # # OUTPUT: updated db file. # # DEPEND: openFile(TEAMS_DB);. # prompt_clear(1); # saveStats(TEAMS_DB, @file_contents); # # SAMPLE CALL: createTeam(); ######################################################################## sub createTeam{ my @file_contents = openFile(TEAMS_DB); my $team_name = ""; my $team_abbr = ""; my $answer = ""; if (@file_contents <= 0){ print"ERROR (createTeam): Nothing in file!\n"; prompt_clear(1); last; } while(1){ print "Provide team name here ==> "; $team_name=; chomp $team_name; my $l = length($team_name); if ($l <= 1){ print"You didnt type anything ... goodbye"; prompt_clear(1);last; } print "Are you sure it is \"$team_name\"? (y or n) "; $answer = ; chomp $answer; if ($answer eq "y" || $answer eq "Y"){ last; } } while(1){ print "Provide team abbreviation (3 letters, no caps) here ==> "; $team_abbr=; chomp $team_abbr; my $l = length($team_abbr); if ($l <= 1){ print"You didnt type anything ... goodbye"; prompt_clear(1);last; } print "Are you sure it is \"$team_abbr\"? (y or n) "; $answer = ; chomp $answer; if ($answer eq "y" || $answer eq "Y"){ last; } } $team_name = "$team_abbr,$team_name,,,0,0,0,0,0,0,0,0,0,0,0.0,0,0.0\n"; push (@file_contents, $team_name); saveStats(TEAMS_DB, @file_contents); updateTeamHTML($team_abbr); } ############### Create Team ########################################### ############### Debug ################################################## # This creates debug lines. # # INPUT: Int (tabs), String (message). # # OUTPUT: print to line. # # DEPEND: none # # SAMPLE CALL: if ($DBUG){debug($tabs, $message);} ######################################################################## sub debug{ my ($tabs, $message) = @_; if ($tabs < 0){$tabs = 0;} for (my $i = $tabs; $i > 0; $i--){ print "\t"; } print "$message"; } ############### Debug ################################################## ############### evenChecker ############################################ # Checks values in a hash and returns a boolean true if they are all # within 1. # # INPUT: Hash. # # OUTPUT: Boolean (true if the values within 1). # # DEPEND: none # # SAMPLE CALL: if(evenChecker(%hash)){} ######################################################################## sub evenChecker { my %h = @_; my $unevenDivisions = 0 ; my @hvalues = values %h; my $numberOfValues = @hvalues ; my $allValuesAdded = 0 ; foreach my $v (@hvalues){ $allValuesAdded = $allValuesAdded + $v; } my $goodValue = int($allValuesAdded / $numberOfValues); foreach my $v (@hvalues){ if( $v == $goodValue || $v == ($goodValue+1) || $v == ($goodValue-1)) { $unevenDivisions = 1 }else{ return 0; } } return $unevenDivisions; } ############### evenChecker ########################################### ##################P R I N T H A S H ######################## # This subroutine prints a hash to the screen. # # IN: hash # OUT: none, prints to the screen. # SUBROUTINES NEEDED: prompt_clear(1); # EXAMPLE: printHash(%hi); ############################################################# sub printHash { my %hsh = @_; foreach (keys %hsh){ print "key =>$_ \t value=>$hsh{$_}\n"; } prompt_clear(1) unless $DBUG; } ################## SET DIVISIONS ###################################### # This subroutine will, upon entering a new league or a new season, # check the teams database for the number of teams. Depending on that # number the leage will be set up structurally...ie - Conferences and # divisions. # # INPUT: None. # OUTPUT: Teams will be organized. # DEPENDENCES: prompt_clear(); # if(evenChecker(%hash)){} # # EXAMPLE CALL: @arrray = setDivisions(@arrray); # NOTE OF IMPORTANCE: ####################################################################### sub setDivisions { my @teamsdb = @_ ; my $tabs = 0 ; my $confRgood = TRUE ; my $numberOfTeams = @teamsdb; my $message = "" ; my $freeAgentFlag = FALSE ; my $freeAgentLine = "" ; my @teamStats = () ; my @divisions = () ; my @conferences = () ; my %seen_confs = () ; my %seen_divs = () ; #################################################################### sub setUpArray { my ($msg, $numbOtimes, $flag, @returnArray) = @_; my $answer = ""; my $name = "division"; my $returnArrayNum = 0; print $msg; $returnArrayNum = @returnArray; if ($flag){ $name = "conference"; if ($returnArrayNum == $numbOtimes){ $answer = 'n'; }else{ $answer = 'y'; } } else { $answer = 'y'; } if ($answer eq 'y'){ if($returnArrayNum == ($numbOtimes + 1)){# dont forget arrays print "Sorry but there are already enough $name (s)\n"; } elsif ($numbOtimes == 0) { @returnArray = (); } elsif ($returnArrayNum > ($numbOtimes + 1)) { print "\nERROR: To many $name (s), go into DB file and ". "delete! This program will now exit!\n"; prompt_clear(1);exit; } else { while ($returnArrayNum <= $numbOtimes){ print "Existing $name(s):\n@returnArray\n\n"; print "Enter $name name (q to quit) => "; $answer = ;chomp $answer; last if ($answer eq 'q'); push(@returnArray, $answer); $returnArrayNum = @returnArray; prompt_clear(0); } } } return @returnArray; } #################################################################### sub rehash { my (@a) = @_; my %seen = (); foreach my $t (@a){ $seen{$t}=0; } return %seen; } #################################################################### #################################################################### sub addToHash{ my ($tc, $ar, %h) = @_; my @ds = split (/,/, $ar); foreach my $div (@ds){ $h{$div} = $tc; } return %h; } #################################################################### #################################################################### sub assignDiv{ my($ds, $stat, %seenhash)=@_; my $ans = "NULL"; prompt_clear(0); print "Existing divisions:\n$ds\n"; while (!exists $seenhash{$ans}){ print "Assign a division to $stat ==> "; $ans = ;chomp $ans; } return $ans; } #################################################################### #################################################################### sub getNumConfs { my ($n) = @_; my $tabs= 2 ; if ($DBUG){debug($tabs, "getNumConfs=>number => $n\n" );} my $a = ""; print "-------- L e a g u e C o n f i g u r e ---------\n\n"; if ($n == 2){ print "WARNING: You can ONLY set up 0 or 2 conferences!\n". "How many would you like to set up? (0 or 2) "; $a = ;chomp $a; if ($a eq ''){print "IDIOT ! ";$a = 1;} if ($a == 0 || $a == 2) {return $a} else { print "ERROR: Bad answer, this program will now exit"; prompt_clear(1);exit; } } elsif ($n == 4){ print "WARNING: You can ONLY set up 4, 2 or 0 conferences!\n". "How many would you like to set up? (0, 2 or 4) "; $a = ;chomp $a; if ($a eq ''){print "IDIOT ! ";$a = 1;} if ($a == 0 || $a == 4 || $a == 2) {return $a} else { print "ERROR: Bad answer, this program will now exit"; prompt_clear(1);exit; } } elsif ($n == 8){ print "WARNING: You can ONLY set up 0, 2, 4, or 8 conferences". "!\nHow many would you like to set up? (0, 2, 4 or 8) "; $a = ;chomp $a; if ($a eq ''){print "IDIOT ! ";$a = 1;} if ($a == 0 || $a == 4 || $a == 2 || $a == 8) { return $a } else { print "ERROR: Bad answer, this program will now exit"; prompt_clear(1);exit; } } elsif ($n == 16){ print "WARN: You can ONLY set up 0, 2, 4, 8 or 16 conferences". "!\nHow many would you like to set up? (0, 2, 4, 8 or 1". "6) "; $a = ;chomp $a; if ($a eq ''){print "IDIOT ! ";$a = 1;} if ($a == 0 || $a == 4 || $a == 2 || $a == 8 || $a == 16) { return $a } else { print "ERROR: Bad answer, this program will now exit"; prompt_clear(1);exit; } } } #################################################################### # MAIN ############################################################# # Remove the Free agents! my @tmpArray = (); foreach my $team (@teamsdb){ my @teamStats = split (/,/, $team); if ($teamStats[0] eq FREE_AGENT){ $freeAgentFlag = TRUE; $freeAgentLine = $team; $numberOfTeams--; } else { push (@tmpArray, $team); } } @teamsdb = @tmpArray; # Record all Divisions and Conferences foreach my $team (@teamsdb){ my @teamStats = split (/,/, $team); if (@teamStats < 3){ print "\nERROR SETDIVISIONS: Teams DB file corrupted. This ". "program will now close."; prompt_clear(1);exit; } # Get the conf as keys in a hash $seen_confs{$teamStats[2]}=""; } @conferences = keys %seen_confs; if ($DBUG){debug($tabs, "seen conferences => \n@conferences\n" );} # Rules if ($numberOfTeams < 2) { prompt_clear(0); print "\nERROR: There is not at least 2 teams set up in this ". "league!\n"; print "This program will now exit...\n"; prompt_clear(1); exit; } elsif ($numberOfTeams < 6) { if (@conferences > 1) { @conferences = (); } prompt_clear(0); } elsif ($numberOfTeams < 12) { prompt_clear(0); $message = ""; @conferences = setUpArray($message, getNumConfs(2), 1, @conferences); } elsif ($numberOfTeams < 24) { prompt_clear(0); $message = ""; @conferences = setUpArray($message, getNumConfs(4), 1, @conferences); } elsif ($numberOfTeams < 48) { prompt_clear(0); $message = ""; @conferences = setUpArray($message, getNumConfs(8), 1, @conferences); } elsif ($numberOfTeams < 96) { prompt_clear(0); $message = ""; @conferences = setUpArray($message, getNumConfs(16), 1, @conferences); } # Set up conferences - if there are enough (i.e. 6) if(@conferences > 1){ my $numofconfs = int(@conferences); my $goodNumber = int($numberOfTeams / $numofconfs); my @savedArray = @teamsdb; while(1){ my $keeptrack = 0; prompt_clear(0); print "\nNOTICE: Try to keep $goodNumber team(s) in each ". "conference!\n"; @teamsdb = @savedArray; foreach my $team (@teamsdb){ my @teamStats = split (/,/, $team); if(!exists $seen_confs{$teamStats[2]} || $teamStats[2] eq ''){ print "\nExisting conferences:\n\n@conferences\n\n"; $message = "NULL"; %seen_confs = rehash(@conferences); while (!exists $seen_confs{$message}){ print "Assign a conference to $teamStats[1] ==> "; $message = ;chomp $message; $confRgood = FALSE; } $seen_confs{$message}++; $teamStats[2]= $message; $team = join (',', @teamStats); } else { $seen_confs{$teamStats[2]}++; } if ($conferences[1] eq $teamStats[2]){$keeptrack++} prompt_clear(0); } %seen_confs = rehash(@conferences); last if evenChecker(%seen_confs); print"UNEVEN ASSIGNMENTS ... TRY AGAIN!\n\n"; prompt_clear(1); } } else { foreach my $team (@teamsdb){ my @teamStats = split (/,/, $team); $teamStats[2]= ''; $team = join (',', @teamStats); } } foreach my $team (@teamsdb){ my @teamStats = split (/,/, $team); $seen_divs{$teamStats[3]}=$teamStats[2]; $teamStats[3]= ''; $team = join (',', @teamStats); } # Tell the user that the conferences are all set if ($confRgood) { print "-------- L e a g u e C o n f i g u r e ---------\n\n"; print "The conferences are already set!\n"; } # Exit if divisions are not wanted print "Do you want to set up divisions? (y or n) "; my $answr = ;chomp $answr; if ($answr eq 'y' || $answr eq 'Y' || $answr eq "yes") { prompt_clear(0); # loop untill divisions are set up correctly. my $thisConf = ""; my $numInConf = 0 ; my @tempArray = (); my @savedArray = @teamsdb; my %temphash = (); my %teamHash = (); @teamsdb = @savedArray; foreach my $team (@teamsdb){ my @teamStats = split (/,/, $team); $thisConf = $teamStats[2]; if($thisConf eq ''){ $numInConf = $numberOfTeams; }else{ $numInConf = $seen_confs{$thisConf}; } @divisions = (); foreach (keys %seen_divs){ if ($seen_divs{$_} eq $thisConf){ push (@divisions, $_); } } if(@divisions > 0){ if ($divisions[0] eq ''){shift @divisions;} } if ($numInConf < 6){ if (!exists $teamHash{$thisConf}){ print"Sorry, not enough teams in $thisConf ". "conference\n"; prompt_clear(1); } $teamHash{$thisConf}=0; } elsif($numInConf < 7){ if(@divisions < 2){ @divisions = setUpArray("", 1, 0, @divisions); } # Add the new stuff added above to hash my $divs = join(',', @divisions); %seen_divs = addToHash($thisConf, $divs, %seen_divs); # Assign division $teamStats[3]= assignDiv($divs, $teamStats[1], %seen_divs); $team = join (',', @teamStats); } elsif ($numInConf < 13){ if(@divisions < 4){ @divisions = setUpArray("", 2, 0, @divisions); } # Add the new stuff added above to hash my $divs = join(',', @divisions); %seen_divs = addToHash($thisConf, $divs, %seen_divs); # Assign division $teamStats[3]= assignDiv($divs, $teamStats[1], %seen_divs); $team = join (',', @teamStats); } elsif ($numInConf < 25){ if(@divisions < 8){ @divisions = setUpArray("", 4, 0, @divisions); } # Add the new stuff added above to hash my $divs = join(',', @divisions); %seen_divs = addToHash($thisConf, $divs, %seen_divs); # Assign division $teamStats[3]= assignDiv($divs, $teamStats[1], %seen_divs); $team = join (',', @teamStats); } elsif ($numInConf < 49){ if(@divisions < 16){ @divisions = setUpArray("", 6, 0, @divisions); } # Add the new stuff added above to hash my $divs = join(',', @divisions); %seen_divs = addToHash($thisConf, $divs, %seen_divs); # Assign division $teamStats[3]= assignDiv($divs, $teamStats[1], %seen_divs); $team = join (',', @teamStats); }elsif ($numInConf < 97){ if(@divisions < 32){ @divisions = setUpArray("", 8, 0, @divisions); } # Add the new stuff added above to hash my $divs = join(',', @divisions); %seen_divs = addToHash($thisConf, $divs, %seen_divs); # Assign division $teamStats[3]= assignDiv($divs, $teamStats[1], %seen_divs); $team = join (',', @teamStats); } } } if($freeAgentFlag){push (@teamsdb, $freeAgentLine);} foreach my $team (@teamsdb){ my @teamStats = split (/,/, $team); if ($teamStats[0] eq ''){my $junk = pop(@teamStats);} $team = join(',', @teamStats); } return @teamsdb; } ##################Data Base Fixer ##################################### # This subroutine opens and checks a database for fields that are # blank or null. # # INPUT: Array (files to be fixed). # OUTPUT: None # DEPENDENCES: @data = openFile($file); # saveStats($file, @data); # EXAMPLE CALL: DBFixer(@file_array); # NOTE OF IMPORTANCE: . ####################################################################### sub DBFixer { my @file_array = @_; my @data = (); my @data_line_elements = (); my $answer1 = ""; my $answer2 = ""; foreach my $file (@file_array){ #open data base & read into an array my @data = openFile($file); #for each element of the arrray split into another array foreach my $data_line (@data){ my @data_line_elements = split(/,/, $data_line); foreach my $element (@data_line_elements){ #Test each element for a blank space if ($element eq '' || $element eq ' '){ #if so prompt the user to fix it while(1){ print "DB ERROR: The following line in $file has ". "an error:\n\n$data_line\n\nWhat do you want t". "o replace the missing data with with ==> "; $answer1 = ; chomp $answer1; print "$answer1 <== Are you shure (y or n)"; $answer2 = ; chomp $answer2; last if ($answer2 eq 'y'); } $element = $answer1; #replace the x with io $data_line = join(',', @data_line_elements); } } } #save to file saveStats($file, @data); } } ####################################################################### ##################MAKE TEAM HTML ###################################### # This constructs a team html page. # # INPUT: None # OUTPUT: HTML # DEPENDENCES: saveStats,makeTeamNameHash, openFile, # getTeamHTMLInfo # EXAMPLE CALL: makeTeamHTML(); # NOTE OF IMPORTANCE: . ####################################################################### sub makeTeamHTML { my @info ; # Info about this team my %teams = makeTeamNameHash() ; # Each team and their name my $FREE_AGNT = FREE_AGENT ; # Identifier to delete my @buffer = () ; # Holds the html my $teamFile ; # Temp file name holder my $pStatHeader ; # Header for player lineups my $gStatHeader ; # Header for goalie lineups my @line1 = () ; # Line One Array my @line2 = () ; # Line Two Array my @line3 = () ; # Line Three Array my @line4 = () ; # Line Four Array my @goalies = () ; # Goalie Array my @reserves = () ; # Reserves Array my @injured = () ; # InjuredArray my @freeAgents = () ; # Free Agents my @tempArray ; # Container my $tempString ; # Container my $end = '' ; # End of the plyr stat table my $injuryMessage ; # Injury Message in html my $reservesMessage ; # Reserves Message in html # First lets make the Free agents page makeFreeAgentPage(); # Get arrays. my @playerStats = openFile(SEASON_P_DB); # Players my @goalieStats = openFile(SEASON_G_DB); # Goalies # Get rid of free agents (for now will put makeFreeAgentsHTML()) delete $teams{$FREE_AGNT}; # Set up stat header for players $pStatHeader = '

    '."\n". ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n"; # Set up stat header for goalies $gStatHeader = '

    '."\n". '

    '."\n". '

    Games
    '."\n". '

    Points
    '."\n". '

    +/-
    '."\n". '

    Pen
    '."\n". '

    PPG
    '."\n". '

    SHG
    '."\n". '

    GWG
    '."\n". '

    GTG
    '."\n". '

    Shots
    '."\n". '

    Goals
    '."\n". '

    Assists
    '. "\n". ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n"; # Subroutine for inserting player lines (stats) !!!!!!!!!!!!!!!!!!!! sub insertPlayer{ my(@p) = @_; # Player info array my $html; # HTML output $html= ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n"; return $html; } # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # Subroutine for inserting goalie lines (stats) !!!!!!!!!!!!!!!!!!!! sub insertGoalie{ my(@p) = @_; # Player info array my $html; # HTML output $html= ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n"; return $html; } # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # For each team set up their page foreach my $t (keys %teams){ @info = getTeamHTMLInfo($t); $teamFile = TEAM_DIR . "/$info[0]" . '.html'; #initialize @line1 = (); # Line One Array @line2 = (); # Line Two Array @line3 = (); # Line Three Array @line4 = (); # Line Four Array @goalies = (); # Goalie Array @reserves = (); # Reserves Array @injured = (); # Injured Array @tempArray = (); # Temp Array # get this teams players foreach my $p (@playerStats){ @tempArray = split(/,/, $p); if ($tempArray[1] eq $t){ $tempString = insertPlayer(@tempArray); if($tempArray[9] == 1) { push (@line1, $tempString); }elsif($tempArray[9] == 2){ push (@line2, $tempString); }elsif($tempArray[9] == 3){ push (@line3, $tempString); }elsif($tempArray[9] == 4){ push (@line4, $tempString); }elsif($tempArray[9] == 5){ push (@reserves, $tempString); }else{ push (@injured, $tempString); } } } # get this teams goalies foreach my $plr (@goalieStats){ @tempArray = split(/,/, $plr); if ($tempArray[1] eq $t){ $tempString = insertGoalie(@tempArray); push (@goalies, $tempString); } } # Check for injuries, if none ... nothing! if (@injured < 1){ $injuryMessage = "No current injured players."; }else{ $injuryMessage = "$pStatHeader@injured$end"; } # Check for reserves, if none ... nothing! if (@reserves < 1){ $reservesMessage = "No current players in reserve."; }else{ $reservesMessage = "$pStatHeader@reserves$end"; } #~~~~~~~~~~~~~~ HTML ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $buffer[0] =''. ''."$info[1] web page".''."\n". ''."\n". '
    '."\n". '

    '."\n". '

    Games
    '."\n". '

    W
    '."\n". '

    L
    '."\n". '

    T
    '."\n". '

    Save%
    '."\n". '

    S
    '."\n". '

    GA
    '."\n". '

    GAA
    '."\n". '

    '."\n". '

    '."$p[0]".'

    '."\n". '

    '."$p[13]".'
    '."\n". '

    '."$p[2]".'
    '."\n". '

    '."$p[3]".'
    '."\n". '

    '."$p[4]".'
    '."\n". '

    '."$p[5]".'
    '."\n". '

    '."$p[6]".'
    '."\n". '

    '."$p[7]".'
    '."\n". '

    '."$p[8]".'
    '."\n". '

    '."$p[10]".'
    '."\n". '

    '."$p[11]".'
    '."\n". '

    '."$p[12]".'
    '."\n". '

    '."$p[0]".'

    '."\n". '

    '."$p[10]".'
    '."\n". '

    '."$p[4]".'
    '."\n". '

    '."$p[5]".'
    '."\n". '

    '."$p[6]".'
    '."\n". '

    '."$p[2]".'
    '."\n". '

    '."$p[7]".'
    '."\n". '

    '."$p[8]".'
    '."\n". '

    '."$p[9]".'
    '."\n". '

    '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". '
    '."\n". '

    '."\n". ''."$info[2]".''."\n". '

    '."\n". '
    '."\n". '
    '."\n". '

    '."\n". ''."$info[1]".''."\n". '

    '."\n". '
    '."\n". '
    Owner:'."\n". ''."$info[17]".''."\n". ' Record:'."\n". ''."$info[5]-$info[6]-$info[7]".''."\n". '
    Address:'."\n". ''."$info[18]".''."\n". ' Goals For:'."\n". ''."$info[10]".''."\n". '
    Contact:'."\n". ''. "$info[19]". ''."\n". ' Goals Against:'."\n". ''."$info[11]".''."\n". '
    Arena:'."\n". ''."$info[20]".''."\n". ' PM: '."\n". ''."$info[15] min.".''."\n". '
    Capacity: '."\n". ''."$info[21]".''."\n". ' Power Play:'."\n". ''."$info[14]\%".''."\n". '
    Attendance:'."\n". ''."$info[22]".''."\n". ' Last Game:'."\n". ''."$info[24]".''."\n". '
    '."\n". '
    '."\n". ' PASSWORD:'."\n". ' '."\n". '
    '."\n". ' '."\n". '
    '."\n". '
     Next Game:'."\n". ''."$info[23]".''."\n". '
    '."\n". '

    '."\n". ''."$info[25]".''."\n". '

    '."\n". '

    Starting Lineup:

    '."\n". ''."$pStatHeader@line1$end".''."\n". '

    Line 2:

    '. '

    '."\n". ''."$pStatHeader@line2$end".''."\n".#start here '

    '."\n". '

    Line 3:

    '. '

    '."\n". ''."$pStatHeader@line3$end".''."\n". '

    '."\n". '

    Line 4:

    '. '

    '."\n". ''."$pStatHeader@line4$end".''."\n". '

    '."\n". '

    Goalies:

    '. '

    '."\n". ''."$gStatHeader@goalies$end".''."\n". '

    '."\n". '

    Reserves:

    '."\n". '

    '."\n". ''."$reservesMessage".''."\n". '

    '."\n". '

    Injured Reserve:

    '."\n". '
    '. ''."$injuryMessage".''."\n". '
    '. "Last updated $info[26]". '
    '."\n". ''."\n". ''."\n"; #~~~~~~~~~~~~~~ HTML ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Save the web page saveStats($teamFile, @buffer); } } ################# GET TEAM HTML INFO ################################## # This constructs a team info array for the team html pages. # # INPUT: String (team abr) # OUTPUT: Array (info) # [0] = team name abbr. # [1] = full name # [2] = conference # [3] = division # [4] = games # [5] = wins # [6] = loses # [7] = ties # [8] = points # [9] = win% # [10] = Goals For # [11] = Goals Against # [12] = Power Play Goals # [13] = PPM # [14] = PP% # [15] = PM # [16] = PK% # [17] = Owner Info # [18] = Address # [19] = Contact Info # [20] = Arena Name # [21] = Seating Capacity # [22] = Last Games Attendance # [23] = Next opponent w/ date # [24] = Last opponent w/ date & score # [25] = Lines are set flag # [26] = Date Compiled # DEPENDENCES: openFile, makeTeamNameHash, # EXAMPLE CALL: @info=getTeamHTMLInfo($team); # NOTE OF IMPORTANCE: . ######################################################################## sub getTeamHTMLInfo { my ($t) = @_; my @thisTeam; # Get the right teams info and thus 0-22 in array! my @team_array = openFile(TEAMS_DB); foreach(@team_array){ @thisTeam = split(/,/, $_); if (@thisTeam < 23){ print "ERROR - GET TEAM HTML INFO: The team info array is not ". "complete. \nThis program will now exit, please refer". " to the config_file_readme.txt \ndocumentation in this ". "foulder."; pc();exit; } last if ($thisTeam[0] eq $t); } # Now 23-24 my $foulder = SEASON_DIR; if ($PLAYOFF_MODE){ $foulder = PLAYOFF_DIR; } else { $foulder = SEASON_DIR; } my @filecontents=openFile("$foulder/schedule.html"); my ($date, $awayt, $homet, $ascore, $hscore, @fileLine); my $l_date = 0; my $l_awayt = 0; my $l_homet = 0; my $l_ascore = '-'; my $l_hscore = '-'; my $l_away = 0; my $season_has_ran = TRUE; #get this teams last name my %teams = makeTeamNameHash(); my $team = $teams{$t}; if($DBUG){ my ($p, $f, $l) = caller; print"---------- GET TEAM HTML INFO ----------\n"; print"$f Called from line $l\n"; print"----------------------------------------\n"; print"team: $team \n"; print"teams hash: \n"; printHash(%teams); } my $endtag = ''; for(my $i = 0; $i < (@filecontents - 1); $i++){ if ($filecontents[$i] =~ m//g){ $date = $filecontents[$i + 1]; $date =~ s/\n//g; $date =~ s/ //g; my $ignore = ''; $date =~ s/$ignore//g; $date =~ s/$endtag//g; $awayt = $filecontents[$i + 2]; $awayt =~ s/\n//g; $awayt =~ s/ //g; $awayt =~ s/$endtag//g; $homet = $filecontents[$i + 4]; $homet =~ s/\n//g; $homet =~ s/ //g; $homet =~ s/$endtag//g; $ascore = $filecontents[$i + 5]; $ascore =~ s/\n//g; $ascore =~ s/ //g; $ascore =~ s/$endtag//g; $ascore =~ s/ //g; $hscore = $filecontents[$i + 6]; $hscore =~ s/\n//g; $hscore =~ s/ //g; $hscore =~ s/$endtag//g; $hscore =~ s/ //g; if($DBUG){ print"ascore: $ascore \n"; print"hscore: $hscore \n"; print"l_ascore: $l_ascore \n"; print"l_hscore: $l_hscore \n"; print"l_awayt: $l_awayt \n"; print"l_homet: $l_homet \n"; print"----------------------------------------\n"; pc(); } # Check to see if we are on the edge of games played. if($ascore eq '-' || $hscore eq '-'){# End of played games if($l_ascore eq '-' || $l_hscore eq '-'){# start of season $thisTeam[23] = ""; $thisTeam[24] = 'None yet'; }else{ # last game exists if($l_ascore < $l_hscore){ # Win $thisTeam[24] = "Won $l_hscore to $l_ascore against ". "$l_awayt"; }elsif($l_ascore > $l_hscore){ # lost $thisTeam[24] = "Lost $l_hscore to $l_ascore against ". "$l_awayt"; }else{ # tie $thisTeam[24] = "Tie $l_hscore to $l_ascore against ". "$l_awayt"; } $season_has_ran = FALSE; } } if($season_has_ran && ($ascore ne '-' || $hscore ne '-')){ my $ht = ''; my $at = ''; my $ae = ''; my $he = ''; if($awayt eq $team){ $ht = $awayt; $at = $homet; $ae = $hscore; $he = $ascore; } else { $at = $awayt; $ht = $homet; $he = $hscore; $ae = $ascore; } if($ascore < $hscore){ # Win $thisTeam[24] = "Won $he to $ae against ". "$at"; }elsif($ascore > $hscore){ # lost $thisTeam[24] = "Lost $he to $ae against ". "$at"; }else{ # tie $thisTeam[24] = "Tie $he to $ae against ". "$at"; } } if($awayt eq $team){ $l_homet = $awayt; $l_awayt = $homet; $l_date = $date; $l_ascore = $hscore; $l_hscore = $ascore; $l_away = $teams{$homet}; } if ($homet eq $team){ $l_homet = $homet; $l_awayt = $awayt; $l_date = $date; $l_ascore = $ascore; $l_hscore = $hscore; $l_away = $teams{$awayt}; } if($awayt eq $team && ($ascore eq '-' || $hscore eq '-')){ $thisTeam[23] = "$date at $homet"; last; } if($homet eq $team && ($ascore eq '-' || $hscore eq '-')){ $thisTeam[23] = "$date Home game v.s. $awayt"; last; } if(@filecontents - 2){ $thisTeam[23] = "No games left"; } } } # Get index #25 if(inspectLines($t)){ $thisTeam[25] = "NOTICE: The lines are not set correctly!"; }else{ $thisTeam[25] = ''; } # Get index #26 my @today = getDate(); $thisTeam[26] = "$today[0]/$today[1]/$today[2]"; return @thisTeam; } ####################################################################### ################## GET TEAM STATS ##################################### # This subroutine constructs an array of lines in a db file that # are ssociated with a specific team.. # # INPUT: String (team abr). # String (p=teamDB, g=goalieDB). # OUTPUT: Array (db lines of specified team abr) # DEPENDENCES: makeTeamNameHash, openFile # EXAMPLE CALL: @array = getTeamStats($team); # NOTE OF IMPORTANCE: ####################################################################### sub getTeamStats { my ($t, $flag) = @_; my %teams = makeTeamNameHash(); # For error checking my $file; # File context (p or g) my @temp; # temp container my @tempLine; # temp container line my @tarray; # array to return my $TEAM_INDEX = 1; # to acess the team field # Error check if (($flag ne 'p' && $flag ne 'g') || (!exists $teams{$t})){ print "\nERROR - GET TEAM STATS: Arguments are invalid\n"; prompt_clear(1);exit; } # Set the file context and get stats if ($flag eq 'p'){$file = PLAYERS_DB}else{$file = GOALIES_DB} @temp = openFile($file); # Remove all but this team foreach (@temp){ @tempLine = split(/,/, $_); if ($tempLine[$TEAM_INDEX] eq $t){ push(@tarray, $_); } } return @tarray; } ####################################################################### ################## UPDATE TEAM PAGES ################################## # This subroutine will update data in a team html page. # # INPUT: String (team abr). # OUTPUT: Updated HTML pages # DEPENDENCES: # EXAMPLE CALL: updateTeamHTML($team); # NOTE OF IMPORTANCE: ####################################################################### sub updateTeamHTML { my ($t) = @_ ; my @info = getTeamHTMLInfo($t) ; my $teamFile = TEAM_DIR . "/$t" . '.html'; my @playerStats = openFile(SEASON_P_DB) ; # Players my @goalieStats = openFile(SEASON_G_DB) ; # Goalies my @teamsWebPage = openFile($teamFile) ; # Web page my @line1 = () ; # Line One Array my @line2 = () ; # Line Two Array my @line3 = () ; # Line Three Array my @line4 = () ; # Line Four Array my @goalies = () ; # Goalie Array my @reserves = () ; # Reserves Array my @injured = () ; # InjuredArray my @tempArray = () ; my $tempString = "" ; my $injuryMessage ; my $reservesMessage ; my $end = '
    ' ; # End of plyr stat # If free agents need updating ... just do it! if ($t eq FREE_AGENT) {makeFreeAgentPage();return;} # First lets make the Free agents page makeFreeAgentPage(); # Set up stat header for players my $pStatHeader = '

    '."\n". ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n"; # Set up stat header for goalies my $gStatHeader = '

    '."\n". '

    '."\n". '

    Games
    '."\n". '

    Points
    '."\n". '

    +/-
    '."\n". '

    Pen
    '."\n". '

    PPG
    '."\n". '

    SHG
    '."\n". '

    GWG
    '."\n". '

    GTG
    '."\n". '

    Shots
    '."\n". '

    Goals
    '."\n". '

    Assists
    '. "\n". ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n"; # Subroutine for inserting player lines (stats) !!!!!!!!!!!!!!!!!!!! sub insertP{ my(@p) = @_; # Player info array my $html; # HTML output $html= ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n"; return $html; } # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # Subroutine for inserting goalie lines (stats) !!!!!!!!!!!!!!!!!!!! sub insertG{ my(@p) = @_; # Player info array my $html; # HTML output $html= ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n"; return $html; } # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # get this teams players foreach my $p (@playerStats){ @tempArray = split(/,/, $p); if ($tempArray[1] eq $t){ $tempString = insertP(@tempArray); if($tempArray[9] == 1) { push (@line1, $tempString); }elsif($tempArray[9] == 2){ push (@line2, $tempString); }elsif($tempArray[9] == 3){ push (@line3, $tempString); }elsif($tempArray[9] == 4){ push (@line4, $tempString); }elsif($tempArray[9] == 5){ push (@reserves, $tempString); }else{ push (@injured, $tempString); } } } # get this teams goalies foreach my $plr (@goalieStats){ @tempArray = split(/,/, $plr); if ($tempArray[1] eq $t){ $tempString = insertG(@tempArray); push (@goalies, $tempString); } } # Check for injuries, if none ... nothing! if (@injured < 1){ $injuryMessage = "No current injured players."; }else{ $injuryMessage = "$pStatHeader@injured$end"; } # Check for reserves, if none ... nothing! if (@reserves < 1){ $reservesMessage = "No current players in reserve."; }else{ $reservesMessage = "$pStatHeader@reserves$end"; } # We have the info, now lets get the specified teams web page and # parse it into one big string. $tempString = EMPTY; foreach(@teamsWebPage){ $tempString = "$tempString$_"; } # Get data ready for insertion, then replace. #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ sub replace{ my($ifo, $flag, $string2replace) = @_; my @a = split(/$flag/, $string2replace); $a[1] = $ifo; $string2replace = join($flag, @a); return $string2replace; } #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ $tempString = replace($info[2], '', $tempString); $tempString = replace($info[1], '', $tempString); $tempString = replace($info[17], '', $tempString); $tempString = replace("$info[5] - $info[6] - $info[7]", '', $tempString); $tempString = replace($info[18], '', $tempString); $tempString = replace($info[10], '', $tempString); $tempString = replace(''.$info[19].'', '', $tempString); $tempString = replace($info[11], '', $tempString); $tempString = replace($info[20], '', $tempString); $tempString = replace("$info[15] min", '', $tempString); $tempString = replace($info[21], '', $tempString); $tempString = replace("$info[14]%", '', $tempString); $tempString = replace($info[22], '', $tempString); $tempString = replace($info[24], '', $tempString); $tempString = replace($info[23], '', $tempString); $tempString = replace($info[25], '', $tempString); $tempString = replace("$pStatHeader@line1$end", '', $tempString); $tempString = replace("$pStatHeader@line2$end", '', $tempString); $tempString = replace("$pStatHeader@line3$end", '', $tempString); $tempString = replace("$pStatHeader@line4$end", '', $tempString); $tempString = replace("$gStatHeader@goalies$end", '', $tempString); $tempString = replace("$reservesMessage", '', $tempString); $tempString = replace("$injuryMessage", '', $tempString); saveStats($teamFile, $tempString,); } ####################################################################### ############### m a k e f r e e a g e n t s h t m l ######### # Makes a free agents web page. # # INPUT: none # # OUTPUT: html updated page # # SAMPLE CALL: makeFreeAgentPage(); ######################################################################## sub makeFreeAgentPage { # Subroutine for inserting player lines (stats) !!!!!!!!!!!!!!!!!!!! sub insert_player{ my(@p) = @_; # Player info array my $html; # HTML output $html= ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n"; return $html; } # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # Subroutine for inserting goalie lines (stats) !!!!!!!!!!!!!!!!!!!! sub insert_goalie{ my(@p) = @_; # Player info array my $html; # HTML output $html= ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n"; return $html; } # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # Set up stat header for players my $pStatHeader =''. '

    Skaters

    '. '

    '."\n". '

    '."\n". '

    Games
    '."\n". '

    W
    '."\n". '

    L
    '."\n". '

    T
    '."\n". '

    Save%
    '."\n". '

    S
    '."\n". '

    GA
    '."\n". '

    GAA
    '."\n". '

    '."\n". '

    '."$p[0]".'

    '."\n". '

    '."$p[13]".'
    '."\n". '

    '."$p[2]".'
    '."\n". '

    '."$p[3]".'
    '."\n". '

    '."$p[4]".'
    '."\n". '

    '."$p[5]".'
    '."\n". '

    '."$p[6]".'
    '."\n". '

    '."$p[7]".'
    '."\n". '

    '."$p[8]".'
    '."\n". '

    '."$p[10]".'
    '."\n". '

    '."$p[11]".'
    '."\n". '

    '."$p[12]".'
    '."\n". '

    '."$p[0]".'

    '."\n". '

    '."$p[10]".'
    '."\n". '

    '."$p[4]".'
    '."\n". '

    '."$p[5]".'
    '."\n". '

    '."$p[6]".'
    '."\n". '

    '."$p[2]".'
    '."\n". '

    '."$p[7]".'
    '."\n". '

    '."$p[8]".'
    '."\n". '

    '."$p[9]".'
    '."\n". '

    '."\n". '

    '."$p[0]".'

    '."\n". '

    '."$p[13]".'
    '."\n". '

    '."$p[2]".'
    '."\n". '

    '."$p[3]".'
    '."\n". '

    '."$p[4]".'
    '."\n". '

    '."$p[5]".'
    '."\n". '

    '."$p[6]".'
    '."\n". '

    '."$p[7]".'
    '."\n". '

    '."$p[8]".'
    '."\n". '

    '."$p[10]".'
    '."\n". '

    '."$p[11]".'
    '."\n". '

    '."$p[12]".'
    '."\n". '

    '."$p[0]".'

    '."\n". '

    '."$p[10]".'
    '."\n". '

    '."$p[4]".'
    '."\n". '

    '."$p[5]".'
    '."\n". '

    '."$p[6]".'
    '."\n". '

    '."$p[2]".'
    '."\n". '

    '."$p[7]".'
    '."\n". '

    '."$p[8]".'
    '."\n". '

    '."$p[9]".'
    '."\n". '

    '."\n". ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n"; # Set up stat header for goalies my $gStatHeader =''. '

    '."\n". '

    '."\n". '

    Games
    '."\n". '

    Points
    '."\n". '

    +/-
    '."\n". '

    Pen
    '."\n". '

    PPG
    '."\n". '

    SHG
    '."\n". '

    GWG
    '."\n". '

    GTG
    '."\n". '

    Shots
    '."\n". '

    Goals
    '."\n". '

    Assists
    '. "\n". '

    Goalies

    '. ''."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ' '."\n". ''."\n"; # Get arrays. my @playerStats = openFile(SEASON_P_DB); # Players my @goalieStats = openFile(SEASON_G_DB); # Goalies # Get free agents my @freePAgents = (); # Player FE Array my @freeGAgents = (); # Goalie FE Array my @tempArray = (); # Temp Array my $tempString = ""; # Temp String push (@freePAgents, $pStatHeader); foreach my $pfe (@playerStats){ @tempArray = split(/,/, $pfe); if ($tempArray[1] eq FREE_AGENT){ $tempString = insert_player(@tempArray); push (@freePAgents, $tempString); } } push (@freeGAgents, $gStatHeader); foreach my $gfe (@goalieStats){ @tempArray = split(/,/, $gfe); if ($tempArray[1] eq FREE_AGENT){ $tempString = insert_goalie(@tempArray); push (@freeGAgents, $tempString); } } #~~~~~~~~~~~~~~ HTML ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ my @buffer = (); $buffer[0] =''. 'Free Agents'. ''. '

    Free Agents

    '. "@freePAgents@freeGAgents". ''; #~~~~~~~~~~~~~~ HTML ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Save the web page my $teamFile = TEAM_DIR . "/---" . '.html'; saveStats($teamFile, @buffer); } ############### F R E E A G E N T S ################################### # signs and releases free agents in the league. # # INPUT: none # # OUTPUT: changed files and an html page. # # DEPEND: openFile, prompt_clear, saveStats, teamsAvailable, # checkteam, teamsArray, printPlayersAvailable, # doesPlayerExist, updateTradesWebPage, openFileWIgnore, # debug, tabber, reinsertPlayer, makeTeamNameHash, # checkDir, pc. # # SAMPLE CALL: freeAgents(); ######################################################################## sub freeAgents { my @player_db = openFile(PLAYERS_DB); #Data Base Files my @goalie_db = openFile(GOALIES_DB); #Data Base Files my @player_ss = openFile(SEASON_P_DB);#Season Stats Files my @goalie_ss = openFile(SEASON_G_DB);#Season Stats Files my $team = EMPTY; #For interaction my $flag = FALSE; #flags that a trade finish my $answer = EMPTY; #For interaction my $p_db; my $g_db; my $p_ss; my $g_ss; ##################################################################### sub puddinpacker { my ($f, $tm, $pdb, $gdb, $pss, $gss) = @_; my $player = EMPTY; #For interaction my $trade_to = EMPTY; #For interaction my @playerdatabase = @$pdb; my @goaliedatabase = @$gdb; my @playerseasonbase = @$pss; my @goalieseasonbase = @$gss; while(1){ prompt_clear(0); printPlayersAvailable($tm); print "\nWhat is the players name --> "; $player = ; chomp $player; if ($DBUG) { print"player = $player\n"; print"pdb = $#playerdatabase\n"; print"gdb(#) = $#goaliedatabase\n"; } if ((doesPlayerExist($player, @playerdatabase)) ||(doesPlayerExist($player, @goaliedatabase))){ while(1){ prompt_clear(0); if ($tm eq FREE_AGENT){ teamsAvailable(); print "\nWhat team is $player going to --> "; $trade_to = ; chomp $trade_to; } else { $trade_to = FREE_AGENT; } if (checkTeam($trade_to, (teamsArray("___")))){ ### THE ACTUAL TRADE ############################# sub checkThis{ my ($tem, $plr, $tt, @argument) = @_; my @p = (); # For each line below my $ps = ""; # For the lines below foreach my $ps (@argument){ chomp $ps; @p = split(/,/, $ps); if ($p[0] eq $plr && $p[1] eq $tem){ $ps = reinsertPlayer($ps, $tt, 1); } $ps = "$ps\n"; } return @argument; } @playerdatabase = checkThis($tm, $player, $trade_to, @playerdatabase); @goaliedatabase = checkThis($tm, $player, $trade_to, @goaliedatabase); @playerseasonbase = checkThis($tm, $player, $trade_to, @playerseasonbase); @goalieseasonbase = checkThis($tm, $player, $trade_to, @goalieseasonbase); updateTradesWebPage($player, $tm, $trade_to); ################################################## #prompt_clear(1); $f = TRUE; return($f, $tm, \@playerdatabase, \@goaliedatabase, \@playerseasonbase, \@goalieseasonbase);#TO THE OUTSIDE print "\n$trade_to does not exist!\n"; prompt_clear(1); } } } else { print "\n$player does not exist!\n"; prompt_clear(1); } } } ##################################################################### while(1){ prompt_clear(0); if($flag){ print "\nDo you want to sign/release another (y or n) --> "; $answer = ; chomp $answer; if ($answer ne 'y'){ print "\nDo you want to save your choices (y or n) --> "; $answer = ; chomp $answer; if ($answer eq 'y'){ saveStats(PLAYERS_DB, @player_db); #Data Base Files saveStats(GOALIES_DB, @goalie_db); #Data Base Files saveStats(SEASON_P_DB, @player_ss); #Season Stats Files saveStats(SEASON_G_DB, @goalie_ss); #Season Stats Files #update the teams web pages my %teams = makeTeamNameHash(); # Each team and their name delete $teams{FREE_AGENT}; foreach my $t (keys %teams){updateTeamHTML($t);} last; } else { last; } } } prompt_clear(0); print "\nDo you want to sign or release a player (s or r)--> "; my $a= ; chomp $a; if ($a eq 'r'){ prompt_clear(0); teamsAvailable(); print "\nWhat team is the player on (choose from above) --> "; $team = ; chomp $team; } elsif ($a eq 's'){ $team = FREE_AGENT; } else { print "Bad selection ... goodbye!"; pc(); last; } if (checkTeam($team, (teamsArray("___")))){ if ($DBUG) { my ($package, $filename, $line) = caller; print"-------- FREE AGENTS: ------------\n"; print"package = $package\n"; print"filename = $filename\n"; print"line = $line\n"; print"-----------------------------------\n"; print"flag = $flag\n"; print"team = $team\n"; print"player_d(#) = $#player_db\n"; print"goalie_db(#) = $#goalie_db\n"; print"player_ss(#) = $#player_ss\n"; print"goalie_ss(#) = $#goalie_ss\n"; } ($flag, $team, $p_db, $g_db, $p_ss, $g_ss) = puddinpacker($flag, $team, \@player_db, \@goalie_db, \@player_ss, \@goalie_ss); @player_db = @$p_db; @goalie_db = @$g_db; @player_ss = @$p_ss; @goalie_ss = @$g_ss; if ($DBUG) { print"\nAFTER PUDDINPACKER:\n"; print"flag = $flag\n"; print"team = $team\n"; print"player_d(#) = $#player_db\n"; print"goalie_db(#) = $#goalie_db\n"; print"player_ss(#) = $#player_ss\n"; print"goalie_ss(#) = $#goalie_ss\n"; } } else { print "\n$team does not exist!\n"; prompt_clear(1); } } } ############### F R E E A G E N T S ################################### ############################### ############################## ############################### ### # # # ############################## #END SUBROUTINE SECTION######## # # # # # ############################## ############################### ### ### # ############################## ############################### # # # # # ############################## ############################### ### # # ### ############################## ############################### ############################## my @file_array = (PLAYERS_DB, GOALIES_DB, SEASON_P_DB, SEASON_G_DB); my $answer = "" ; my $dir = '' ; my $team ; my $run = TRUE; print"Initializing constants...........\n"; initializeConstants(); print"Making sure DB files are correct.\n"; DBFixer(@file_array); print"Checking the Season DBases.......\n"; checkDB(); print"Checking config file for modes...\n"; if ($PLAYOFF_MODE){ $dir = PLAYOFF_DIR; } else { $dir = SEASON_DIR; } print"Ready to start main loop.........\n"; while(1){ if($run && !$START){ print"Making HTML Today page...........\n"; makeHtmltodayPage(); $run = FALSE; } prompt_clear(0); print"Prompting for an answer..........\n"; prompt_clear(); if ($PLAYOFF_MODE){ # Playoffs getAnswer $answer = getPAnswer(); } elsif ($START){ # Start League getAnswer $answer = getSSAnswer(); } else { # Season getAnswer $answer = getSAnswer(); } print"Answer received ....TAKING ACTION\n"; if($answer eq "e" && !($PLAYOFF_MODE) && !($START)){################### leagueEdit(); prompt_clear(0); } elsif ($answer eq "e" && $PLAYOFF_MODE && !($START)){################ $team = getTeam("Name of"); if($team eq '1'){last}; print"\nType 'manual' for manual edit or 'auto' ". "for auto line set ==> "; my $editAnswer=; chomp $editAnswer; if ($editAnswer eq "m" || $editAnswer eq "manual"){ changeLines($team, 1); }elsif($editAnswer eq "a" || $editAnswer eq "auto"){ changeLines($team, 0); }else{ print"INVALID ANSWER\n"; } prompt_clear(0); } elsif ($answer eq "r" && !($START)){################################# prompt_clear(0); runGames(); updateNavHeader("rgm"); } elsif ($answer eq "s" && $START){#################################### startSeason(); prompt_clear(1); } elsif ($answer eq "p" && !($START) && !($PLAYOFF_MODE)){############# sorter(2, 11, SEASON_P_DB); # sort makePlayerHtmlStats(); # update print"Done\n"; prompt_clear(1); } elsif ($answer eq "q"){############################################## prompt_clear(0); last; } elsif ($answer eq "p" && $PLAYOFF_MODE){############################# prompt_clear(0); print "What team?\n". "(enter 't' for a list of available teams) --> "; my $team = ;chomp $team; # get team if ($team eq "t"){ teamsAvailable(); print "What team --> "; my $team = ;chomp $team; } if (!checkTeam($team, teamsArray("___"))){ # Does team exist? print "\n\nGAMESETUP:Team $team does not exist!\n\n"; prompt_clear(1); last; } printPlayersAvailable($team); prompt_clear(1); } elsif ($answer eq "n"){############################################### startNav("index.html"); } elsif ($answer eq "stand"){########################################### printStandings(); prompt_clear(1); } elsif ($answer eq "sched"){########################################### printSchedule(); prompt_clear(1); } elsif ($answer eq "player"){########################################## printScoringLeaders(); prompt_clear(1); } elsif ($answer eq "goalie"){########################################## printGoalieLeaders(); prompt_clear(1); } elsif ($answer eq "trades"){######################################### printTrades(); prompt_clear(1); } elsif ($answer eq "exit"){########################################### exit; } elsif ($answer eq "gig"){############################################ print"\nLog bug and press enter to save into a bug.txt file ==> "; my @bug = openFile("bug.txt"); my $b = ; push(@bug, $b); saveStats("bug.txt", @bug); } elsif ($answer eq "killseason"){##################################### killseason(); } elsif ($answer eq "debug"){##################################### $DBUG = 1; }else {print "Wrong input!\n";prompt_clear(1);} }
    '."\n". '

    '."\n". '

    Games
    '."\n". '

    W
    '."\n". '

    L
    '."\n". '

    T
    '."\n". '

    Save%
    '."\n". '

    S
    '."\n". '

    GA
    '."\n". '

    GAA
    '."\n". '