Compare commits

...

294 Commits

Author SHA1 Message Date
Kevin Rode
9888bcbb11
Removed test change 2021-01-28 20:08:31 -05:00
Kevin Rode
c6d1843ef0 Made a test change 2021-01-28 20:07:40 -05:00
Kevin Rode
c575c71096 Fixing team search 2021-01-17 16:44:31 -05:00
Kevin Rode
41812e786d Merge remote-tracking branch 'upstream/master' 2021-01-17 16:17:07 -05:00
Sakimori
d141c21433 fixed bye string sneaking into league 2021-01-17 15:48:21 -05:00
Sakimori
8d21e29fdd resolved gitignore conflict 2021-01-17 15:09:13 -05:00
Sakimori
5216d7a4d3 edited gitignore 2021-01-17 15:08:12 -05:00
Sakimori
e27354abe0
Merge pull request #163 from Sakimori/indev
fixed some home/away logic
2021-01-17 15:03:54 -05:00
Sakimori
74f3ac5c98 fixed some home/away logic 2021-01-17 15:01:05 -05:00
Sakimori
0e6cc6e464
Merge pull request #158 from Sakimori/indev
major website refactor, leagues update
2021-01-17 14:34:55 -05:00
Sakimori
e086980c44
Merge pull request #162 from Genderdruid/master
minor readme update with the new season flag for schedules
2021-01-16 18:40:40 -05:00
Sakimori
7809a9fecb Merge branch 'indev' of https://github.com/Sakimori/matteo-the-prestige into indev 2021-01-16 18:39:15 -05:00
Sakimori
012fad8850 corrected midseries restart check 2021-01-16 18:39:08 -05:00
Genderdruid
9a1fd5c553 Update README.md 2021-01-16 14:27:14 -08:00
Sakimori
29b299d8ff
Merge pull request #161 from jmaliksi/jm_157
Throw error if draft isn't formatted with new lines
2021-01-16 14:25:30 -05:00
joe
fca826df39 fix #157 2021-01-16 13:36:23 -05:00
Sakimori
c461c6cd39
Merge pull request #160 from esSteres/leagues
better error coverage
2021-01-16 01:33:24 -05:00
Elijah Steres
04f8c1bf2c fix deleted team error 2021-01-16 01:30:15 -05:00
Elijah Steres
b713de220e Merge remote-tracking branch 'upstream/indev' into leagues 2021-01-16 01:14:15 -05:00
Elijah Steres
49027b37c1 error checking all over 2021-01-16 01:13:12 -05:00
Sakimori
018c853be6 Merge branch 'indev' of https://github.com/Sakimori/matteo-the-prestige into indev 2021-01-16 01:10:02 -05:00
Sakimori
df7a12e19a fixed idolize commands not being stripped 2021-01-16 01:09:59 -05:00
Sakimori
a09653a7a6
Merge pull request #144 from Sakimori/leagues
leagues and stuff
2021-01-15 22:26:25 -05:00
Sakimori
7764e2ab32 disabled turbo mode 2021-01-15 22:08:52 -05:00
Sakimori
58797cf04c fixed postseason pause feature 2021-01-15 22:00:46 -05:00
Sakimori
62dbc6f533 tidyed up instructions for draft command 2021-01-15 20:27:58 -05:00
Sakimori
797e0da931 past season standings with -s flag 2021-01-15 20:15:52 -05:00
Sakimori
c4b4af2322
Merge pull request #156 from Sakimori/license-shenanigans
Delete LICENSE.md
2021-01-15 16:33:07 -05:00
Sakimori
7ab11dcebf
Rename LICENSE to LICENSE.md 2021-01-15 16:32:44 -05:00
Sakimori
6ccd88a7ba
Delete LICENSE.md 2021-01-15 16:32:18 -05:00
Sakimori
70dadfc971
Merge pull request #155 from Genderdruid/master
updated the readme with all the new commands in the patch
2021-01-15 16:31:27 -05:00
Genderdruid
ab909d7841 Update README.md 2021-01-15 13:30:16 -08:00
Sakimori
d96355c3f0 postseason pause flag 2021-01-15 16:30:11 -05:00
Sakimori
eead0c9309 finalized league ownership 2021-01-15 16:24:00 -05:00
Genderdruid
68a48b9441 Merge branch 'leagues' 2021-01-15 13:17:55 -08:00
Genderdruid
fa54536bfa Update README.md 2021-01-15 13:17:20 -08:00
Genderdruid
7bf35e656c Update README.md 2021-01-15 13:15:49 -08:00
Genderdruid
53e67d484a Update README.md 2021-01-15 13:13:29 -08:00
Sakimori
6cdfa1bd5b fixed handling on league claim 2021-01-15 16:08:39 -05:00
Sakimori
bac252b0be added league ownership commands 2021-01-15 16:06:52 -05:00
Sakimori
b2b790b3c9 fixed tourney days 2021-01-15 06:21:25 -05:00
Sakimori
780ca4b3bf changed some language to be more clear about what tournament rounds mean what 2021-01-15 06:18:29 -05:00
Sakimori
80aaa086fb fixed threshold for missed games 2021-01-15 06:08:52 -05:00
Sakimori
26ddaf7e5a adjusted some text in discord 2021-01-15 06:00:51 -05:00
Sakimori
363d58905e fixed titles on interrupted games 2021-01-15 05:54:06 -05:00
Sakimori
92034c185e fixed incrementation 2021-01-15 05:46:50 -05:00
Sakimori
6c30ccb88a fixed season length for real this time, started saving champs 2021-01-15 05:44:59 -05:00
Sakimori
9404ffd8fc fixed season length 2021-01-15 05:37:25 -05:00
Sakimori
a1a45ca805 fixed an f-string 2021-01-15 05:34:17 -05:00
Sakimori
3d2df59ca1 started recording season champions 2021-01-15 05:12:55 -05:00
Sakimori
016bc2ed24 set only one tournament to increment league day 2021-01-15 05:09:23 -05:00
Sakimori
fc07efa7ef tidyed up wait times for tournament games 2021-01-15 04:31:31 -05:00
Sakimori
af7112367d added m;leagueschedule 2021-01-15 04:27:20 -05:00
Sakimori
5eec52db62 made tournaments use rotations when leagues are assigned 2021-01-15 03:22:26 -05:00
Sakimori
e77e406470 adjusted tournaments to work on the same schedule system as leagues 2021-01-15 03:18:41 -05:00
Sakimori
8d6f6ab33a direct start to postseason, partial series support 2021-01-15 02:23:44 -05:00
Sakimori
19072f2111 implemented tiebreakers and postseason tournament 2021-01-15 02:12:30 -05:00
Sakimori
121d92885a
Merge pull request #151 from esSteres/leagues
fix numerical inputs in league options
2021-01-14 23:39:31 -05:00
Sakimori
333476548d standings and wildcard commands added 2021-01-14 23:39:08 -05:00
Elijah Steres
e184c91515 add history box to game page 2021-01-14 21:26:54 -05:00
Elijah Steres
5f6d8cc2ec fix numerical inputs in league options
also clean up some eslint warnings
2021-01-14 17:58:24 -05:00
Sakimori
6b56c87bef added handling for postseason constraints 2021-01-14 17:47:57 -05:00
Sakimori
ee55b00caf
Merge pull request #150 from esSteres/leagues
add create league link, use logos in link_div
2021-01-14 17:31:51 -05:00
Elijah Steres
96f272127c add create league link, use logos in link_div 2021-01-14 17:21:31 -05:00
Sakimori
60fe1da2ad
Merge pull request #149 from esSteres/leagues
Add create league page to site
2021-01-14 04:49:28 -05:00
Sakimori
4acaca0fb1 added the startleague command 2021-01-14 02:37:23 -05:00
Elijah Steres
c837a826c0 connect league create page to backend 2021-01-14 01:40:44 -05:00
Sakimori
b83bf771ca made leagues save properly after autoplaying 2021-01-14 00:37:58 -05:00
Sakimori
da8607e295 fixed some blocking bugs in startleague 2021-01-14 00:25:24 -05:00
Sakimori
5826574a1d startleague command attempt 2021-01-14 00:20:43 -05:00
Sakimori
3def1378a9 bugfixes for veil and twilight, changed veil text and emoji 2021-01-13 23:21:28 -05:00
Sakimori
ae256de645 implemented thinned veil and twilight weathers 2021-01-13 22:34:46 -05:00
Sakimori
22115ee2c3 closed #142 2021-01-13 20:55:12 -05:00
Sakimori
c141c0a02f
Merge pull request #147 from xSke/leagues
Update Dockerfile for frontend build
2021-01-13 20:46:25 -05:00
Elijah Steres
8f610eaa2e Merge branch 'create-league' into leagues 2021-01-13 20:20:50 -05:00
Sakimori
cbcb950d78 implemented league saving and loading 2021-01-13 19:20:58 -05:00
Genderdruid
d5bc2200da Merge branch 'leagues' 2021-01-13 15:59:35 -08:00
Sakimori
a330290712
Merge pull request #148 from esSteres/leagues
fix inning arrow not updating
2021-01-13 16:34:42 -05:00
Elijah Steres
2b0aadd34f fix inning arrow not updating 2021-01-13 16:18:43 -05:00
Sakimori
cfd4af5f7c
added another patron 2021-01-13 15:27:59 -05:00
Astrid
1189fb219a Update Dockerfile for frontend build 2021-01-13 12:56:00 +01:00
Sakimori
8255d838e5 got leagues actually functioning, i think 2021-01-13 06:32:28 -05:00
Sakimori
0349f45394 fixed an unresolved import 2021-01-13 04:33:42 -05:00
Sakimori
b6e4c1069c lots of league database foundation 2021-01-13 04:23:48 -05:00
Sakimori
c407722166
Merge pull request #139 from esSteres/react
Rebuild frontend in react
2021-01-13 02:07:36 -05:00
Sakimori
ac2f303936
switched to gpl3 2021-01-12 15:36:56 -05:00
Elijah Steres
ab488c331a add more option fields 2021-01-12 13:16:31 -05:00
Elijah Steres
39e30c3811 finish league create page 2021-01-12 03:17:02 -05:00
Elijah Steres
1337df4af3 fix weird gap 2021-01-11 16:11:35 -05:00
Elijah Steres
74c9da684f change to using fetch over jquery 2021-01-11 14:14:54 -05:00
Sakimori
df09a2cf97 added standings to league object and began collecting them from prestige.py 2021-01-11 06:36:13 -05:00
Sakimori
31930aab63 this should add all the infrastructure needed to run a league's games (and only *run* them, no data yet). untested 2021-01-11 06:17:14 -05:00
Elijah Steres
c3a35c07a4 work on team search 2021-01-10 23:47:49 -05:00
Elijah Steres
72edbf5022 make league structure 2021-01-10 01:27:30 -05:00
Elijah Steres
a9cd89d5ce Merge branch 'react' of https://github.com/esSteres/matteo-the-prestige into react 2021-01-10 01:23:31 -05:00
Elijah Steres
31acd0ceed organize things and switch to using /game/:id over /game?id= 2021-01-10 01:18:37 -05:00
esSteres
0ce37e37d9
Merge branch 'indev' into react 2021-01-09 20:35:28 -05:00
Kevin Rode
c7c675fd07 Merge remote-tracking branch 'upstream/master' 2021-01-09 16:02:41 -05:00
Sakimori
20a13fdf2e
added another patron 2021-01-09 11:55:58 -05:00
Sakimori
4099c0fafc
Merge pull request #143 from Sakimori/indev
Indev
2021-01-08 22:22:03 -05:00
Sakimori
7e3b1d353f fixed an error oops 2021-01-08 13:56:36 -05:00
Sakimori
c04e96f8f5 Merge branch 'indev' of https://github.com/Sakimori/matteo-the-prestige into indev 2021-01-08 13:55:59 -05:00
Sakimori
0a1f1a9e73 added connection closing statements to most database.py functions 2021-01-08 13:55:52 -05:00
Sakimori
049c605f83
Merge pull request #140 from Genderdruid/master
a few minor text updates to the readme and help text
2021-01-08 13:18:34 -05:00
Genderdruid
ad6cc90e82 Update the_prestige.py 2021-01-08 10:15:50 -08:00
Genderdruid
d34efcad4b a few minor text updates 2021-01-08 10:10:01 -08:00
Elijah Steres
013d1e0585 move typsecript libs to dev deps 2021-01-08 11:03:11 -05:00
Elijah Steres
2cad62eda4 Merge remote-tracking branch 'upstream/indev' into react 2021-01-08 00:44:31 -05:00
Elijah Steres
5dd57c0f2a use Link instead of a for share link 2021-01-08 00:39:24 -05:00
Elijah Steres
0157ea3122 React conversion DONE! 2021-01-08 00:29:39 -05:00
Sakimori
8b9d5c2723 Merge branch 'indev' of https://github.com/Sakimori/matteo-the-prestige into indev 2021-01-07 22:37:13 -05:00
Sakimori
e6a1100b5e fixed tailwind only applying to batters with more than 5 stars 2021-01-07 22:37:04 -05:00
Kevin Rode
00f918ea17 fuzzy search not searching team #11 2021-01-07 20:47:35 -05:00
Kevin Rode
cdf15ce46b Removed debugs for #10 2021-01-07 20:40:25 -05:00
Kevin Rode
13f8003859 Debugging for #10 2021-01-07 20:34:15 -05:00
Sakimori
65546bd239
added another patreon sub 2021-01-07 20:01:53 -05:00
Sakimori
43d6b08961 changed "home run" to "dinger" 2021-01-07 19:27:12 -05:00
kevroded
8c861d1651 Fixes #9 2021-01-07 22:58:46 +00:00
Elijah Steres
09b90cf445 add grid filling 2021-01-07 16:22:39 -05:00
Elijah Steres
364834befa more progress, switch to using hooks over classes 2021-01-07 06:33:44 -05:00
Elijah Steres
486ba1f200 it works! (feature parity coming soon™️) 2021-01-07 03:10:53 -05:00
Sakimori
5d7d28445d
Merge pull request #113 from jmaliksi/jm_the_draft_1
merging draft feature into indev; want some more testing but looks *very* good
2021-01-06 21:01:41 -05:00
kevroded
ae81961428 Merge remote-tracking branch 'upstream/master' 2021-01-06 20:47:54 -05:00
joe
97546d7be5 erroneous merge 2021-01-06 17:45:39 -08:00
joe
c15f500058 Final tweaks 2021-01-06 17:42:33 -08:00
joe
c65d81a5e6 fix help text 2021-01-06 17:42:33 -08:00
joe
b76c7de8bc text tweaks 2021-01-06 17:42:33 -08:00
joe
b17d3a3042 pitcher fix 2021-01-06 17:42:33 -08:00
joe
ba70ac4f31 some fixes 2021-01-06 17:42:33 -08:00
joe
56a1b06d28 rebase latest master 2021-01-06 17:42:33 -08:00
joe
5bc2c520ea discord commands 2021-01-06 17:41:52 -08:00
joe
996d35ec06 more whitepace handling 2021-01-06 17:41:52 -08:00
joe
e22a1b3345 filter bookmark out of teams 2021-01-06 17:41:52 -08:00
joe
2718f79c19 Draft controller class 2021-01-06 17:41:52 -08:00
kevroded
8ce9bb5e84 Fixes #7 2021-01-06 20:38:39 -05:00
kevroded
ff867b541c Added ability to pull weather information from db for game history 2021-01-06 20:35:37 -05:00
Sakimori
e733059ac1
Merge pull request #137 from Sakimori/master
bring indev into line with master re: security patch
2021-01-06 20:00:28 -05:00
Sakimori
e4cf9f584e
Merge pull request #133 from xSke/resilience-fixes
Resilience fixes
2021-01-06 19:58:18 -05:00
Sakimori
f60da215e3
added new supporter 2021-01-06 19:57:53 -05:00
Sakimori
5aa1ae4b7b
Merge pull request #135 from esSteres/indev
forgot about leagues, whoops
2021-01-06 15:23:31 -05:00
Elijah Steres
c931733ad1 forgot about leagues, whoops 2021-01-06 15:20:46 -05:00
Sakimori
af657d3be2
Merge pull request #134 from esSteres/indev
(URGENT) Fix js injection vulnerability
2021-01-06 14:36:01 -05:00
Elijah Steres
eb2c5797cb Fix js injection vulnerability 2021-01-06 14:14:19 -05:00
Elijah Steres
1f15811170 add react 2021-01-06 14:05:58 -05:00
kevroded
957c11c60d Moved DB update command to limit duplicate entries 2021-01-06 12:24:59 -05:00
Astrid
1d3ac175e3 Add WAL files to .gitignore 2021-01-06 12:04:44 +01:00
Astrid
e44ce70a1c Use sqlite3 write-ahead log 2021-01-06 12:03:52 +01:00
Astrid
47b5788a09 Store bot data in a data/ directory 2021-01-06 11:53:51 +01:00
Sakimori
9df80e0095
Merge pull request #132 from Sakimori/indev
cleaned up a comment
2021-01-06 02:27:37 -05:00
Sakimori
2c638970de cleaned up a comment 2021-01-06 02:27:04 -05:00
Sakimori
933c642dc4
Merge pull request #131 from Sakimori/indev
1/5/2021 hotfix
2021-01-06 02:00:59 -05:00
kevroded
8044c1cae7 New attempt to fix game history saving multiple times 2021-01-06 01:24:03 -05:00
kevroded
97f125c55e Moved db statement to remove duplicate saves 2021-01-06 01:05:37 -05:00
kevroded
3c93d1e4c8 fixed db error 2021-01-06 00:46:51 -05:00
kevroded
3e8f5c46d3 Fixed cache_history 2021-01-06 00:26:27 -05:00
kevroded
f8b5480cfa debug removed weather info should be getting saved to the DB 2021-01-06 00:19:31 -05:00
kevroded
9a5162a448 Updated debug message 2021-01-06 00:12:46 -05:00
kevroded
8444e5b07a Fixed commented out line 2021-01-06 00:04:14 -05:00
kevroded
bd25fae829 debugging staement added 2021-01-06 00:02:46 -05:00
kevroded
e9abc7befd First try at adding weather to game history command 2021-01-05 23:52:23 -05:00
Kevin Rode
9f6f74f1e9 Updated readme fixes #8 2021-01-05 20:47:22 -05:00
Kevin Rode
6a1ff1d352 Merge branch 'master' of https://github.com/kevroded/matteo-the-prestige 2021-01-05 20:38:19 -05:00
Kevin Rode
120496f66b Readded commands to save game history 2021-01-05 20:38:02 -05:00
Sakimori
aff7c88775 Merge branch 'indev' of https://github.com/Sakimori/matteo-the-prestige into indev 2021-01-05 17:30:00 -05:00
Sakimori
9b7038990f strip trailing spaces from team name and slogan 2021-01-05 17:28:45 -05:00
Sakimori
d2461cf81b
Create LICENSE.md
added the attribution-noncommercial-sharealike 4.0 international license to simsim
2021-01-05 17:03:48 -05:00
Sakimori
0a1ce24853 Merge branch 'indev' of https://github.com/Sakimori/matteo-the-prestige into indev 2021-01-05 15:31:57 -05:00
Sakimori
84cb16ab5d added --bestof and --finalsbestof flags to tournament 2021-01-05 15:31:50 -05:00
Sakimori
5eee2f4d0e
Merge pull request #130 from esSteres/indev
missed a merge conflict riv
2021-01-05 15:28:51 -05:00
Elijah Steres
3b1a9d2548 missed a merge conflict riv 2021-01-05 15:25:12 -05:00
Sakimori
55f589dde1 adjusted the mulligan curve 2021-01-05 15:18:18 -05:00
Sakimori
ccd7702db8
Merge pull request #127 from jmaliksi/jm_fix_imports
Fix onomancer import
2021-01-05 14:29:36 -05:00
Sakimori
803f633a9e changed timestamp to uuid strings, adjusted variable names in the_prestige and main_controller 2021-01-05 14:26:54 -05:00
joe
60196929fd erroneous not 2021-01-05 09:15:54 -08:00
joe
56fbe809c7 fix onomancer import with add_pitcher 2021-01-05 09:09:41 -08:00
kevroded
178a414846 Updated base.html 2021-01-05 11:56:41 -05:00
Sakimori
8d01a3cc79
Merge pull request #125 from esSteres/dynamic-grid
Dynamic grid column count
2021-01-05 01:48:29 -05:00
Elijah Steres
bfd7a8065d Merge remote-tracking branch 'upstream/indev' into dynamic-grid 2021-01-05 00:51:23 -05:00
Elijah Steres
4a8285ca9f fixes and tweaks 2021-01-05 00:26:33 -05:00
Sakimori
74a205fe74
Merge pull request #124 from esSteres/indev
fix game page getting squashed on mobile
2021-01-05 00:05:37 -05:00
Eli
b31b19ea05 make grid columns dynamically adjust to screen size 2021-01-04 23:39:24 -05:00
Elijah Steres
e37abb55a1 fix game page getting squashed on mobile 2021-01-04 22:55:53 -05:00
Kevin Rode
4cf5e48910 Removed weather counts as they are not used 2021-01-04 22:51:22 -05:00
Kevin Rode
6ebea65a93 Reverting fuzzy select 2021-01-04 22:39:58 -05:00
Kevin Rode
14e4b5db6f Fixed debug messages? 2021-01-04 22:32:41 -05:00
Kevin Rode
ad85e92511 debug 2021-01-04 22:31:12 -05:00
Kevin Rode
c12a167795 () 2021-01-04 22:30:24 -05:00
Kevin Rode
aa5b4b0c14 Needs more debug 2021-01-04 22:29:45 -05:00
Kevin Rode
b7853200da more debug 2021-01-04 22:25:13 -05:00
Kevin Rode
d669c90de3 debugging 2021-01-04 22:23:26 -05:00
Kevin Rode
c5abae79eb Added fuzzy search back 2021-01-04 22:16:57 -05:00
Kevin Rode
2d5458904a Re added tournament command 2021-01-04 22:05:29 -05:00
Kevin Rode
ceb2a2ad11 Merge remote-tracking branch 'upstream/master' 2021-01-04 22:02:33 -05:00
Sakimori
d331338d93 stopped games printing end-card 1 update too soon 2021-01-04 20:35:59 -05:00
Sakimori
ebaef8828c
Merge pull request #123 from Sakimori/indev
fixed random game end cards for real this time (probably)
2021-01-04 20:26:25 -05:00
Sakimori
6235564622 fixed random game end cards for real this time (probably) 2021-01-04 20:23:32 -05:00
Sakimori
6eec667370
Merge pull request #120 from Sakimori/indev
patch to fix game endcards
2021-01-04 19:56:24 -05:00
Sakimori
759f274efc Merge branch 'indev' of https://github.com/Sakimori/matteo-the-prestige into indev 2021-01-04 19:42:51 -05:00
Sakimori
5cb23c87df games will stay on "play blall" for a shorter time 2021-01-04 19:42:42 -05:00
Sakimori
fd249efb39
Merge pull request #122 from esSteres/hotfix
Hotfix safari mobile display
2021-01-04 18:14:07 -05:00
Elijah Steres
ae9b831151 Merge remote-tracking branch 'upstream/indev' 2021-01-04 17:59:23 -05:00
Elijah Steres
808712a7c7 fix safari display, maybe 2021-01-04 17:57:13 -05:00
Sakimori
772aa2f770 deletes tournament setup message, ensures more than 1 team in a tournament 2021-01-04 16:17:55 -05:00
Sakimori
32136b51dc added error message to addplayer if pitcher/batter is not specified 2021-01-04 15:45:30 -05:00
Sakimori
b4202a1a46 fixes bug #118 2021-01-04 15:37:53 -05:00
Sakimori
5870325254 Merge branch 'indev' of https://github.com/Sakimori/matteo-the-prestige into indev 2021-01-04 15:24:44 -05:00
Sakimori
5f5ee9e1f0 fixed bug in game_watcher, added game_freeze check to tournament and randomgame 2021-01-04 15:24:19 -05:00
Sakimori
27c1a787d1
Merge pull request #115 from Sakimori/indev
push indev branch to live on 1/4/2021
2021-01-04 13:38:11 -05:00
Sakimori
c5392d000c
Merge pull request #117 from Genderdruid/master
updated the readme and the help commands to keep them consistent when…
2021-01-04 13:03:37 -05:00
Genderdruid
4e9e02ba12 updated the readme and the help commands to keep them consistent when it makes sense 2021-01-04 08:42:02 -08:00
Kevin Rode
7f1fb0282c
Update README.md 2021-01-04 03:08:12 -05:00
Kevin Rode
8aefab625f
Update README.md 2021-01-04 03:07:34 -05:00
Kevin Rode
9e9129a462 Spelling and Fixes #2 2021-01-04 03:04:47 -05:00
Kevin Rode
e35078820a spelling 2021-01-04 03:02:56 -05:00
Kevin Rode
98409fd6c6 First try at Game History Embed 2021-01-04 03:01:51 -05:00
Kevin Rode
a89aed6f75 Selecting from the correct table helps 2021-01-04 02:43:27 -05:00
Kevin Rode
04f61470fa Fixed get_history command in database 2021-01-04 02:42:15 -05:00
Kevin Rode
ebd44c6d3c Please 2021-01-04 02:40:54 -05:00
Kevin Rode
199f938e38 It is late and I make typos 2021-01-04 02:39:22 -05:00
Kevin Rode
055f7db17e Debugging get_history 2021-01-04 02:36:53 -05:00
Kevin Rode
f5cb646087 Moved db save command to the right spot 2021-01-04 02:17:39 -05:00
Kevin Rode
6393f006e8 Save game history to table in database 2021-01-04 02:12:46 -05:00
Kevin Rode
1acf56d1b9
Update README.md 2021-01-04 01:48:57 -05:00
Sakimori
3899041536
Merge pull request #116 from Genderdruid/master
Updated the readme with all the features of the new patch and cleaned up some other parts
2021-01-04 00:57:51 -05:00
Genderdruid
5200ce687c Merge branch 'indev' 2021-01-03 21:46:23 -08:00
Genderdruid
6e403a0d1e Merge branch 'indev' of https://github.com/Sakimori/matteo-the-prestige into indev 2021-01-03 21:45:57 -08:00
Genderdruid
7a4f8d1f0f Update README.md 2021-01-03 21:45:49 -08:00
Sakimori
864c1af655 made day=1 give first pitcher, not second 2021-01-03 23:43:04 -05:00
Sakimori
ee11aca3c0 added a -d or --day flag to force rotation slots in games 2021-01-03 23:41:31 -05:00
Sakimori
6e69117e62
Merge pull request #114 from Sakimori/leagues
implements tournaments and a foundation for leagues
2021-01-03 23:23:16 -05:00
Sakimori
f391577792
Merge branch 'indev' into leagues 2021-01-03 23:23:02 -05:00
Sakimori
ff582d8709 finished implementing tournaments, slowed game ticks to 8 seconds 2021-01-03 23:18:45 -05:00
Kevin Rode
ddc74fea97 Added bird emoji for Crowstorm 2021-01-03 23:14:03 -05:00
Kevin Rode
73ab5572ec Fixes #4 2021-01-03 23:05:27 -05:00
Kevin Rode
eac1e66395 Removed debug text 2021-01-03 23:01:13 -05:00
Kevin Rode
aff8f71130 fixed static cast? 2021-01-03 22:59:25 -05:00
Kevin Rode
0db17ce838 needs more debug 2021-01-03 22:57:57 -05:00
Kevin Rode
e73810024f float not int 2021-01-03 22:57:07 -05:00
Kevin Rode
420f1a62ab Remove debug line 2021-01-03 22:56:14 -05:00
Kevin Rode
cbb30cb2e9 Fixing weird json things 2021-01-03 22:55:51 -05:00
Kevin Rode
779e6058f0 debug,debug,debug... 2021-01-03 22:53:54 -05:00
Kevin Rode
e3f7bc6703 Added debug messages 2021-01-03 22:52:27 -05:00
Kevin Rode
f5af4515a9 fixed else if 2021-01-03 22:51:25 -05:00
Kevin Rode
190790a1af Added vibe lookup 2021-01-03 22:49:46 -05:00
Kevin Rode
19b6d0649e reboved dug messages 2021-01-03 22:28:57 -05:00
Kevin Rode
2cd3397970 or should be used not and 2021-01-03 22:25:46 -05:00
Kevin Rode
f502073e02 Still trying to fix crows 2021-01-03 22:16:46 -05:00
Kevin Rode
22751876b9 I am not smart 2021-01-03 22:12:01 -05:00
Kevin Rode
3cc53d453b Please work crows 2021-01-03 22:07:48 -05:00
Kevin Rode
b6f4bf6396 Fixed crow percent chance brackets 2021-01-03 21:59:55 -05:00
Kevin Rode
0709acf48a FC_flag added to crows 2021-01-03 21:56:45 -05:00
Kevin Rode
6220d8d5ae weather updated to maybe work 2021-01-03 21:53:38 -05:00
Kevin Rode
ad7353270e debugging 2021-01-03 21:49:17 -05:00
Kevin Rode
5e65d33379 Crow not Crows 2021-01-03 21:43:47 -05:00
Kevin Rode
d57aa9ccd8 Variables are hard 2021-01-03 21:41:29 -05:00
Kevin Rode
78165853fd I am a fool...a bufffoon 2021-01-03 21:40:02 -05:00
Kevin Rode
383cc7ccda Implimented Crows...maybe 2021-01-03 21:37:40 -05:00
Kevin Rode
3ca24b313a New weather effects added I really hope this is working 2021-01-03 20:49:51 -05:00
Sakimori
a2a6e9d7bb added m;randomgame 2021-01-03 17:59:13 -05:00
Genderdruid
56b5d9f45f Update README.md 2021-01-03 14:28:11 -08:00
Sakimori
63db3ba1be added handling for teams without slogans 2021-01-03 17:16:05 -05:00
Sakimori
1838e9198a added weather to discord embed at end of game 2021-01-03 16:57:41 -05:00
Sakimori
5e00d0d271 moved the team fuzzy searching to a get_team_fuzzy_search for ease of coding 2021-01-03 16:48:51 -05:00
Genderdruid
cb167e2464 Merge branch 'indev' 2021-01-03 13:35:45 -08:00
Genderdruid
604ea598ec Merge branch 'indev' of https://github.com/Sakimori/matteo-the-prestige into indev 2021-01-03 13:35:22 -08:00
Genderdruid
7191e3ca8c Update README.md 2021-01-03 13:35:09 -08:00
Sakimori
5697c5dbb3 got leagues up to date with indev 2021-01-03 16:33:45 -05:00
Sakimori
92cd4a1858 Merge branch 'indev' of https://github.com/Sakimori/matteo-the-prestige into indev 2021-01-03 16:30:01 -05:00
Sakimori
222d2f2fba fixed some inconsestencies with new commands 2021-01-03 16:29:56 -05:00
Genderdruid
ba25fdd7ed Merge branch 'indev' 2021-01-03 12:30:26 -08:00
Genderdruid
4b0932427f Merge branch 'indev' of https://github.com/Sakimori/matteo-the-prestige into indev 2021-01-03 12:29:32 -08:00
Sakimori
d78de96ad4
Merge pull request #112 from esSteres/indev
Fix a css thing I didn't notice because RIV browser cache
2021-01-03 15:27:01 -05:00
Elijah Steres
088671096d Merge remote-tracking branch 'upstream/indev' into indev 2021-01-03 15:25:44 -05:00
Elijah Steres
1eaa1d3cd8 css fixes x_x 2021-01-03 15:24:50 -05:00
Sakimori
0cba1156e4
Merge pull request #111 from esSteres/indev
Add title field
2021-01-03 15:12:26 -05:00
Elijah Steres
f91de92ed2 Merge remote-tracking branch 'upstream/indev' into indev 2021-01-03 15:10:02 -05:00
Elijah Steres
c670c8a1a2 css changes and add title field 2021-01-03 15:09:31 -05:00
Sakimori
2c14d7cf73 added win values to debug tourney to test win seeding 2021-01-03 06:56:40 -05:00
Sakimori
527170a81e fixed tournament blocking everything else 2021-01-03 06:30:07 -05:00
Sakimori
d5f2ceeac9 set max innings of debug tournament round to 3 for faster testing 2021-01-03 06:09:27 -05:00
Sakimori
12255e3eef m;starttournament now starts a debug tournament 2021-01-03 06:06:51 -05:00
Sakimori
1f1b215d02 changed background image for accessibility purposes 2021-01-03 04:14:05 -05:00
Sakimori
f16cee6f84 added error messages to not enough lines on new commands 2021-01-03 03:55:03 -05:00
Sakimori
28dca13f53 moved league work to new branch in case not ready for monday release 2021-01-03 03:51:45 -05:00
kevroded
57e7847f5a Removed db backup 2021-01-03 06:29:02 +00:00
Sakimori
22150033ca started implementing bracket generation 2021-01-03 01:04:51 -05:00
Genderdruid
ccac199304 Update README.md 2021-01-02 21:47:38 -08:00
Genderdruid
14adf8ab1e Update README.md 2021-01-02 21:42:05 -08:00
Elijah Steres
1b2544cc4b my life is an endless series of one-line css changes now 2021-01-02 21:41:00 -05:00
Sakimori
cda703bfae
Merge pull request #105 from esSteres/indev
Use twemoji (for #94)
2021-01-02 18:13:15 -05:00
Elijah Steres
cd242c0b2b Merge remote-tracking branch 'upstream/indev' into indev 2021-01-02 17:38:11 -05:00
Elijah Steres
5abd7f2c3a use twemoji instead of raw unicode 2021-01-02 17:36:19 -05:00
kevroded
9e51ffc247 Updated with configuration changes for FredChat 2021-01-02 22:02:23 +00:00
Elijah Steres
6e999bae44 Merge remote-tracking branch 'upstream/indev' into indev 2021-01-02 11:53:18 -05:00
61 changed files with 21968 additions and 844 deletions

Binary file not shown.

6
.dockerignore Normal file
View File

@ -0,0 +1,6 @@
venv/
matteo_env/
__pycache__/
simmadome/node_modules
data/
.git/

9
.gitignore vendored
View File

@ -344,7 +344,16 @@ config.json
games_config.json games_config.json
weather_config.json weather_config.json
ids ids
data/
# database # database
matteo.db matteo.db
matteo.db-wal
matteo.db-shm
/data/leagues/*
/matteo_env/Lib/site-packages/flask_socketio/__init__.py /matteo_env/Lib/site-packages/flask_socketio/__init__.py
Pipfile
*_bak
env
/data/leagues
/simmadome/build

View File

@ -1,9 +1,20 @@
FROM python:3.8 # - Build stage 1: frontend (simmadome/ directory)
EXPOSE 5000 FROM node:alpine AS frontend
WORKDIR /app WORKDIR /app
COPY . ./ COPY simmadome/package.json simmadome/package-lock.json ./
RUN npm install
COPY simmadome/ ./
RUN npm run build
# - Build stage 2: backend (Python)
FROM python:3.8
EXPOSE 5000
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt RUN pip install -r requirements.txt
COPY . ./
COPY --from=frontend /app/build/ simmadome/build/
CMD ["python", "the_prestige.py"] CMD ["python", "the_prestige.py"]

674
LICENSE.md Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

13
Makefile Normal file
View File

@ -0,0 +1,13 @@
SOURCES = $(wildcard ./simmadome/src/*) $(wildcard ./simmadome/public/*)
OUTPUTS = $(wildcard ./simmadome/build/*)
.PHONY: run frontend
run: $(OUTPUTS)
python3 the_prestige.py
frontend:
(cd simmadome && npm run build)
$(OUTPUTS): $(SOURCES)
(cd simmadome && npm run build)

136
README.md
View File

@ -1,35 +1,121 @@
# A simsim fork for the FredChat
This fork changes small things about the bot to better fit in in the FredChat discord. The official readme can be seen below and a summary of changes is viewable directly below this
- Removes almost all references to Matteo as that is not the name of the bot user
- Adds in new weather effects
- Adds the help command as the bot's status
- Shows a players vibes when requesting their stats
- Updated the credit command to credit Sakimori and SIBR instead of the pfp artist as the original profile pic is not being used
- Game history with weather can be viewed in the same style embed as showallteams
- Merged in commits to utilize the website
# matteo-the-prestige # matteo-the-prestige
# simsim discord bot # simsim discord bot
blaseball, blaseball, is back! in an unofficial capacity. this is completely unaffiliated with the game band blaseball, blaseball, is back! in an unofficial capacity. this project is completely unaffiliated with the game band.
custom players, custom teams, custom leagues (that last one is coming soon™) all set up in discord and watchable at https://simsim.sibr.dev we have custom players (generated by onomancer), custom teams, custom leagues, all set up in discord and watchable at https://simsim.sibr.dev!
we've also got things like custom team creation, easy setup for your teams to play against each other, and player idolization, all powered by this bot and onomancer. if you would like to add matteo to your server to be able to set up teams and games, you can do so with this link: https://discord.com/api/oauth2/authorize?client_id=789956166796574740&permissions=388160&scope=bot
accepting pull requests, check the issues for to-dos. accepting pull requests, check the issues for to-dos.
## commands: (everything here is case sensitive, and can be prefixed with either m; or m!) ## commands: (everything here is case sensitive, and can be prefixed with either m; or m!)
### team commands: ### team commands:
#### creation and deletion:
- m;saveteam - m;saveteam
- saves a team to the database allowing it to be used for games. send this command at the top of a list, with entries separated by new lines (shift+enter in discord, or copy+paste from notepad). - saves a team to the database allowing it to be used for games. use this command at the top of a list with entries separated by new lines:
- the first line of the list is your team's name (cannot contain emoji). - the first line of the list is your team's name.
- the second line is your team's icon and slogan, this should begin with an emoji followed by a space, followed by a short slogan. - the second line is the team's icon and slogan, generally this is an emoji followed by a space, followed by a short slogan.
- the third line must be blank.
- the next lines are your batters' names in the order you want them to appear in your lineup, lineups can contain any number of batters between 1 and 12. - the next lines are your batters' names in the order you want them to appear in your lineup, lineups can contain any number of batters between 1 and 12.
- the final line is your pitcher's name. - then another blank line seperating your batters and your pitchers.
- if you did it correctly, you'll get a team embed with a prompt to confirm. hit the 👍 and it'll be saved. - the final lines are the names of the pitchers in your rotation, rotations can contain any number of pitchers between 1 and 8.
- if you did it correctly, you'll get a team embed with a prompt to confirm. hit the 👍 and your team will be saved!
- m;deleteteam [teamname] \(requires team ownership)
- allows you to delete the team with the provided name. you'll get an embed with a confirmation to prevent accidental deletions. hit the 👍 and your team will be deleted.
- m;import
- imports an onomancer collection as a new team. you can use the new onomancer simsim setting to ensure compatibility. similarly to saveteam, you'll get a team embed with a prompt to confirm, hit the 👍 and your team will be saved!
#### editing (all of these commands require ownership and exact spelling of the team name):
- m;addplayer batter/pitcher [team name] \[player name]
- adds a new player to the end of your team, either in the lineup or the rotation depending on which version you use. use addplayer batter or addplayer pitcher at the top of a list with entries separated by new lines:
- the name of the team you want to add the player to.
- the name of the player you want to add to the team.
- m;moveplayer [team name] \[player name] [new lineup/rotation position number]
- moves a player within your lineup or rotation. if you want to instead move a player from your rotation to your lineup or vice versa, use m;swapsection instead. use this command at the top of a list with entries separated by new lines:
- the name of the team you want to move the player on.
- the name of the player you want to move.
- the position you want to move them too, indexed with 1 being the first position of the lineup or rotation. all players below the specified position in the lineup or rotation will be pushed down.
- m;swapsection [team name] \[player name]
- swaps a player from your lineup to the end of your rotation or your rotation to the end of your lineup. use this command at the top of a list with entries separated by new lines:
- the name of the team you want to swap the player on.
- the name of the player you want to swap.
- m;removeplayer [team name] \[player name]
- removes a player from your team. if there are multiple copies of the same player on a team this will only delete the first one. use this command at the top of a list with entries separated by new lines:
- the name of the team you want to remove the player from.
- the name of the player you want to remove.
#### viewing and searching:
- m;showteam [name] - m;showteam [name]
- shows information about any saved team. - shows the lineup, rotation, and slogan of any saved team in a discord embed with primary stat star ratings for all of the players. this command has fuzzy search so you don't need to type the full name of the team as long as you give enough to identify the team you're looking for.
- m;showallteams
- shows a paginated list of all teams available for games which can be scrolled through.
- m;searchteams [searchterm] - m;searchteams [searchterm]
- shows a paginated list of all teams whose names contain the given search term. - shows a paginated list of all teams whose names contain the given search term.
- m;deleteteam [teamname] - m;showallteams
- allows you to delete the team with the provided name if you are the owner of it, gives a confirmation first to prevent accidental deletions. if it isn't letting you delete your team, you probably created it before teams having owners was a thing, contact xvi and xie can assign you as the owner. - shows a paginated list of all teams available for games which can be scrolled through.
- m;import
- imports an onomancer collection as a new team. you can use the new onomancer simsim setting to ensure compatibility. ### game commands:
- m;startgame --day # or -d #
- starts a game with premade teams made using saveteam. provides a link to the website where you can watch the game.
- the --day/-d is optional, if used it'll force the game to use the #th spot in each team's rotations. if this number is larger than the number of pitchers in one or both of the teams' rotations it'll wrap around. if it is not used pitchers will be chosen randomly from the teams' rotations.
- use this command at the top of a list with entries separated by new lines:
- the away team's name.
- the home team's name.
- optionally, the number of innings, which must be greater than 2 and less than 201. if not included it will default to 9.
- this command has fuzzy search so you don't need to type the full name of the team as long as you give enough to identify the team you're looking for.
- m;randomgame
- starts a 9-inning game between 2 entirely random teams. embrace chaos!
- m;starttournament --rounddelay #
- starts a randomly seeded tournament with the provided teams, automatically adding byes as necessary. all series have a 5 minute break between games. the current format is: best of 5 until the finals which are best of 7.
- the --rounddelay is optional, if used, # must be between 1 and 120 and it'll set the delay between rounds to be # minutes. if not included it will default to 10.
- use this command at the top of a list with entries separated by new lines:
- the name of the tournament.
- the name of each participating team on its own line.
### draft commands
- m;startdraft
- starts a draft with an arbitrary number of participants. use this command at the top of a list with entries separated by new lines:
- for each participant's entry you need three lines:
- their discord @
- their team name
- their team slogan
- post this with all three of these things for all participants and the draft will begin.
- the draft will begin once all participants have given a 👍 and will proceed in the order that participants were entered. each participant will select 12 hitters and 1 pitcher from a pool of 20 random players which will refresh automatically when it becomes small.
- m;draft [name]
- use this on your turn during a draft to pick your player.
- you can also just use a 'd' instead of the full command.
### league commands
- all of these commands are for leagues that have already been started. to start a league, click the 'create a league' button on the website and fill out the info for your league there, then use the m;claimleague command in discord to set yourself as the owner.
- commissioner commands (all of these except for m;claimleague require ownership of the specified league):
- m;claimleague [leaguename]
- sets yourself as the owner of an unclaimed league created on the website. make sure to do this as soon as possible since if someone does this before you, you will not have access to the league.
- m;addleagueowner [leaguename]
- use this command at the top of a list of @mentions, with entries separated by new lines, of people you want to have owner powers in your league.
- m;startleague [leaguename] --queue #/-q # --noautopostseason
- send this command with the number of games per hour you want on the next line, minimum 1 (one game every hour), maximum 12 (one game every 5 minutes, uses spillover rules).
- starts the playing of league games at the pace specified, by default will play the entire season and the postseason unless an owner pauses the league with the m;pauseleague command.
- if you use the --queue #/-q # flag, the league will only play # series' at a time before automatically pausing until you use this command again.
- if you use the --noautopostseason flag, instead of starting automatically, the league will pause at the end of the regular season and not start the postseason until you use this command again.
- m;pauseleague [leaguename]
- pauses the specified league after the current series finishes until the league is started again with m;startleague.
- general commands (all of these can be used by anyone):
- m;leaguestandings [leaguename] --season #/-s #
- displays the current standings for the specified league.
- by default this will display the standings for the current season but if the --season #/-s # flag is set it will instead display the standings for the #th season instead for viewing historical standings.
- m;leaguewildcard [leaguename]
- displays the wild card standings for the specified league. if the league doesn't have wild cards, it will instead tell you that.
- m;leagueschedule [leaguename]
- displays the upcoming schedule for the specified league. shows the current series and the next three series after that for every team.
### player commands: ### player commands:
- m;showplayer [name] - m;showplayer [name]
@ -37,18 +123,11 @@ accepting pull requests, check the issues for to-dos.
- m;idolize [name] - m;idolize [name]
- records any name as your idol, mostly for fun. - records any name as your idol, mostly for fun.
- m;showidol - m;showidol
- displays your idol's name and stars. - displays your idol's name and stars in a discord embed.
### game commands:
- m;startgame
- starts a game with premade teams made using saveteam, use this command at the top of a list followed by each of these in a new line:
- the away team's name.
- the home team's name.
- and finally, optionally, the number of innings, which must be greater than 2 and less than 31. if not included it will default to 9.
### other commands: ### other commands:
- m;help [command] - m;help [command]
- shows the instructions from here for given command. if no command is provided, it will instead provide a list of all of the commands that instructions can be provided for. - shows instructions for a given command. if no command is provided, it will instead provide a list of all of the commands that instructions can be provided for.
- m;credit - m;credit
- shows artist credit for matteo's avatar. - shows artist credit for matteo's avatar.
- m;roman [number] - m;roman [number]
@ -61,3 +140,10 @@ these folks are helping me a *ton* via patreon, and i cannot possibly thank them
- Chris Denmark - Chris Denmark
- Astrid Bek - Astrid Bek
- Kameleon - Kameleon
- Ryan Littleton
- Evie Diver
- iliana etaoin
## Attribution
Twemoji is copyright 2020 Twitter, Inc and other contributors; code licensed under [the MIT License](http://opensource.org/licenses/MIT), graphics licensed under [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/)

View File

@ -2,12 +2,17 @@
import os, json, datetime, re import os, json, datetime, re
import sqlite3 as sql import sqlite3 as sql
data_dir = "data"
def create_connection(): def create_connection():
#create connection, create db if doesn't exist #create connection, create db if doesn't exist
conn = None conn = None
try: try:
conn = sql.connect("matteo.db") conn = sql.connect(os.path.join(data_dir, "matteo.db"))
# enable write-ahead log for performance and resilience
conn.execute('pragma journal_mode=wal')
return conn return conn
except: except:
print("oops, db connection no work") print("oops, db connection no work")
@ -66,6 +71,15 @@ def initialcheck():
owner_id integer owner_id integer
); """ ); """
history_table_check_string = """ CREATE TABLE IF NOT EXISTS history (
id integer PRIMARY Key,
Team_1 text NOT NULL,
Team_1_Score integer,
Team_2 text NOT NULL,
Team_2_Score integer,
Weather text NOT NULL
);"""
if conn is not None: if conn is not None:
c = conn.cursor() c = conn.cursor()
c.execute(soulscream_table_check_string) c.execute(soulscream_table_check_string)
@ -73,6 +87,7 @@ def initialcheck():
c.execute(player_table_check_string) c.execute(player_table_check_string)
c.execute(player_stats_table_check_string) c.execute(player_stats_table_check_string)
c.execute(teams_table_check_string) c.execute(teams_table_check_string)
c.execute(history_table_check_string)
conn.commit() conn.commit()
conn.close() conn.close()
@ -181,9 +196,13 @@ def get_user_player_conn(conn, user):
except TypeError: except TypeError:
return False return False
else: else:
print(conn) conn.close()
return False
except: except:
print(conn) conn.close()
return False
conn.close()
return False
def get_user_player(user): def get_user_player(user):
conn = create_connection() conn = create_connection()
@ -206,6 +225,8 @@ def save_team(name, team_json_string, user_id):
return False return False
except: except:
return False return False
conn.close()
return False
def update_team(name, team_json_string): def update_team(name, team_json_string):
conn = create_connection() conn = create_connection()
@ -220,6 +241,9 @@ def update_team(name, team_json_string):
conn.close() conn.close()
return False return False
except: except:
conn.close()
return False
conn.close()
return False return False
def get_team(name, owner=False): def get_team(name, owner=False):
@ -253,6 +277,8 @@ def delete_team(team):
except: except:
conn.close() conn.close()
return False return False
conn.close()
return False
def assign_owner(team_name, owner_id): def assign_owner(team_name, owner_id):
conn = create_connection() conn = create_connection()
@ -266,6 +292,8 @@ def assign_owner(team_name, owner_id):
except: except:
conn.close() conn.close()
return False return False
conn.close()
return False
def get_all_teams(): def get_all_teams():
conn = create_connection() conn = create_connection()
@ -309,3 +337,24 @@ def add_stats(player_game_stats_list):
c.execute(f"UPDATE stats SET {stat} = ? WHERE name=?",(player_stats_dic[stat],name)) c.execute(f"UPDATE stats SET {stat} = ? WHERE name=?",(player_stats_dic[stat],name))
conn.commit() conn.commit()
conn.close() conn.close()
def cache_history(Team_1, Team_1_Score, Team_2, Team_2_Score, weather):
conn = create_connection()
store_string = """ INSERT INTO history(Team_1, Team_1_Score, Team_2, Team_2_Score, Weather)
VALUES (?,?,?,?,?) """
if conn is not None:
c = conn.cursor()
c.execute(store_string, (Team_1, Team_1_Score, Team_2, Team_2_Score, weather))
conn.commit()
conn.close()
def get_history():
conn = create_connection()
if conn is not None:
c = conn.cursor()
c.execute("SELECT * FROM history")
history_strings = c.fetchall()
conn.close()
return history_strings

213
games.py
View File

@ -2,8 +2,13 @@ import json, random, os, math, jsonpickle
from enum import Enum from enum import Enum
import database as db import database as db
data_dir = "data"
games_config_file = os.path.join(data_dir, "games_config.json")
def config(): def config():
if not os.path.exists("games_config.json"): if not os.path.exists(os.path.dirname(games_config_file)):
os.makedirs(os.path.dirname(games_config_file))
if not os.path.exists(games_config_file):
#generate default config #generate default config
config_dic = { config_dic = {
"default_length" : 3, "default_length" : 3,
@ -16,22 +21,42 @@ def config():
"stolen_base_chance_mod" : 1, "stolen_base_chance_mod" : 1,
"stolen_base_success_mod" : 1 "stolen_base_success_mod" : 1
} }
with open("games_config.json", "w") as config_file: with open(games_config_file, "w") as config_file:
json.dump(config_dic, config_file, indent=4) json.dump(config_dic, config_file, indent=4)
return config_dic return config_dic
else: else:
with open("games_config.json") as config_file: with open(games_config_file) as config_file:
return json.load(config_file) return json.load(config_file)
def all_weathers(): def all_weathers():
weathers_dic = { if not os.path.exists("weather_config.json"):
#"Supernova" : weather("Supernova", "🌟"), #generate default config
"Midnight": weather("Midnight", "🕶"), super_weather_json = jsonpickle.encode(weather("Supernova", "🌟"))
"Slight Tailwind": weather("Slight Tailwind", "🏌️‍♀️"), mid_weather_json = jsonpickle.encode(weather("Midnight", "🕶"))
"Heavy Snow": weather("Heavy Snow", "") crow_weather_json = jsonpickle.encode(weather("Crowstorm", "🐦"))
slime_weather_json = jsonpickle.encode(weather("Slime", "🟢"))
peanut_weather_json = jsonpickle.encode(weather("Peanado", "🥜"))
thickair_weather_json = jsonpickle.encode(weather("Thick Air", "🌫️"))
molasses_weather_json = jsonpickle.encode(weather("Molasses", "🧇"))
coke_weather_json = jsonpickle.encode(weather("Coke Raine", "🥤"))
config_dic = {
"Supernova" : super_weather_json,
"Midnight" : mid_weather_json,
"Crowstorm" : crow_weather_json,
"Slime" : slime_weather_json,
"Peanado" : peanut_weather_json,
"Thick Air" : thickair_weather_json,
"Molasses" : molasses_weather_json,
"Coke Raine" : coke_weather_json
} }
return weathers_dic with open("weather_config.json", "w") as config_file:
json.dump(config_dic, config_file, indent=4)
with open("weather_config.json") as config_file:
weather_dic = {}
for weather_json in json.load(config_file).values():
this_weather = jsonpickle.decode(weather_json, classes=weather)
weather_dic[this_weather.name] = this_weather
return weather_dic
class appearance_outcomes(Enum): class appearance_outcomes(Enum):
strikeoutlooking = "strikes out looking." strikeoutlooking = "strikes out looking."
@ -45,8 +70,9 @@ class appearance_outcomes(Enum):
single = "hits a single!" single = "hits a single!"
double = "hits a double!" double = "hits a double!"
triple = "hits a triple!" triple = "hits a triple!"
homerun = "hits a home run!" homerun = "hits a dinger!"
grandslam = "hits a grand slam!" grandslam = "hits a grand slam!"
crows = "is chased away by crows."
class player(object): class player(object):
@ -108,6 +134,14 @@ class team(object):
else: else:
return (None, None, None) return (None, None, None)
def average_stars(self):
total_stars = 0
for _player in self.lineup:
total_stars += _player.stlats["batting_stars"]
for _player in self.rotation:
total_stars += _player.stlats["pitching_stars"]
return total_stars/(len(self.lineup) + len(self.rotation))
def swap_player(self, name): def swap_player(self, name):
this_player, index, roster = self.find_player(name) this_player, index, roster = self.find_player(name)
if this_player is not None and len(roster) > 1: if this_player is not None and len(roster) > 1:
@ -131,7 +165,7 @@ class team(object):
def slide_player(self, name, new_spot): def slide_player(self, name, new_spot):
this_player, index, roster = self.find_player(name) this_player, index, roster = self.find_player(name)
if this_player is not None and new_spot < len(roster): if this_player is not None and new_spot <= len(roster):
roster.pop(index) roster.pop(index)
roster.insert(new_spot-1, this_player) roster.insert(new_spot-1, this_player)
return True return True
@ -160,9 +194,14 @@ class team(object):
if rotation_slot is None: if rotation_slot is None:
self.pitcher = random.choice(temp_rotation) self.pitcher = random.choice(temp_rotation)
else: else:
self.pitcher = temp_rotation[rotation_slot % len(temp_rotation)] self.pitcher = temp_rotation[(rotation_slot-1) % len(temp_rotation)]
def is_ready(self): def is_ready(self):
try:
return (len(self.lineup) >= 1 and len(self.rotation) > 0)
except AttributeError:
self.rotation = [self.pitcher]
self.pitcher = None
return (len(self.lineup) >= 1 and len(self.rotation) > 0) return (len(self.lineup) >= 1 and len(self.rotation) > 0)
def prepare_for_save(self): def prepare_for_save(self):
@ -177,11 +216,11 @@ class team(object):
for this_player in self.rotation: for this_player in self.rotation:
for stat in this_player.game_stats.keys(): for stat in this_player.game_stats.keys():
this_player.game_stats[stat] = 0 this_player.game_stats[stat] = 0
return True return self
def finalize(self): def finalize(self):
if self.is_ready(): if self.is_ready():
if self.pitcher is None: if self.pitcher == None:
self.set_pitcher() self.set_pitcher()
while len(self.lineup) <= 4: while len(self.lineup) <= 4:
self.lineup.append(random.choice(self.lineup)) self.lineup.append(random.choice(self.lineup))
@ -192,8 +231,7 @@ class team(object):
class game(object): class game(object):
def __init__(self, name, team1, team2, length=None): def __init__(self, team1, team2, length=None):
self.name = name
self.over = False self.over = False
self.teams = {"away" : team1, "home" : team2} self.teams = {"away" : team1, "home" : team2}
self.inning = 1 self.inning = 1
@ -213,10 +251,8 @@ class game(object):
def get_batter(self): def get_batter(self):
if self.top_of_inning: if self.top_of_inning:
bat_team = self.teams["away"] bat_team = self.teams["away"]
counter = self.weather.counter_away
else: else:
bat_team = self.teams["home"] bat_team = self.teams["home"]
counter = self.weather.counter_home
if self.weather.name == "Heavy Snow" and counter == bat_team.lineup_position: if self.weather.name == "Heavy Snow" and counter == bat_team.lineup_position:
return bat_team.pitcher return bat_team.pitcher
@ -246,15 +282,32 @@ class game(object):
bat_stat = random_star_gen("batting_stars", batter) bat_stat = random_star_gen("batting_stars", batter)
pitch_stat = random_star_gen("pitching_stars", pitcher) pitch_stat = random_star_gen("pitching_stars", pitcher)
if weather.name == "Supernova": if self.weather.name == "Supernova":
pitch_stat = pitch_stat / 0.9
elif self.weather.name == "Thick Air":
pitch_stat = pitch_stat * 0.9 pitch_stat = pitch_stat * 0.9
pb_system_stat = (random.gauss(1*math.erf((bat_stat - pitch_stat)*1.5)-1.8,2.2)) pb_system_stat = (random.gauss(1*math.erf((bat_stat - pitch_stat)*1.5)-1.8,2.2))
hitnum = random.gauss(2*math.erf(bat_stat/4)-1,3) hitnum = random.gauss(2*math.erf(bat_stat/4)-1,3)
crow = False
if self.weather.name == "Twilight":
error_line = - (math.log(defender.stlats["defense_stars"] + 1)/50) + 1
error_roll = random.random()
if error_roll > error_line:
outcome["error"] = True
outcome["defender"] = defender
pb_system_stat = 0.1
if self.weather.name == "Crowstorm":
if pb_system_stat <= 0: randomchance = random.gauss(0,1)
if randomchance < -1.5 or randomchance > 1.5:
outcome["ishit"] = False
fc_flag = False
outcome["text"] = appearance_outcomes.crows
crow = True
else:
if pb_system_stat <= 0 and crow == False:
outcome["ishit"] = False outcome["ishit"] = False
fc_flag = False fc_flag = False
if hitnum < -1.5: if hitnum < -1.5:
@ -285,6 +338,10 @@ class game(object):
if self.outs < 2 and len(runners) > 1: #fielder's choice replaces not great groundouts if any forceouts are present if self.outs < 2 and len(runners) > 1: #fielder's choice replaces not great groundouts if any forceouts are present
def_stat = random_star_gen("defense_stars", defender) def_stat = random_star_gen("defense_stars", defender)
if self.weather.name == "Coke Raine":
def_stat = def_stat / 0.9
elif self.weather.name == "Molasses":
def_stat = def_stat * 0.9
if -1.5 <= hitnum and hitnum < -0.5: #poorly hit groundouts if -1.5 <= hitnum and hitnum < -0.5: #poorly hit groundouts
outcome["text"] = appearance_outcomes.fielderschoice outcome["text"] = appearance_outcomes.fielderschoice
outcome["defender"] = "" outcome["defender"] = ""
@ -292,7 +349,7 @@ class game(object):
if 2.5 <= hitnum and self.outs < 2: #well hit flyouts can lead to sacrifice flies/advanced runners if 2.5 <= hitnum and self.outs < 2: #well hit flyouts can lead to sacrifice flies/advanced runners
if self.bases[2] is not None or self.bases[3] is not None: if self.bases[2] is not None or self.bases[3] is not None:
outcome["advance"] = True outcome["advance"] = True
else: elif crow == False:
outcome["ishit"] = True outcome["ishit"] = True
if hitnum < 1: if hitnum < 1:
outcome["text"] = appearance_outcomes.single outcome["text"] = appearance_outcomes.single
@ -305,6 +362,61 @@ class game(object):
outcome["text"] = appearance_outcomes.grandslam outcome["text"] = appearance_outcomes.grandslam
else: else:
outcome["text"] = appearance_outcomes.homerun outcome["text"] = appearance_outcomes.homerun
elif pb_system_stat <= 0 and crow == False:
outcome["ishit"] = False
fc_flag = False
if hitnum < -1.5:
outcome["text"] = random.choice([appearance_outcomes.strikeoutlooking, appearance_outcomes.strikeoutswinging])
elif hitnum < 1:
outcome["text"] = appearance_outcomes.groundout
outcome["defender"] = defender
elif hitnum < 4:
outcome["text"] = appearance_outcomes.flyout
outcome["defender"] = defender
else:
outcome["text"] = appearance_outcomes.walk
if self.bases[1] is not None and hitnum < -2 and self.outs != 2:
outcome["text"] = appearance_outcomes.doubleplay
outcome["defender"] = ""
#for base in self.bases.values():
#if base is not None:
#fc_flag = True
runners = [(0,self.get_batter())]
for base in range(1,4):
if self.bases[base] == None:
break
runners.append((base, self.bases[base]))
outcome["runners"] = runners #list of consecutive baserunners: (base number, player object)
if self.outs < 2 and len(runners) > 1: #fielder's choice replaces not great groundouts if any forceouts are present
def_stat = random_star_gen("defense_stars", defender)
if self.weather.name == "Coke Raine":
def_stat = def_stat / 0.9
elif self.weather.name == "Molasses":
def_stat = def_stat * 0.9
if -1.5 <= hitnum and hitnum < -0.5: #poorly hit groundouts
outcome["text"] = appearance_outcomes.fielderschoice
outcome["defender"] = ""
if 2.5 <= hitnum and self.outs < 2: #well hit flyouts can lead to sacrifice flies/advanced runners
if self.bases[2] is not None or self.bases[3] is not None:
outcome["advance"] = True
elif crow == False:
outcome["ishit"] = True
if hitnum < 1:
outcome["text"] = appearance_outcomes.single
elif hitnum < 2.85 or "error" in outcome.keys():
outcome["text"] = appearance_outcomes.double
elif hitnum < 3.1:
outcome["text"] = appearance_outcomes.triple
else:
if self.bases[1] is not None and self.bases[2] is not None and self.bases[3] is not None:
outcome["text"] = appearance_outcomes.grandslam
else:
outcome["text"] = appearance_outcomes.homerun
return outcome return outcome
def thievery_attempts(self): #returns either false or "at-bat" outcome def thievery_attempts(self): #returns either false or "at-bat" outcome
@ -318,6 +430,8 @@ class game(object):
run_stars = random_star_gen("baserunning_stars", baserunner)*config()["stolen_base_chance_mod"] run_stars = random_star_gen("baserunning_stars", baserunner)*config()["stolen_base_chance_mod"]
if self.weather.name == "Midnight": if self.weather.name == "Midnight":
run_stars = run_stars*2 run_stars = run_stars*2
elif self.weather.name == "Slime":
run_stars = run_stars*.75
def_stars = random_star_gen("defense_stars", self.get_pitcher()) def_stars = random_star_gen("defense_stars", self.get_pitcher())
if run_stars >= (def_stars - 1.5): #if baserunner isn't worse than pitcher if run_stars >= (def_stars - 1.5): #if baserunner isn't worse than pitcher
roll = random.random() roll = random.random()
@ -347,6 +461,7 @@ class game(object):
run_roll = run_roll * .9 #stealing third is harder run_roll = run_roll * .9 #stealing third is harder
if run_roll < 1: if run_roll < 1:
outcome["steals"].append(f"{baserunner} was caught stealing {base_string(start_base+1)} base by {defender}!") outcome["steals"].append(f"{baserunner} was caught stealing {base_string(start_base+1)} base by {defender}!")
self.get_pitcher().game_stats["outs_pitched"] += 1
self.outs += 1 self.outs += 1
else: else:
outcome["steals"].append(f"{baserunner} steals {base_string(start_base+1)} base!") outcome["steals"].append(f"{baserunner} steals {base_string(start_base+1)} base!")
@ -366,6 +481,11 @@ class game(object):
if base is not None: if base is not None:
runs += 1 runs += 1
self.bases = {1 : None, 2 : None, 3 : None} self.bases = {1 : None, 2 : None, 3 : None}
if "veil" in outcome.keys():
if runs < 4:
self.bases[runs] = self.get_batter()
else:
runs += 1
return runs return runs
elif "advance" in outcome.keys(): elif "advance" in outcome.keys():
@ -482,16 +602,14 @@ class game(object):
result = self.at_bat() result = self.at_bat()
if self.top_of_inning: if self.top_of_inning:
offense_team = self.teams["away"] offense_team = self.teams["away"]
weather_count = self.weather.counter_away
defense_team = self.teams["home"] defense_team = self.teams["home"]
else: else:
offense_team = self.teams["home"] offense_team = self.teams["home"]
weather_count = self.weather.counter_home
defense_team = self.teams["away"] defense_team = self.teams["away"]
if self.weather.name == "Slight Tailwind" and "mulligan" not in self.last_update[0].keys() and not result["ishit"] and result["text"] != appearance_outcomes.walk: if self.weather.name == "Slight Tailwind" and "mulligan" not in self.last_update[0].keys() and not result["ishit"] and result["text"] != appearance_outcomes.walk:
mulligan_roll_target = -((((self.get_batter().stlats["batting_stars"])-7)/7)**2)+1 mulligan_roll_target = -((((self.get_batter().stlats["batting_stars"])-5)/6)**2)+1
if random.random() > mulligan_roll_target: if random.random() > mulligan_roll_target and self.get_batter().stlats["batting_stars"] <= 5:
result["mulligan"] = True result["mulligan"] = True
return (result, 0) return (result, 0)
@ -517,6 +635,10 @@ class game(object):
elif result["text"] == appearance_outcomes.homerun or result["text"] == appearance_outcomes.grandslam: elif result["text"] == appearance_outcomes.homerun or result["text"] == appearance_outcomes.grandslam:
self.get_batter().game_stats["total_bases"] += 4 self.get_batter().game_stats["total_bases"] += 4
self.get_batter().game_stats["home_runs"] += 1 self.get_batter().game_stats["home_runs"] += 1
if self.weather.name == "Thinned Veil":
result["veil"] = True
scores_to_add += self.baserunner_check(defender, result) scores_to_add += self.baserunner_check(defender, result)
@ -589,12 +711,8 @@ class game(object):
for base in self.bases.keys(): for base in self.bases.keys():
self.bases[base] = None self.bases[base] = None
self.outs = 0 self.outs = 0
if self.top_of_inning and self.weather.name == "Heavy Snow" and self.weather.counter_away < self.teams["away"].lineup_position:
self.weather.counter_away = self.pitcher_insert(self.teams["away"])
if not self.top_of_inning: if not self.top_of_inning:
if self.weather.name == "Heavy Snow" and self.weather.counter_home < self.teams["home"].lineup_position:
self.weather.counter_home = self.pitcher_insert(self.teams["home"])
self.inning += 1 self.inning += 1
if self.inning > self.max_innings and self.teams["home"].score != self.teams["away"].score: #game over if self.inning > self.max_innings and self.teams["home"].score != self.teams["away"].score: #game over
self.over = True self.over = True
@ -658,6 +776,10 @@ class game(object):
return "Game not started." return "Game not started."
def add_stats(self): def add_stats(self):
players = self.get_stats()
db.add_stats(players)
def get_stats(self):
players = [] players = []
for this_player in self.teams["away"].lineup: for this_player in self.teams["away"].lineup:
players.append((this_player.name, this_player.game_stats)) players.append((this_player.name, this_player.game_stats))
@ -665,7 +787,20 @@ class game(object):
players.append((this_player.name, this_player.game_stats)) players.append((this_player.name, this_player.game_stats))
players.append((self.teams["home"].pitcher.name, self.teams["home"].pitcher.game_stats)) players.append((self.teams["home"].pitcher.name, self.teams["home"].pitcher.game_stats))
players.append((self.teams["away"].pitcher.name, self.teams["away"].pitcher.game_stats)) players.append((self.teams["away"].pitcher.name, self.teams["away"].pitcher.game_stats))
db.add_stats(players) return players
def get_team_specific_stats(self):
players = {
self.teams["away"].name : [],
self.teams["home"].name : []
}
for this_player in self.teams["away"].lineup:
players[self.teams["away"].name].append((this_player.name, this_player.game_stats))
for this_player in self.teams["home"].lineup:
players[self.teams["home"].name].append((this_player.name, this_player.game_stats))
players[self.teams["home"].name].append((self.teams["home"].pitcher.name, self.teams["home"].pitcher.game_stats))
players[self.teams["away"].name].append((self.teams["away"].pitcher.name, self.teams["away"].pitcher.game_stats))
return players
@ -748,9 +883,21 @@ def get_all_teams():
teams.append(this_team) teams.append(this_team)
return teams return teams
def get_history():
games = []
for game in db.get_history():
game_dict = {"Team1" : game[1],
"Team1Score" : game[2],
"Team2" : game[3],
"Team2Score" : game[4],
"Weather" : game[5]}
games.append(game_dict)
return games
def search_team(search_term): def search_team(search_term):
teams = [] teams = []
for team_pickle in db.search_teams(search_term): for team_pickle in db.search_teams(search_term):
print(team_pickle)
team_json = jsonpickle.decode(team_pickle[0], keys=True, classes=team) team_json = jsonpickle.decode(team_pickle[0], keys=True, classes=team)
try: try:
if team_json.pitcher is not None: if team_json.pitcher is not None:
@ -786,8 +933,6 @@ class weather(object):
def __init__(self, new_name, new_emoji): def __init__(self, new_name, new_emoji):
self.name = new_name self.name = new_name
self.emoji = new_emoji self.emoji = new_emoji
self.counter_away = 0
self.counter_home = 0
def __str__(self): def __str__(self):
return f"{self.emoji} {self.name}" return f"{self.emoji} {self.name}"

202
league_storage.py Normal file
View File

@ -0,0 +1,202 @@
import os, json, re, jsonpickle
import sqlite3 as sql
data_dir = "data"
league_dir = "leagues"
def create_connection(league_name):
#create connection, create db if doesn't exist
conn = None
try:
if not os.path.exists(os.path.join(data_dir, league_dir, league_name)):
os.makedirs(os.path.join(data_dir, league_dir, league_name))
conn = sql.connect(os.path.join(data_dir, league_dir, league_name, f"{league_name}.db"))
# enable write-ahead log for performance and resilience
conn.execute('pragma journal_mode=wal')
return conn
except:
print("oops, db connection no work")
return conn
def create_season_connection(league_name, season_num):
#create connection, create db if doesn't exist
conn = None
try:
if not os.path.exists(os.path.join(data_dir, league_dir, league_name)):
os.makedirs(os.path.join(data_dir, league_dir, league_name))
conn = sql.connect(os.path.join(data_dir, league_dir, league_name, season_num, f"{league_name}.db"))
# enable write-ahead log for performance and resilience
conn.execute('pragma journal_mode=wal')
return conn
except:
print("oops, db connection no work")
return conn
def state(league_name):
if not os.path.exists(os.path.dirname(os.path.join(data_dir, league_dir, league_name, f"{league_name}.state"))):
os.makedirs(os.path.dirname(os.path.join(data_dir, league_dir, league_name, f"{league_name}.state")))
with open(os.path.join(data_dir, league_dir, league_name, f"{league_name}.state")) as state_file:
return json.load(state_file)
def init_league_db(league):
conn = create_connection(league.name)
player_stats_table_check_string = """ CREATE TABLE IF NOT EXISTS stats (
counter integer PRIMARY KEY,
id text,
name text,
team_name text,
outs_pitched integer DEFAULT 0,
walks_allowed integer DEFAULT 0,
hits_allowed integer DEFAULT 0,
strikeouts_given integer DEFAULT 0,
runs_allowed integer DEFAULT 0,
plate_appearances integer DEFAULT 0,
walks_taken integer DEFAULT 0,
sacrifices integer DEFAULT 0,
hits integer DEFAULT 0,
home_runs integer DEFAULT 0,
total_bases integer DEFAULT 0,
rbis integer DEFAULT 0,
strikeouts_taken integer DEFAULT 0
);"""
teams_table_check_string = """ CREATE TABLE IF NOT EXISTS teams (
counter integer PRIMARY KEY,
name text NOT NULL,
wins integer DEFAULT 0,
losses integer DEFAULT 0,
run_diff integer DEFAULT 0
); """
if conn is not None:
c = conn.cursor()
c.execute(player_stats_table_check_string)
c.execute(teams_table_check_string)
for team in league.teams_in_league():
c.execute("INSERT INTO teams (name) VALUES (?)", (team.name,))
player_string = "INSERT INTO stats (name, team_name) VALUES (?,?)"
for batter in team.lineup:
c.execute(player_string, (batter.name, team.name))
for pitcher in team.rotation:
c.execute(player_string, (pitcher.name, team.name))
conn.commit()
conn.close()
def save_league(league):
if league_exists(league.name):
state_dic = {
"season" : league.season,
"day" : league.day,
"constraints" : league.constraints,
"schedule" : league.schedule,
"game_length" : league.game_length,
"series_length" : league.series_length,
"games_per_hour" : league.games_per_hour,
"owner" : league.owner,
"champion" : league.champion,
"historic" : league.historic
}
with open(os.path.join(data_dir, league_dir, league.name, f"{league.name}.state"), "w") as state_file:
json.dump(state_dic, state_file, indent=4)
def add_stats(league_name, player_game_stats_list):
conn = create_connection(league_name)
if conn is not None:
c=conn.cursor()
for team_name in player_game_stats_list.keys():
for (name, player_stats_dic) in player_game_stats_list[team_name]:
c.execute("SELECT * FROM stats WHERE name=? AND team_name=?",(name, team_name))
this_player = c.fetchone()
if this_player is not None:
for stat in player_stats_dic.keys():
c.execute(f"SELECT {stat} FROM stats WHERE name=? AND team_name=?",(name, team_name))
old_value = int(c.fetchone()[0])
c.execute(f"UPDATE stats SET {stat} = ? WHERE name=? AND team_name=?",(player_stats_dic[stat]+old_value, name, team_name))
else:
c.execute("INSERT INTO stats(name) VALUES (?)",(name,))
for stat in player_stats_dic.keys():
c.execute(f"UPDATE stats SET {stat} = ? WHERE name=? AND team_name=?",(player_stats_dic[stat], name, team_name))
conn.commit()
conn.close()
def update_standings(league_name, update_dic):
if league_exists(league_name):
conn = create_connection(league_name)
if conn is not None:
c = conn.cursor()
for team_name in update_dic.keys():
for stat_type in update_dic[team_name].keys(): #wins, losses, run_diff
c.execute(f"SELECT {stat_type} FROM teams WHERE name = ?", (team_name,))
old_value = int(c.fetchone()[0])
c.execute(f"UPDATE teams SET {stat_type} = ? WHERE name = ?", (update_dic[team_name][stat_type]+old_value, team_name))
conn.commit()
conn.close()
def get_standings(league_name):
if league_exists(league_name):
conn = create_connection(league_name)
if conn is not None:
c = conn.cursor()
c.execute("SELECT name, wins, losses, run_diff FROM teams",)
standings_array = c.fetchall()
conn.close()
return standings_array
def season_save(league):
if league_exists(league.name):
seasons = 1
with os.scandir(os.path.join(data_dir, league_dir, league.name)) as folder:
for item in folder:
if "." not in item.name:
seasons += 1
new_dir = os.path.join(data_dir, league_dir, league.name, str(seasons))
os.makedirs(new_dir)
with os.scandir(os.path.join(data_dir, league_dir, league.name)) as folder:
for item in folder:
if "." in item.name:
os.rename(os.path.join(data_dir, league_dir, league.name, item.name), os.path.join(new_dir, item.name))
def get_past_standings(league_name, season_num):
if league_exists(league_name):
with os.scandir(os.path.join(data_dir, league_dir, league_name)) as folder:
for item in folder:
if item.name == str(season_num):
conn = create_season_connection(league_name, str(item.name))
if conn is not None:
c = conn.cursor()
c.execute("SELECT name, wins, losses, run_diff FROM teams",)
standings_array = c.fetchall()
conn.close()
return standings_array
def get_past_champion(league_name, season_num):
if league_exists(league_name):
with os.scandir(os.path.join(data_dir, league_dir, league_name)) as folder:
for item in folder:
if item.name == str(season_num):
with open(os.path.join(data_dir, league_dir, league_name, item.name, f"{league_name}.state")) as state_file:
state_dic = json.load(state_file)
return state_dic["champion"]
def league_exists(league_name):
with os.scandir(os.path.join(data_dir, league_dir)) as folder:
for subfolder in folder:
if league_name == subfolder.name:
with os.scandir(subfolder.path) as league_folder:
for item in league_folder:
if item.name == f"{league_name}.db":
return True
return False

View File

@ -1,19 +1,509 @@
import time, asyncio, jsonpickle import time, asyncio, json, jsonpickle, random, math, os
import database as db import league_storage as league_db
from itertools import chain
from copy import deepcopy
from games import team, game
from discord import Embed, Color
data_dir = "data"
league_dir = "leagues"
class league_structure(object):
def __init__(self, name):
class league(object):
def __init__(self, name, subleagues_dic):
self.subleagues = {} #key: name, value: [divisions]
self.max_days
self.day = 1
self.name = name self.name = name
self.subleagues = subleagues_dic self.historic = False
self.owner = None
self.season = 1
self.autoplay = -1
self.champion = None
class division(object): def setup(self, league_dic, division_games = 1, inter_division_games = 1, inter_league_games = 1, games_per_hour = 2):
def __init__(self): self.league = league_dic # { subleague name : { division name : [team object] } }
self.teams = {} #key: team name, value: {wins; losses; run diff} self.constraints = {
"division_games" : division_games,
"inter_div_games" : inter_division_games,
"inter_league_games" : inter_league_games,
"division_leaders" : 0,
"wild_cards" : 0
}
self.day = 1
self.schedule = {}
self.series_length = 3 #can be changed
self.game_length = None
self.active = False
self.games_per_hour = games_per_hour
def season_reset(self):
self.season += 1
self.day = 1
self.champion = None
self.schedule = {}
self.generate_schedule()
save_league(self)
def add_stats_from_game(self, players_dic):
league_db.add_stats(self.name, players_dic)
def update_standings(self, results_dic):
league_db.update_standings(self.name, results_dic)
def last_series_check(self):
return str(math.ceil((self.day)/self.series_length) + 1) not in self.schedule.keys()
def day_to_series_num(self, day):
return math.ceil((self.day)/self.series_length)
def tiebreaker_required(self):
standings = {}
matchups = []
tournaments = []
for team_name, wins, losses, run_diff in league_db.get_standings(self.name):
standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
for subleague in iter(self.league.keys()):
team_dic = {}
subleague_array = []
wildcard_leaders = []
for division in iter(self.league[subleague].keys()):
division_standings = []
division_standings += self.division_standings(self.league[subleague][division], standings)
division_leaders = division_standings[:self.constraints["division_leaders"]]
for division_team, wins, losses, diff, gb in division_standings[self.constraints["division_leaders"]:]:
if division_team.name != division_leaders[-1][0].name and standings[division_team.name]["wins"] == standings[division_leaders[-1][0].name]["wins"]:
matchups.append((division_team, division_standings[self.constraints["division_leaders"]-1][0], f"{division} Tiebreaker"))
this_div_wildcard = [this_team for this_team, wins, losses, diff, gb in self.division_standings(self.league[subleague][division], standings)[self.constraints["division_leaders"]:]]
subleague_array += this_div_wildcard
if self.constraints["wild_cards"] > 0:
wildcard_standings = self.division_standings(subleague_array, standings)
wildcard_leaders = wildcard_standings[:self.constraints["wild_cards"]]
for wildcard_team, wins, losses, diff, gb in wildcard_standings[self.constraints["wild_cards"]:]:
if wildcard_team.name != wildcard_leaders[-1][0].name and standings[wildcard_team.name]["wins"] == standings[wildcard_leaders[-1][0].name]["wins"]:
matchups.append((wildcard_team, wildcard_standings[self.constraints["wild_cards"]-1][0], f"{subleague} Wildcard Tiebreaker"))
for team_a, team_b, type in matchups:
tourney = tournament(f"{self.name} {type}",{team_a : {"wins" : 1}, team_b : {"wins" : 0}}, finals_series_length=1, secs_between_games=int(3600/self.games_per_hour), secs_between_rounds=int(7200/self.games_per_hour))
tourney.build_bracket(by_wins = True)
tourney.league = self
tournaments.append(tourney)
return tournaments
def find_team(self, team_name):
for subleague in iter(self.league.keys()):
for division in iter(self.league[subleague].keys()):
if team_name in self.league[subleague][division]:
return (subleague, division)
def teams_in_league(self):
teams = []
for division in self.league.values():
for teams_list in division.values():
teams += teams_list
return teams
def teams_in_subleague(self, subleague_name):
teams = []
if subleague_name in self.league.keys():
for division_list in self.league[subleague_name].values():
teams += division_list
return teams
else:
print("League not found.")
return None
def teams_in_division(self, subleague_name, division_name):
if subleague_name in self.league.keys() and division_name in self.league[subleague_name].keys():
return self.league[subleague_name][division_name]
else:
print("Division in that league not found.")
return None
def make_matchups(self):
matchups = []
batch_subleagues = [] #each sub-array is all teams in each subleague
subleague_max = 1
league = deepcopy(self.league)
for subleague in league.keys():
teams = deepcopy(self.teams_in_subleague(subleague))
if subleague_max < len(teams):
subleague_max = len(teams)
batch_subleagues.append(teams)
for subleague in batch_subleagues:
while len(subleague) < subleague_max:
subleague.append("OFF")
for i in range(0, self.constraints["inter_league_games"]): #generates inter-league matchups
unmatched_indices = [i for i in range(0, len(batch_subleagues))]
for subleague_index in range(0, len(batch_subleagues)):
if subleague_index in unmatched_indices:
unmatched_indices.pop(unmatched_indices.index(subleague_index))
match_with_index = random.choice(unmatched_indices)
unmatched_indices.pop(unmatched_indices.index(match_with_index))
league_a = batch_subleagues[subleague_index].copy()
league_b = batch_subleagues[match_with_index].copy()
random.shuffle(league_a)
random.shuffle(league_b)
a_home = True
for team_a, team_b in zip(league_a, league_b):
if a_home:
matchups.append([team_b.name, team_a.name])
else:
matchups.append([team_a.name, team_b.name])
a_home = not a_home
for i in range(0, self.constraints["inter_div_games"]): #inter-division matchups
for subleague in league.keys():
division_max = 1
divisions = []
for div in league[subleague].keys():
if division_max < len(league[subleague][div]):
divison_max = len(league[subleague][div])
divisions.append(deepcopy(league[subleague][div]))
last_div = None
if len(divisions) % 2 != 0:
if division_max % 2 != 0:
divisions.append(["OFF" for i in range(0, division_max)])
else:
last_div = divisions.pop
divs_a = list(chain(divisions[int(len(divisions)/2):]))[0]
if last_div is not None:
divs_a.extend(last_div[int(len(last_div)/2):])
random.shuffle(divs_a)
divs_b = list(chain(divisions[:int(len(divisions)/2)]))[0]
if last_div is not None:
divs_a.extend(last_div[:int(len(last_div)/2)])
random.shuffle(divs_b)
a_home = True
for team_a, team_b in zip(divs_a, divs_b):
if a_home:
matchups.append([team_b.name, team_a.name])
else:
matchups.append([team_a.name, team_b.name])
a_home = not a_home
for subleague in league.keys():
for division in league[subleague].values(): #generate round-robin matchups
if len(division) % 2 != 0:
division.append("OFF")
for i in range(0, len(division)-1):
teams_a = division[int(len(division)/2):]
teams_b = division[:int(len(division)/2)]
teams_b.reverse()
for team_a, team_b in zip(teams_a, teams_b):
if team_a != "OFF" and team_b != "OFF":
for j in range(0, self.constraints["division_games"]):
if i % 2 == 0:
matchups.append([team_b.name, team_a.name])
else:
matchups.append([team_a.name, team_b.name])
division.insert(1, division.pop())
return matchups
def generate_schedule(self):
matchups = self.make_matchups()
random.shuffle(matchups)
for game in matchups:
scheduled = False
day = 1
while not scheduled:
found = False
if str(day) in self.schedule.keys():
for game_on_day in self.schedule[str(day)]:
for team in game:
if team in game_on_day:
found = True
if not found:
self.schedule[str(day)].append(game)
scheduled = True
else:
self.schedule[str(day)] = [game]
scheduled = True
day += 1
def division_standings(self, division, standings):
def sorter(team_in_list):
if team_in_list[2] == 0 and team_in_list[1] == 0:
return (0, team_in_list[3])
return (team_in_list[1]/(team_in_list[1]+team_in_list[2]), team_in_list[3])
teams = division.copy()
for index in range(0, len(teams)):
this_team = teams[index]
teams[index] = [this_team, standings[teams[index].name]["wins"], standings[teams[index].name]["losses"], standings[teams[index].name]["run_diff"], 0]
teams.sort(key=sorter, reverse=True)
return teams
def past_standings(self, season_num):
this_embed = Embed(color=Color.purple(), title=self.name)
standings = {}
for team_name, wins, losses, run_diff in league_db.get_past_standings(self.name, season_num):
standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
this_embed.add_field(name=league_db.get_past_champion(self.name, season_num), value=f"Season {season_num} champions", inline = False)
for subleague in iter(self.league.keys()):
this_embed.add_field(name="Subleague:", value=f"**{subleague}**", inline = False)
for division in iter(self.league[subleague].keys()):
teams = self.division_standings(self.league[subleague][division], standings)
for index in range(0, len(teams)):
if index == self.constraints["division_leaders"] - 1:
teams[index][4] = "-"
else:
games_behind = ((teams[self.constraints["division_leaders"] - 1][1] - teams[index][1]) + (teams[index][2] - teams[self.constraints["division_leaders"] - 1][2]))/2
teams[index][4] = games_behind
teams_string = ""
for this_team in teams:
if this_team[2] != 0 or this_team[1] != 0:
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: {round(this_team[1]/(this_team[1]+this_team[2]), 3)} GB: {this_team[4]}\n\n"
else:
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}\n\n"
this_embed.add_field(name=f"{division} Division:", value=teams_string, inline = False)
this_embed.set_footer(text=f"Season {season_num} Final Standings")
return this_embed
def season_length(self):
return int(list(self.schedule.keys())[-1]) * self.series_length
def standings_embed(self):
this_embed = Embed(color=Color.purple(), title=f"{self.name} Season {self.season}")
standings = {}
for team_name, wins, losses, run_diff in league_db.get_standings(self.name):
standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
for subleague in iter(self.league.keys()):
this_embed.add_field(name="Subleague:", value=f"**{subleague}**", inline = False)
for division in iter(self.league[subleague].keys()):
teams = self.division_standings(self.league[subleague][division], standings)
for index in range(0, len(teams)):
if index == self.constraints["division_leaders"] - 1:
teams[index][4] = "-"
else:
games_behind = ((teams[self.constraints["division_leaders"] - 1][1] - teams[index][1]) + (teams[index][2] - teams[self.constraints["division_leaders"] - 1][2]))/2
teams[index][4] = games_behind
teams_string = ""
for this_team in teams:
if this_team[2] != 0 or this_team[1] != 0:
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: {round(this_team[1]/(this_team[1]+this_team[2]), 3)} GB: {this_team[4]}\n\n"
else:
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}\n\n"
this_embed.add_field(name=f"{division} Division:", value=teams_string, inline = False)
this_embed.set_footer(text=f"Standings as of day {self.day-1} / {self.season_length()}")
return this_embed
def wildcard_embed(self):
this_embed = Embed(color=Color.purple(), title=f"{self.name} Wildcard Race")
standings = {}
for team_name, wins, losses, run_diff in league_db.get_standings(self.name):
standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
for subleague in iter(self.league.keys()):
subleague_array = []
for division in iter(self.league[subleague].keys()):
this_div = [this_team for this_team, wins, losses, diff, gb in self.division_standings(self.league[subleague][division], standings)[self.constraints["division_leaders"]:]]
subleague_array += this_div
teams = self.division_standings(subleague_array, standings)
teams_string = ""
for index in range(0, len(teams)):
if index == self.constraints["wild_cards"] - 1:
teams[index][4] = "-"
else:
games_behind = ((teams[self.constraints["wild_cards"] - 1][1] - teams[index][1]) + (teams[index][2] - teams[self.constraints["wild_cards"] - 1][2]))/2
teams[index][4] = games_behind
for this_team in teams:
if this_team[2] != 0 or this_team[1] != 0:
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: {round(this_team[1]/(this_team[1]+this_team[2]), 3)} GB: {this_team[4]}\n\n"
else:
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}\n\n"
this_embed.add_field(name=f"{subleague} League:", value=teams_string, inline = False)
this_embed.set_footer(text=f"Wildcard standings as of day {self.day-1}")
return this_embed
def champ_series(self):
tournaments = []
standings = {}
for team_name, wins, losses, run_diff in league_db.get_standings(self.name):
standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
for subleague in iter(self.league.keys()):
team_dic = {}
division_leaders = []
subleague_array = []
wildcard_leaders = []
for division in iter(self.league[subleague].keys()):
division_leaders += self.division_standings(self.league[subleague][division], standings)[:self.constraints["division_leaders"]]
this_div_wildcard = [this_team for this_team, wins, losses, diff, gb in self.division_standings(self.league[subleague][division], standings)[self.constraints["division_leaders"]:]]
subleague_array += this_div_wildcard
if self.constraints["wild_cards"] > 0:
wildcard_leaders = self.division_standings(subleague_array, standings)[:self.constraints["wild_cards"]]
for this_team, wins, losses, diff, gb in division_leaders + wildcard_leaders:
team_dic[this_team] = {"wins" : wins}
subleague_tournament = tournament(f"{self.name} {subleague} Subleague Series", team_dic, series_length=3, finals_series_length=5, secs_between_games=int(3600/self.games_per_hour), secs_between_rounds=int(7200/self.games_per_hour))
subleague_tournament.build_bracket(by_wins = True)
subleague_tournament.league = self
tournaments.append(subleague_tournament)
return tournaments
class tournament(object):
def __init__(self, name, team_dic, series_length = 5, finals_series_length = 7, max_innings = 9, id = None, secs_between_games = 300, secs_between_rounds = 600):
self.name = name
self.teams = team_dic #key: team object, value: wins
self.bracket = None
self.results = None
self.series_length = series_length
self.finals_length = finals_series_length
self.game_length = max_innings
self.active = False
self.delay = secs_between_games
self.round_delay = secs_between_rounds
self.finals = False
self.id = id
self.league = None
self.winner = None
self.day = None
if id is None:
self.id = random.randint(1111,9999)
else:
self.id = id
def build_bracket(self, random_sort = False, by_wins = False, manual = False):
teams_list = list(self.teams.keys()).copy()
if random_sort:
def sorter(team_in_list):
return random.random()
elif by_wins:
def sorter(team_in_list):
return self.teams[team_in_list]["wins"] #sorts by wins
else: #sort by average stars
def sorter(team_in_list):
return team_in_list.average_stars()
if not manual:
teams_list.sort(key=sorter, reverse=True)
bracket_layers = int(math.ceil(math.log(len(teams_list), 2)))
empty_slots = int(math.pow(2, bracket_layers) - len(teams_list))
for i in range(0, empty_slots):
teams_list.append(None)
previous_bracket_layer = teams_list.copy()
for i in range(0, bracket_layers - 1):
this_layer = []
for pair in range(0, int(len(previous_bracket_layer)/2)):
if pair % 2 == 0: #if even number
this_layer.insert(0+int(pair/2), [previous_bracket_layer.pop(0), previous_bracket_layer.pop(-1)]) #every other pair goes at front of list, moving forward
else:
this_layer.insert(0-int((1+pair)/2), [previous_bracket_layer.pop(int(len(previous_bracket_layer)/2)-1), previous_bracket_layer.pop(int(len(previous_bracket_layer)/2))]) #every other pair goes at end of list, moving backward
previous_bracket_layer = this_layer
self.bracket = bracket(previous_bracket_layer, bracket_layers)
def round_check(self):
if self.bracket.depth == 1:
self.finals = True
return True
else:
return False
class bracket(object):
this_bracket = []
def __init__(self, bracket_list, depth):
self.this_bracket = bracket_list
self.depth = depth
self.bottom_row = []
def get_bottom_row(self):
self.depth = 1
self.bottom_row = []
self.dive(self.this_bracket)
return self.bottom_row
def dive(self, branch):
if not isinstance(branch[0], list): #if it's a pair of games
self.bottom_row.append(branch)
else:
self.depth += 1
return self.dive(branch[0]), self.dive(branch[1])
def set_winners_dive(self, winners_list, index = 0, branch = None, parent = None):
if branch is None:
branch = self.this_bracket.copy()
if not isinstance(branch[0], list): #if it's a pair of games
if branch[0].name in winners_list or branch[1] is None:
winner = branch[0]
if parent is not None:
parent[index] = winner
elif branch[1].name in winners_list:
winner = branch[1]
if parent is not None:
parent[index] = winner
else:
self.set_winners_dive(winners_list, index = 0, branch = branch[0], parent = branch)
self.set_winners_dive(winners_list, index = 1, branch = branch[1], parent = branch)
if parent is None:
self.this_bracket = branch
return branch
def save_league(this_league):
if not league_db.league_exists(this_league.name):
league_db.init_league_db(this_league)
with open(os.path.join(data_dir, league_dir, this_league.name, f"{this_league.name}.league"), "w") as league_file:
league_json_string = jsonpickle.encode(this_league.league, keys=True)
json.dump(league_json_string, league_file, indent=4)
league_db.save_league(this_league)
def load_league_file(league_name):
if league_db.league_exists(league_name):
state = league_db.state(league_name)
this_league = league_structure(league_name)
with open(os.path.join(data_dir, league_dir, league_name, f"{this_league.name}.league")) as league_file:
this_league.league = jsonpickle.decode(json.load(league_file), keys=True, classes=team)
with open(os.path.join(data_dir, league_dir, league_name, f"{this_league.name}.state")) as state_file:
state_dic = json.load(state_file)
this_league.day = state_dic["day"]
this_league.schedule = state_dic["schedule"]
this_league.constraints = state_dic["constraints"]
this_league.game_length = state_dic["game_length"]
this_league.series_length = state_dic["series_length"]
this_league.owner = state_dic["owner"]
this_league.games_per_hour = state_dic["games_per_hour"]
this_league.historic = state_dic["historic"]
this_league.season = state_dic["season"]
try:
this_league.champion = state_dic["champion"]
except:
this_league.champion = None
return this_league

View File

@ -1,39 +1,130 @@
import asyncio, time, datetime, games, json, threading, jinja2, leagues import asyncio, time, datetime, games, json, threading, jinja2, leagues, os, leagues
from flask import Flask, url_for, Response, render_template, request, jsonify from leagues import league_structure
from league_storage import league_exists
from flask import Flask, url_for, Response, render_template, request, jsonify, send_from_directory, abort
from flask_socketio import SocketIO, emit from flask_socketio import SocketIO, emit
import database as db
app = Flask("the-prestige") app = Flask("the-prestige", static_folder='simmadome/build')
app.config['SECRET KEY'] = 'dev' app.config['SECRET KEY'] = 'dev'
#app.config['SERVER_NAME'] = '0.0.0.0:5000' #app.config['SERVER_NAME'] = '0.0.0.0:5000'
socketio = SocketIO(app) socketio = SocketIO(app)
@app.route('/') # Serve React App
def index(): @app.route('/', defaults={'path': ''})
if ('league' in request.args): @app.route('/<path:path>')
return render_template("index.html", league=request.args['league']) def serve(path):
return render_template("index.html") if path != "" and os.path.exists(app.static_folder + '/' + path):
return send_from_directory(app.static_folder, path)
else:
return send_from_directory(app.static_folder, 'index.html')
@app.route('/game') ### API
def game_page():
return render_template("game.html")
@app.route('/api/teams/search')
def search_teams():
query = request.args.get('query')
page_len = int(request.args.get('page_len'))
page_num = int(request.args.get('page_num'))
if query is None:
abort(400, "A query term is required")
result = db.search_teams(query)
if page_len is not None: #pagination should probably be done in the sqlite query but this will do for now
if page_num is None:
abort(400, "A page_len argument must be accompanied by a page_num argument")
result = result[page_num*page_len : (page_num + 1)*page_len]
return jsonify([json.loads(x[0])['name'] for x in result]) #currently all we need is the name but that can change
MAX_SUBLEAGUE_DIVISION_TOTAL = 22;
MAX_TEAMS_PER_DIVISION = 12;
@app.route('/api/leagues', methods=['POST'])
def create_league():
config = json.loads(request.data)
if league_exists(config['name']):
return jsonify({'status':'err_league_exists'}), 400
num_subleagues = len(config['structure']['subleagues'])
if num_subleagues < 1 or num_subleagues % 2 != 0:
return jsonify({'status':'err_invalid_subleague_count'}), 400
num_divisions = len(config['structure']['subleagues'][0]['divisions'])
if num_subleagues * (num_divisions + 1) > MAX_SUBLEAGUE_DIVISION_TOTAL:
return jsonify({'status':'err_invalid_subleague_division_total'}), 400
league_dic = {}
err_teams = []
for subleague in config['structure']['subleagues']:
if subleague['name'] in league_dic:
return jsonify({'status':'err_duplicate_name', 'cause':subleague['name']})
subleague_dic = {}
for division in subleague['divisions']:
if division['name'] in subleague_dic:
return jsonify({'status':'err_duplicate_name', 'cause':f"{subleague['name']}/{division['name']}"}), 400
elif len(division['teams']) > MAX_TEAMS_PER_DIVISION:
return jsonify({'status':'err_too_many_teams', 'cause':f"{subleague['name']}/{division['name']}"})
teams = []
for team_name in division['teams']:
team = games.get_team(team_name)
if team is None:
err_teams.append(team_name)
else:
teams.append(team)
subleague_dic[division['name']] = teams
league_dic[subleague['name']] = subleague_dic
if len(err_teams) > 0:
return jsonify({'status':'err_no_such_team', 'cause': err_teams}), 400
for (key, min_val) in [
('division_series', 1),
('inter_division_series', 1),
('inter_league_series', 1)
]:
if config[key] < min_val:
return jsonify({'status':'err_invalid_optiion_value', 'cause':key}), 400
new_league = league_structure(config['name'])
new_league.setup(
league_dic,
division_games=config['division_series'], # need to add a check that makes sure these values are ok
inter_division_games=config['inter_division_series'],
inter_league_games=config['inter_league_series'],
)
new_league.constraints["division_leaders"] = config["top_postseason"]
new_league.constraints["wild_cards"] = config["wildcards"]
new_league.generate_schedule()
leagues.save_league(new_league)
return jsonify({'status':'success_league_created'})
### SOCKETS
thread2 = threading.Thread(target=socketio.run,args=(app,'0.0.0.0')) thread2 = threading.Thread(target=socketio.run,args=(app,'0.0.0.0'))
thread2.start() thread2.start()
master_games_dic = {} #key timestamp : (game game, {} state) master_games_dic = {} #key timestamp : (game game, {} state)
data_to_send = [] game_states = []
@socketio.on("recieved") @socketio.on("recieved")
def handle_new_conn(data): def handle_new_conn(data):
socketio.emit("states_update", data_to_send, room=request.sid) socketio.emit("states_update", game_states, room=request.sid)
def update_loop(): def update_loop():
global game_states
while True: while True:
game_states = {} game_states = []
game_times = iter(master_games_dic.copy().keys()) game_ids = iter(master_games_dic.copy().keys())
for game_time in game_times: for game_id in game_ids:
this_game, state, discrim_string = master_games_dic[game_time] this_game, state, discrim_string = master_games_dic[game_id]
test_string = this_game.gamestate_display_full() test_string = this_game.gamestate_display_full()
state["leagueoruser"] = discrim_string state["leagueoruser"] = discrim_string
state["display_inning"] = this_game.inning #games need to be initialized with the following keys in state: state["display_inning"] = this_game.inning #games need to be initialized with the following keys in state:
@ -110,6 +201,8 @@ def update_loop():
if this_game.last_update[0]["defender"] != "": if this_game.last_update[0]["defender"] != "":
punc = ". " punc = ". "
if "fc_out" in this_game.last_update[0].keys(): if "fc_out" in this_game.last_update[0].keys():
name, base_string = this_game.last_update[0]['fc_out'] name, base_string = this_game.last_update[0]['fc_out']
updatestring = f"{this_game.last_update[0]['batter']} {this_game.last_update[0]['text'].value.format(name, base_string)} {this_game.last_update[0]['defender']}{punc}" updatestring = f"{this_game.last_update[0]['batter']} {this_game.last_update[0]['text'].value.format(name, base_string)} {this_game.last_update[0]['defender']}{punc}"
@ -121,36 +214,32 @@ def update_loop():
state["update_emoji"] = "🏏" state["update_emoji"] = "🏏"
state["update_text"] = updatestring state["update_text"] = updatestring
if "veil" in this_game.last_update[0].keys():
state["update_emoji"] = "🌌"
state["update_text"] += f" {this_game.last_update[0]['batter']}'s will manifests on {games.base_string(this_game.last_update[1])} base."
elif "error" in this_game.last_update[0].keys():
state["update_emoji"] = "👻"
state["update_text"] = f"{this_game.last_update[0]['batter']}'s hit goes ethereal, and {this_game.last_update[0]['defender']} can't catch it! {this_game.last_update[0]['batter']} reaches base safely."
state["bases"] = this_game.named_bases() state["bases"] = this_game.named_bases()
state["top_of_inning"] = this_game.top_of_inning state["top_of_inning"] = this_game.top_of_inning
game_states[game_time] = state game_states.append([game_id, state])
if state["update_pause"] <= 1 and state["start_delay"] < 0: if state["update_pause"] <= 1 and state["start_delay"] < 0:
if this_game.over: if this_game.over:
state["update_pause"] = 2 state["update_pause"] = 2
if state["end_delay"] < 0: if state["end_delay"] < 0:
master_games_dic.pop(game_time) db.cache_history(this_game.teams['home'].name, this_game.teams["home"].score, this_game.teams['away'].name, this_game.teams['away'].score, this_game.weather.name)
master_games_dic.pop(game_id)
else: else:
state["end_delay"] -= 1 state["end_delay"] -= 1
master_games_dic[game_time][1]["end_delay"] -= 1 master_games_dic[game_id][1]["end_delay"] -= 1
else: else:
this_game.gamestate_update_full() this_game.gamestate_update_full()
state["update_pause"] -= 1 state["update_pause"] -= 1
global data_to_send socketio.emit("states_update", game_states)
data_to_send = [] time.sleep(8)
template = jinja2.Environment(loader=jinja2.FileSystemLoader('templates')).get_template('game_box.html')
for timestamp in game_states:
data_to_send.append({
'timestamp' : timestamp,
'league' : game_states[timestamp]['leagueoruser'] if game_states[timestamp]['is_league'] else '',
'state' : game_states[timestamp],
'html' : template.render(state=game_states[timestamp], timestamp=timestamp)
})
socketio.emit("states_update", data_to_send)
time.sleep(6)

BIN
matteo_bak.db Normal file

Binary file not shown.

View File

@ -1,12 +1,29 @@
#interfaces with onomancer #interfaces with onomancer
import requests, json, urllib import requests, json, urllib
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import database as db import database as db
onomancer_url = "https://onomancer.sibr.dev/api/" onomancer_url = "https://onomancer.sibr.dev/api/"
name_stats_hook = "getOrGenerateStats?name=" name_stats_hook = "getOrGenerateStats?name="
collection_hook = "getCollection?token=" collection_hook = "getCollection?token="
names_hook = "getNames"
def _retry_session(retries=3, backoff=0.3, status=(500, 501, 502, 503, 504)):
session = requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff,
status_forcelist=status,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('https://', adapter)
return session
def get_stats(name): def get_stats(name):
player = db.get_stats(name) player = db.get_stats(name)
@ -14,7 +31,7 @@ def get_stats(name):
return player #returns json_string return player #returns json_string
#yell at onomancer if not in cache or too old #yell at onomancer if not in cache or too old
response = requests.get(onomancer_url + name_stats_hook + urllib.parse.quote_plus(name)) response = _retry_session().get(onomancer_url + name_stats_hook + urllib.parse.quote_plus(name))
if response.status_code == 200: if response.status_code == 200:
stats = json.dumps(response.json()) stats = json.dumps(response.json())
db.cache_stats(name, stats) db.cache_stats(name, stats)
@ -30,9 +47,32 @@ def get_scream(username):
return scream return scream
def get_collection(collection_url): def get_collection(collection_url):
response = requests.get(onomancer_url + collection_hook + urllib.parse.quote(collection_url)) response = _retry_session().get(onomancer_url + collection_hook + urllib.parse.quote(collection_url))
if response.status_code == 200: if response.status_code == 200:
for player in response.json()['lineup'] + response.json()['rotation']: for player in response.json()['lineup'] + response.json()['rotation']:
db.cache_stats(player['name'], json.dumps(player)) db.cache_stats(player['name'], json.dumps(player))
return json.dumps(response.json()) return json.dumps(response.json())
def get_names(limit=20, threshold=1):
"""
Get `limit` random players that have at least `threshold` upvotes.
Returns dictionary keyed by player name of stats.
"""
response = _retry_session().get(
onomancer_url + names_hook,
params={
'limit': limit,
'threshold': threshold,
'with_stats': 1,
'random': 1,
},
)
response.raise_for_status()
res = {}
for stats in response.json():
name = stats['name']
db.cache_stats(name, json.dumps(stats))
res[name] = stats
return res

1
simmadome/.eslintcache Normal file
View File

@ -0,0 +1 @@
[{"/Users/elijah/Documents/Projects/matteo/simmadome/src/index.tsx":"1","/Users/elijah/Documents/Projects/matteo/simmadome/src/reportWebVitals.ts":"2","/Users/elijah/Documents/Projects/matteo/simmadome/src/GamesPage.tsx":"3","/Users/elijah/Documents/Projects/matteo/simmadome/src/GamePage.tsx":"4","/Users/elijah/Documents/Projects/matteo/simmadome/src/CreateLeague.tsx":"5","/Users/elijah/Documents/Projects/matteo/simmadome/src/GamesUtil.tsx":"6","/Users/elijah/Documents/Projects/matteo/simmadome/src/util.tsx":"7","/Users/elijah/Documents/Projects/matteo/simmadome/src/Game.tsx":"8"},{"size":2368,"mtime":1610663769654,"results":"9","hashOfConfig":"10"},{"size":425,"mtime":1610566206674,"results":"11","hashOfConfig":"10"},{"size":4725,"mtime":1610664926203,"results":"12","hashOfConfig":"10"},{"size":1836,"mtime":1610677519051,"results":"13","hashOfConfig":"10"},{"size":18825,"mtime":1610778204901,"results":"14","hashOfConfig":"10"},{"size":1116,"mtime":1610677473305,"results":"15","hashOfConfig":"10"},{"size":961,"mtime":1610694553519,"results":"16","hashOfConfig":"10"},{"size":3089,"mtime":1610572714752,"results":"17","hashOfConfig":"10"},{"filePath":"18","messages":"19","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"1bvn6qu",{"filePath":"20","messages":"21","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"22","messages":"23","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"24","messages":"25","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"26","messages":"27","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"28","messages":"29","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"30","messages":"31","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"32","messages":"33","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"/Users/elijah/Documents/Projects/matteo/simmadome/src/index.tsx",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/reportWebVitals.ts",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/GamesPage.tsx",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/GamePage.tsx",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/CreateLeague.tsx",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/GamesUtil.tsx",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/util.tsx",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/Game.tsx",[]]

24
simmadome/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
.eslintcache
npm-debug.log*
yarn-debug.log*
yarn-error.log*

46
simmadome/README.md Normal file
View File

@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

16792
simmadome/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

56
simmadome/package.json Normal file
View File

@ -0,0 +1,56 @@
{
"name": "simmadome",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:5000",
"dependencies": {
"jquery": "^3.5.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.1",
"socket.io-client": "^3.0.5",
"twemoji": "^13.0.1",
"typescript": "^4.1.3",
"web-vitals": "^0.2.4"
},
"devDependencies": {
"@testing-library/jest-dom": "^5.11.8",
"@testing-library/react": "^11.2.2",
"@testing-library/user-event": "^12.6.0",
"@types/jest": "^26.0.19",
"@types/jquery": "^3.5.5",
"@types/node": "^12.19.12",
"@types/react": "^16.14.2",
"@types/react-dom": "^16.9.10",
"@types/react-router": "^5.1.10",
"@types/react-router-dom": "^5.1.7",
"@types/socket.io-client": "^1.4.34",
"@types/twemoji": "^12.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

View File

@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<title>⚾ The Simmadome</title>
<meta property="og:title" content="Watch at the Simmadome" />
<meta property="og:description" content="The Simsim: Your players, your teams, your games." />
<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@SIBR_XVI">
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@ -0,0 +1,325 @@
.cl_table_header > .cl_subleague_bg {
border-top-left-radius: 0.5rem;
border-top-right-radius: 0.5rem;
padding-top: 1rem;
}
.cl_league_structure_table .cl_table_row:last-child .cl_subleague_bg {
border-bottom-left-radius: 0.5rem;
border-bottom-right-radius: 0.5rem;
padding-bottom: 1rem;
}
.cl_league_structure_table .cl_table_row:last-child .cl_division_delete {
margin-bottom: 0.5rem;
}
input {
border: none;
border-radius: 1rem;
height: 2rem;
padding-left: 1rem;
background: var(--background-secondary);
font-size: 14pt;
}
input:focus {
outline: none;
}
input[type="number"] {
-webkit-appearance: textfield;
-moz-appearance: textfield;
appearance: textfield;
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
}
.cl_league_main {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
margin-top: 3rem;
}
.cl_league_name {
margin-top: 1rem;
}
.cl_league_options, .cl_league_structure, .cl_confirm_box {
display: flex;
background: var(--background-tertiary);
flex-direction: column;
max-width: 100%;
border-radius: 1rem;
padding-top: 1.5rem;
}
.cl_confirm_box {
min-width: 55rem;
padding: 2.5rem;
display: flex;
align-items: center;
justify-content: center;
font-size: 20pt;
}
.cl_league_options {
align-items: center;
}
.cl_league_structure, .cl_subleague_add_align {
display: flex;
align-items: center;
justify-content: center;
width: min-content;
}
.cl_league_structure {
margin-top: 1rem;
}
.cl_league_structure_table {
display: table;
margin-right: 1rem;
}
.cl_headers, .cl_table_row {
display: table-row;
height: min-content;
}
.cl_table_header, .cl_delete_filler, .cl_delete_box, .cl_division_cell {
display: table-cell;
height:100%;
}
.cl_delete_box {
vertical-align: middle;
}
.cl_league_structure_scrollbox {
max-width: 100%;
overflow-y: scroll;
}
/* Hide scrollbar for Chrome, Safari and Opera */
.cl_league_structure_scrollbox::-webkit-scrollbar {
display: none;
}
/* Hide scrollbar for IE, Edge and Firefox */
.cl_league_structure_scrollbox {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
.cl_subleague_add_align{
margin-left: 1.5rem;
padding-right: 1.5rem;
}
.cl_subleague_header {
display: flex;
width:100%;
align-items: center;
justify-content: space-between;
}
.cl_subleague_bg {
background: var(--background-main);
padding: 0.5rem 1rem;
margin: 0rem 0.5rem;
min-width: 22rem;
height: 100%;
box-sizing: border-box;
}
.cl_subleague_name {
flex-grow: 1;
margin-right: 0.5rem;
}
.cl_division_name_box {
width: 100%;
}
.cl_division_name {
margin-bottom: 0.5rem;
width: 95%;
}
.cl_newteam_name {
width: 95%;
}
.cl_division {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 1rem;
border-radius: 0.5rem;
background: var(--background-accent);
}
.cl_team, .cl_team_add {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
margin: 0.4rem 0rem;
}
.cl_team_name {
font-size: 14pt;
padding: 0 0.5rem;
overflow: hidden;
text-overflow: ellipsis;
}
.cl_team_add {
display: flex;
flex-direction: column;
margin-bottom: 0rem;
}
.cl_search_list {
width: 95%;
margin-top: 0.6rem;
padding: 0.5rem;
background: var(--background-tertiary);
border-radius: 0.5rem;
}
.cl_search_result {
padding: 0.2rem 0.4rem;
border-radius: 0.5rem;
}
.cl_search_result:hover {
background: var(--background-main);
}
.cl_league_options {
padding: 1rem;
margin-top: 1.5rem;
width: 55rem;
box-sizing: border-box;
}
.cl_option_main {
display: flex;
flex-direction: row;
justify-content: space-around;
width: 100%;
}
.cl_option_submit_box {
display: flex;
flex-direction: column;
align-items: center;
}
.cl_option_box {
margin: 1rem;
width: max-content;
}
.cl_option_label, .cl_option_err, .cl_structure_err {
margin: 0.25rem;
}
.cl_option_err, .cl_structure_err {
color: var(--accent-red);
}
.cl_option_err {
min-height: 1.5rem;
margin-bottom: -0.5rem;
margin-top: 0.25rem;
}
.cl_structure_err {
margin-bottom: -0.5rem;
}
.cl_structure_err_div {
margin-top: -0.25rem;
margin-bottom: 0;
}
.cl_structure_err_team {
margin-top: -0.5rem;
margin-bottom: 0;
width: 85%;
}
.cl_team_name_err {
color: var(--accent-red);
}
.cl_structure_err_teams {
width: 98%;
}
.cl_subleague_add_filler, .cl_division_add_filler {
width: 2rem;
height: 2rem;
}
/* button styles */
button > .emoji {
margin: 0;
width: 1rem;
height: 1rem;
}
.cl_subleague_delete, .cl_team_delete, .cl_division_delete, .cl_subleague_add, .cl_division_add {
padding: 0;
width: 2rem;
height: 2rem;
border: none;
border-radius: 1rem;
display: flex;
align-items: center;
justify-content: center;
}
.cl_subleague_delete, .cl_team_delete, .cl_division_delete {
background: var(--accent-red);
}
.cl_subleague_add, .cl_division_add {
background: var(--accent-green);
}
.cl_subleague_add, .cl_subleague_add_filler {
position: relative;
top: 1.5rem;
}
.cl_division_add, .cl_division_add_filler {
margin-top: 1.25rem;
margin-bottom: 1.25rem;
}
.cl_delete_filler {
min-width: 3rem;
}
.cl_option_submit {
padding: 1rem 2rem;
height: 2rem;
border: none;
border-radius: 0.75rem;
display: flex;
align-items: center;
justify-content: center;
background: var(--accent-green);
font-size: 14pt;
}

View File

@ -0,0 +1,527 @@
import React, {useState, useRef, useLayoutEffect, useReducer} from 'react';
import {removeIndex, replaceIndex, append, arrayOf, shallowClone, getUID, DistributiveOmit} from './util';
import './CreateLeague.css';
import twemoji from 'twemoji';
// CONSTS
const MAX_SUBLEAGUE_DIVISION_TOTAL = 22;
const MAX_TEAMS_PER_DIVISION = 12;
// STATE CLASSES
class LeagueStructureState {
subleagues: SubleagueState[]
constructor(subleagues: SubleagueState[] = []) {
this.subleagues = subleagues;
}
}
class SubleagueState {
name: string
divisions: DivisionState[]
id: string|number
constructor(divisions: DivisionState[] = []) {
this.name = "";
this.divisions = divisions;
this.id = getUID();
}
}
class DivisionState {
name: string
teams: TeamState[]
id: string|number
constructor() {
this.name = "";
this.teams = [];
this.id = getUID();
}
}
class TeamState {
name: string
id: string|number
constructor(name: string = "") {
this.name = name;
this.id = getUID();
}
}
// STRUCTURE REDUCER
type StructureReducerActions =
{type: 'remove_subleague', subleague_index: number} |
{type: 'add_subleague'} |
{type: 'rename_subleague', subleague_index: number, name: string} |
{type: 'remove_divisions', division_index: number} |
{type: 'add_divisions'} |
{type: 'rename_division', subleague_index: number, division_index: number, name: string} |
{type: 'remove_team', subleague_index: number, division_index: number, name:string} |
{type: 'add_team', subleague_index:number, division_index:number, name:string}
function leagueStructureReducer(state: LeagueStructureState, action: StructureReducerActions): LeagueStructureState {
switch (action.type) {
case 'remove_subleague':
return {subleagues: removeIndex(state.subleagues, action.subleague_index)};
case 'add_subleague':
return {subleagues: append(state.subleagues, new SubleagueState(
arrayOf(state.subleagues[0].divisions.length, i =>
new DivisionState()
)
))}
case 'rename_subleague':
return replaceSubleague(state, action.subleague_index, subleague => {
let nSubleague = shallowClone(subleague);
nSubleague.name = action.name;
return nSubleague;
});
case 'remove_divisions':
return {subleagues: state.subleagues.map(subleague => {
let nSubleague = shallowClone(subleague);
nSubleague.divisions = removeIndex(subleague.divisions, action.division_index)
return nSubleague;
})};
case 'add_divisions':
return {subleagues: state.subleagues.map(subleague => {
let nSubleague = shallowClone(subleague);
nSubleague.divisions = append(subleague.divisions, new DivisionState())
return nSubleague;
})};
case 'rename_division':
return replaceDivision(state, action.subleague_index, action.division_index, division => {
let nDivision = shallowClone(division);
nDivision.name = action.name;
return nDivision;
});
case 'remove_team':
return replaceDivision(state, action.subleague_index, action.division_index, division => {
let nDivision = shallowClone(division);
nDivision.teams = removeIndex(division.teams, division.teams.findIndex(val => val.name === action.name));
return nDivision;
});
case 'add_team':
return replaceDivision(state, action.subleague_index, action.division_index, division => {
let nDivision = shallowClone(division);
nDivision.teams = append(division.teams, new TeamState(action.name));
return nDivision;
});
}
}
function replaceSubleague(state: LeagueStructureState, si: number, func: (val: SubleagueState) => SubleagueState) {
return {subleagues: replaceIndex(state.subleagues, si, func(state.subleagues[si]))}
}
function replaceDivision(state: LeagueStructureState, si: number, di: number, func:(val: DivisionState) => DivisionState) {
return replaceSubleague(state, si, subleague => {
let nSubleague = shallowClone(subleague);
nSubleague.divisions = replaceIndex(subleague.divisions, di, func(subleague.divisions[di]));
return nSubleague;
});
}
// OPTIONS REDUCER
class LeagueOptionsState {
games_series = "3"
intra_division_series = "8"
inter_division_series = "16"
inter_league_series = "8"
top_postseason = "1"
wildcards = "0"
}
type OptionsReducerActions =
{type: 'set_games_series', value: string} |
{type: 'set_intra_division_series', value: string} |
{type: 'set_inter_division_series', value: string} |
{type: 'set_inter_league_series', value: string} |
{type: 'set_top_postseason', value: string} |
{type: 'set_wildcards', value: string}
function LeagueOptionsReducer(state: LeagueOptionsState, action: OptionsReducerActions) {
let newState = shallowClone(state);
switch (action.type) {
case 'set_games_series':
newState.games_series = action.value;
break;
case 'set_intra_division_series':
newState.intra_division_series = action.value;
break;
case 'set_inter_division_series':
newState.inter_division_series = action.value;
break;
case 'set_inter_league_series':
newState.inter_league_series = action.value;
break;
case 'set_top_postseason':
newState.top_postseason = action.value;
break;
case 'set_wildcards':
newState.wildcards = action.value;
break;
}
return newState
}
// CREATE LEAGUE
let initLeagueStructure = {
subleagues: [0, 1].map((val) =>
new SubleagueState([0, 1].map((val) =>
new DivisionState()
))
)
};
function CreateLeague() {
let [name, setName] = useState("");
let [showError, setShowError] = useState(false);
let [nameExists, setNameExists] = useState(false);
let [deletedTeams, setDeletedTeams] = useState<string[]>([]);
let [createSuccess, setCreateSuccess] = useState(false);
let [structure, structureDispatch] = useReducer(leagueStructureReducer, initLeagueStructure);
let [options, optionsDispatch] = useReducer(LeagueOptionsReducer, new LeagueOptionsState());
let self = useRef<HTMLDivElement | null>(null)
useLayoutEffect(() => {
if (self.current) {
twemoji.parse(self.current)
}
})
if (createSuccess) {
return(
<div className="cl_league_main" ref={self}>
<div className="cl_confirm_box">
League created succesfully!
</div>
</div>
);
}
return (
<div className="cl_league_main" ref={self}>
<input type="text" className="cl_league_name" placeholder="League Name" value={name} onChange={(e) => {
setName(e.target.value);
setNameExists(false);
}}/>
<div className="cl_structure_err">{
name === "" && showError ? "A name is required." :
nameExists && showError ? "A league by that name already exists" :
""
}</div>
<LeagueStructre state={structure} dispatch={structureDispatch} deletedTeams={deletedTeams} showError={showError}/>
<div className="cl_league_options">
<LeagueOptions state={options} dispatch={optionsDispatch} showError={showError}/>
<div className="cl_option_submit_box">
<button className="cl_option_submit" onClick={e => {
if (!validRequest(name, structure, options)) {
setShowError(true);
} else {
let req = new XMLHttpRequest();
let data = makeRequest(name, structure, options);
req.open("POST", "/api/leagues", true);
req.setRequestHeader("Content-type", "application/json");
req.onreadystatechange = () => {
if(req.readyState === 4) {
if (req.status === 200) {
setCreateSuccess(true);
}
if (req.status === 400) {
let err = JSON.parse(req.response);
switch (err.status) {
case 'err_league_exists':
setNameExists(true);
break;
case 'err_no_such_team':
setDeletedTeams(err.cause);
break;
}
setShowError(true);
}
}
}
req.send(data);
}
}}>Submit</button>
<div className="cl_option_err">{
!validRequest(name, structure, options) && showError ?
"Cannot create league. Some information is missing or invalid." : ""
}</div>
</div>
</div>
</div>
);
}
function makeRequest(name:string, structure: LeagueStructureState, options:LeagueOptionsState) {
return JSON.stringify({
name: name,
structure: {
subleagues: structure.subleagues.map(subleague => ({
name: subleague.name,
divisions: subleague.divisions.map(division => ({
name: division.name,
teams: division.teams.map(team => team.name)
}))
}))
},
games_per_series: Number(options.games_series),
division_series: Number(options.intra_division_series),
inter_division_series: Number(options.inter_division_series),
inter_league_series: Number(options.inter_league_series),
top_postseason: Number(options.top_postseason),
wildcards: Number(options.wildcards)
});
}
function validRequest(name:string, structure: LeagueStructureState, options:LeagueOptionsState) {
return (
name !== "" &&
validNumber(options.games_series) &&
validNumber(options.intra_division_series) &&
validNumber(options.inter_division_series) &&
validNumber(options.inter_league_series) &&
validNumber(options.top_postseason) &&
validNumber(options.wildcards, 0) &&
structure.subleagues.length % 2 === 0 &&
structure.subleagues.every((subleague, si) =>
subleague.name !== "" &&
!structure.subleagues.slice(0, si).some(val => val.name === subleague.name) &&
subleague.divisions.every((division, di) =>
division.name !== "" &&
division.teams.length >= 2 &&
division.teams.length <= MAX_TEAMS_PER_DIVISION &&
!subleague.divisions.slice(0, di).some(val => val.name === division.name)
)
)
)
}
function validNumber(value: string, min = 1) {
return !isNaN(Number(value)) && Number(value) >= min;
}
// LEAGUE STRUCUTRE
function LeagueStructre(props: {state: LeagueStructureState, dispatch: React.Dispatch<StructureReducerActions>, deletedTeams: string[], showError: boolean}) {
let nSubleagues = props.state.subleagues.length;
let nDivisions = props.state.subleagues[0].divisions.length;
return (
<div className="cl_league_structure">
<div className="cl_league_structure_scrollbox">
<div className="cl_subleague_add_align">
<div className="cl_league_structure_table">
<SubleagueHeaders subleagues={props.state.subleagues} dispatch={props.dispatch} showError={props.showError}/>
<Divisions subleagues={props.state.subleagues} dispatch={props.dispatch} deletedTeams={props.deletedTeams} showError={props.showError}/>
</div>
{ (nSubleagues+1) * (nDivisions+1) < MAX_SUBLEAGUE_DIVISION_TOTAL ?
<button className="cl_subleague_add" onClick={e => props.dispatch({type: 'add_subleague'})}></button> :
<div className="cl_subleague_add_filler"/>
}
</div>
</div>
<div className="cl_structure_err">{props.state.subleagues.length % 2 !== 0 && props.showError ? "Must have an even number of subleagues." : ""}</div>
{ nSubleagues * (nDivisions+2) < MAX_SUBLEAGUE_DIVISION_TOTAL ?
<button className="cl_division_add" onClick={e => props.dispatch({type: 'add_divisions'})}></button>:
<div className="cl_division_add_filler"/>
}
</div>
);
}
function SubleagueHeaders(props: {subleagues: SubleagueState[], dispatch: React.Dispatch<StructureReducerActions>, showError:boolean}) {
return (
<div className="cl_headers">
<div key="filler" className="cl_delete_filler"/>
{props.subleagues.map((subleague, i) => {
let err =
subleague.name === "" ?
"A name is required." :
props.subleagues.slice(0, i).some(val => val.name === subleague.name) ?
"Each subleague must have a different name." :
"";
return (
<div key={subleague.id} className="cl_table_header">
<div className="cl_subleague_bg">
<SubleageHeader state={subleague} canDelete={props.subleagues.length > 1} dispatch={action =>
props.dispatch(Object.assign({subleague_index: i}, action))
}/>
<div className="cl_structure_err">{props.showError ? err : ""}</div>
</div>
</div>
)
})}
</div>
);
}
function SubleageHeader(props: {state: SubleagueState, canDelete: boolean, dispatch:(action: DistributiveOmit<StructureReducerActions, 'subleague_index'>) => void}) {
return (
<div className="cl_subleague_header">
<input type="text" className="cl_subleague_name" placeholder="Subleague Name" value={props.state.name} onChange={e =>
props.dispatch({type: 'rename_subleague', name: e.target.value})
}/>
{props.canDelete ? <button className="cl_subleague_delete" onClick={e => props.dispatch({type: 'remove_subleague'})}></button> : null}
</div>
);
}
function Divisions(props: {subleagues: SubleagueState[], dispatch: React.Dispatch<StructureReducerActions>, deletedTeams: string[], showError: boolean}) {
return (<>
{props.subleagues[0].divisions.map((val, di) => (
<div key={val.id} className="cl_table_row">
<div key="delete" className="cl_delete_box">
{props.subleagues[0].divisions.length > 1 ?
<button className="cl_division_delete" onClick={e => props.dispatch({type: 'remove_divisions', division_index: di})}></button> :
null
}
</div>
{props.subleagues.map((subleague, si) => (
<div key={subleague.id} className="cl_division_cell">
<div className="cl_subleague_bg">
<Division state={subleague.divisions[di]} dispatch={action =>
props.dispatch(Object.assign({subleague_index: si, division_index: di}, action))
}
isDuplicate={subleague.divisions.slice(0, di).some(val => val.name === subleague.divisions[di].name)}
deletedTeams={props.deletedTeams} showError={props.showError} />
</div>
</div>
))}
</div>
))}
</>);
}
function Division(props: {
state: DivisionState,
dispatch: (action: DistributiveOmit<StructureReducerActions, 'subleague_index'|'division_index'>) => void,
isDuplicate: boolean,
deletedTeams: string[],
showError: boolean
}) {
let [newName, setNewName] = useState("");
let [searchResults, setSearchResults] = useState<string[]>([]);
let newNameInput = useRef<HTMLInputElement>(null);
let resultList = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
if (resultList.current) {
twemoji.parse(resultList.current)
}
})
let divisionErr =
props.state.name === "" ?
"A name is required." :
props.isDuplicate ?
"Each division in a subleague must have a different name." :
""
let teamsErr = props.state.teams.length < 2 ? "Must have at least 2 teams." : "";
return (
<div className="cl_division">
<div className="cl_division_name_box">
<input type="text" className="cl_division_name" placeholder="Division Name" key="input" value={props.state.name} onChange={e =>
props.dispatch({type: 'rename_division', name: e.target.value})
}/>
<div className="cl_structure_err cl_structure_err_div">{props.showError ? divisionErr : ""}</div>
</div>
{props.state.teams.map((team, i) => {
let showDeleted = props.showError && props.deletedTeams.includes(team.name)
return (<>
<div className="cl_team" key={team.id}>
<div className={"cl_team_name" + (showDeleted ? " cl_team_name_err" : "")}>{team.name}</div>
<button className="cl_team_delete" onClick={e => props.dispatch({type:'remove_team', name: team.name})}></button>
</div>
<div className="cl_structure_err cl_structure_err_team">{showDeleted ? "This team was deleted" : ""}</div>
</>)
})}
{ props.state.teams.length < MAX_TEAMS_PER_DIVISION ? <>
<div className="cl_team_add">
<input type="text" className="cl_newteam_name" placeholder="Add team..." value={newName} ref={newNameInput}
onChange={e => {
let params = new URLSearchParams({query: e.target.value, page_len: '5', page_num: '0'});
fetch("/api/teams/search?" + params.toString())
.then(response => response.json())
.then(data => setSearchResults(data));
setNewName(e.target.value);
}}/>
</div>
{searchResults.length > 0 && newName.length > 0 ?
(<div className="cl_search_list" ref={resultList}>
{searchResults.map(result =>
<div className="cl_search_result" key={result} onClick={e => {
props.dispatch({type:'add_team', name: result});
setNewName("");
if (newNameInput.current) {
newNameInput.current.focus();
}
}}>{result}</div>
)}
</div>):
null
}</> :
null
}
<div className="cl_structure_err cl_structure_err_teams">{props.showError ? teamsErr : ""}</div>
</div>
);
}
// LEAGUE OPTIONS
function LeagueOptions(props: {state: LeagueOptionsState, dispatch: React.Dispatch<OptionsReducerActions>, showError: boolean}) {
return (
<div className="cl_option_main">
<div className="cl_option_column">
<NumberInput title="Number of games per series" value={props.state.games_series} setValue={(value: string) =>
props.dispatch({type: 'set_games_series', value: value})} showError={props.showError}/>
<NumberInput title="Number of teams from top of division to postseason" value={props.state.top_postseason} setValue={(value: string) =>
props.dispatch({type: 'set_top_postseason', value: value})} showError={props.showError}/>
<NumberInput title="Number of wildcards" value={props.state.wildcards} minValue={0} setValue={(value: string) =>
props.dispatch({type: 'set_wildcards', value: value})} showError={props.showError}/>
</div>
<div className="cl_option_column">
<NumberInput title="Number of series with each division opponent" value={props.state.intra_division_series} setValue={(value: string) =>
props.dispatch({type: 'set_intra_division_series', value: value})} showError={props.showError}/>
<NumberInput title="Number of inter-divisional series" value={props.state.inter_division_series} setValue={(value: string) =>
props.dispatch({type: 'set_inter_division_series', value: value})} showError={props.showError}/>
<NumberInput title="Number of inter-league series" value={props.state.inter_league_series} setValue={(value: string) =>
props.dispatch({type: 'set_inter_league_series', value: value})} showError={props.showError}/>
</div>
</div>
);
}
function NumberInput(props: {title: string, value: string, setValue: (newVal: string) => void, showError: boolean, minValue? : number}) {
let minValue = 1;
if (props.minValue !== undefined) {
minValue = props.minValue
}
return (
<div className="cl_option_box">
<div className="cl_option_label">{props.title}</div>
<input className="cl_option_input" type="number" min={minValue} value={props.value} onChange={e => props.setValue(e.target.value)}/>
<div className="cl_option_err">{(isNaN(Number(props.value)) || Number(props.value) < minValue) && props.showError ? "Must be a number greater than " + minValue : ""}</div>
</div>
);
}
export default CreateLeague;

View File

@ -1,14 +1,4 @@
:root {
--background-main: #2f3136; /*discord dark theme background-secondary - the same color as the embeds*/
--background-secondary: #4f545c; /*discord's background-tertiary*/
--background-accent: #4f545c; /*discord's background-accent*/
--highlight: rgb(113, 54, 138); /*matteo purple™*/
}
.game { .game {
align-self: stretch;
justify-self: stretch;
text-align: center; text-align: center;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@ -19,7 +9,10 @@
border-top: none; border-top: none;
border-right: none; border-right: none;
border-bottom: none; border-bottom: none;
height: max-content; height: min-content;
width: 100%;
min-width: 32rem;
max-width: 44rem;
} }
.header { .header {
@ -27,33 +20,23 @@
background-color: var(--background-secondary); background-color: var(--background-secondary);
border-top-right-radius: 4px; border-top-right-radius: 4px;
height: max-content; height: max-content;
display: flex;
justify-content: space-between
} }
.inning { .header > div {
float: left; margin: 0.3rem 0.5rem;
margin: 5px;
margin-left: 8px;
}
.weather {
float: right;
margin: 5px;
margin-right: 8px;
} }
.body { .body {
margin: 10px; margin: 0.5rem;
display: grid; display: grid;
grid-template-columns: 66% 33%; grid-template-columns: repeat(3, minmax(0, 1fr));
grid-template-areas: grid-template-areas:
"teams info" "teams teams info" "players players info" "update update update";
"players info" grid-template-rows: minmax(5.75rem, min-content) minmax(4rem, min-content) minmax(4rem, min-content);
"update update"; grid-row-gap: 0.5rem;
grid-template-rows: 90px 85px; grid-column-gap: 0.75rem;
grid-row-gap: 4px;
grid-column-gap: 14px;
flex: 1;
} }
.teams { .teams {
@ -61,14 +44,16 @@
display: flex; display: flex;
flex-direction: column; flex-direction: column;
justify-content: space-around; justify-content: space-around;
margin-right: 12px; min-width: 95%;
max-width: 100%;
width: min-content;
} }
.team { .team {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
width: 100%; width: 100%;
margin: 5px 0px; margin: 0.25rem 0rem;
} }
.team_name { .team_name {
@ -84,8 +69,7 @@
align-items: center; align-items: center;
justify-content: space-around; justify-content: space-around;
background: #4f545c; background: #4f545c;
padding: 25px 0px; padding: 0.75rem 0rem;
margin-right: 10px;
border-radius: 4px; border-radius: 4px;
} }
@ -93,14 +77,14 @@
font-size: 10pt; font-size: 10pt;
text-align: left; text-align: left;
height: max-content; height: max-content;
padding: 5px; margin: 0.3rem 0.5rem;
} }
.leagueoruser { .leagueoruser {
font-size: 10pt; font-size: 10pt;
text-align: right; text-align: right;
height: max-content; height: max-content;
padding: 5px; margin: 0.3rem 0.5rem;
} }
.footer { .footer {
@ -132,7 +116,7 @@
} }
.score { .score {
background: var(--background-accent); background: var(--background-secondary);
width: 40px; width: 40px;
min-width: 40px; min-width: 40px;
height: 40px; height: 40px;
@ -142,17 +126,22 @@
.players { .players {
grid-area: players; grid-area: players;
display: flex; display: grid;
flex-direction: column; grid-template-columns: auto minmax(0, 1fr);
justify-content: space-around; grid-template-rows: auto auto;
align-items: start; grid-column-gap: 0.5rem;
margin-left: 0.3rem;
} }
.player { .players > div {
display: flex; margin: 0.25rem 0rem;
align-items: end; }
width: 100%;
flex-direction: column; .player_type {
text-align: end;
font-weight: bolder;
display: inline-block;
vertical-align: middle;
} }
.player_name { .player_name {
@ -160,32 +149,23 @@
text-overflow: ellipsis; text-overflow: ellipsis;
text-align: start; text-align: start;
white-space: nowrap; white-space: nowrap;
width: 95%; width: 100%;
margin-top: -4px;
} }
.update { .update {
grid-area: update; grid-area: update;
margin-right: 10px; min-height: 3.5rem;
margin-top: 5px; padding: 0rem 0.75rem;
min-height: 50px;
padding: 0px 10px;
height: 100%; height: 100%;
background: var(--background-secondary); background: var(--background-secondary);
border-radius: 4px; border-radius: 4px;
align-items: center; align-items: center;
display: flex; display: flex;
justify-content: start; justify-content: flex-start;
}
.player_type {
width: 100%;
text-align: start;
font-weight: bolder;
} }
.update_emoji { .update_emoji {
margin-right: 10px; margin-right: 0.75rem;
margin-left: 2px; margin-left: 2px;
} }
@ -204,38 +184,26 @@
height: 60px; height: 60px;
} }
.base_2 { .field > .base {
margin-bottom: -25% margin-bottom: -25%
} }
@media only screen and (max-device-width: 800px) { @media only screen and (max-device-width: 800px) {
.batting { .game {
font-size: 15pt; font-size: 15pt;
text-align: left;
height: max-content;
padding: 5px;
} }
.leagueoruser { .batting, .leagueoruser {
font-size: 15pt; font-size: 14pt;
text-align: right; padding: 3px;
height: max-content;
padding: 5px;
} }
.team_name, .score { .team_name, .score {
font-size: 23px font-size: 25px
} }
.players { .players {
font-size: 20px; font-size: 20px;
grid-area: players;
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
height: 100%;
padding-right: 50px;
} }
.update_emoji, .update_text { .update_emoji, .update_text {

85
simmadome/src/Game.tsx Normal file
View File

@ -0,0 +1,85 @@
import { GameState } from './GamesUtil';
import twemoji from 'twemoji';
import React, { useRef, useLayoutEffect } from 'react';
import { Link } from 'react-router-dom';
import './Game.css';
import base_filled from './img/base_filled.png';
import base_empty from './img/base_empty.png';
import out_filled from './img/out_out.png';
import out_empty from './img/out_in.png';
function Game(props: {gameId: string, state : GameState}) {
let self: React.MutableRefObject<HTMLDivElement | null> = useRef(null);
useLayoutEffect(() => {
if (self.current) {
twemoji.parse(self.current);
}
})
let state = props.state;
return (
<div className="game" ref={self}>
<div className="header">
<div className="inning">Inning: <span>{state.display_top_of_inning ? "🔼" : "🔽"}</span> {state.display_inning}/{state.max_innings}</div>
<div className="title">{state.title}</div>
<div className="weather">{state.weather_emoji} {state.weather_text}</div>
</div>
<div className="body">
<div className="teams">
<Team name={state.away_name} score={state.away_score}/>
<Team name={state.home_name} score={state.home_score}/>
</div>
<div className="info">
<div className="field">
<Base name={state.bases[2]} />
<div style={{display: "flex"}}>
<Base name={state.bases[3]} />
<Base name={state.bases[1]} />
</div>
</div>
<div className="outs">
<div className="outs_title">OUTS</div>
<div className="outs_count">
{[1, 2].map((out) => <Out thisOut={out} totalOuts={state.outs} key={out} />)}
</div>
</div>
</div>
<div className="players">
<div className="player_type">PITCHER</div>
<div className="player_name">{state.pitcher}</div>
<div className="player_type">BATTER</div>
<div className="player_name batter_name">{state.batter}</div>
</div>
<div className="update">
<div className="update_emoji">{state.update_emoji}</div>
<div className="update_text">{state.update_text}</div>
</div>
</div>
<div className="footer">
<div className="batting">{state.display_top_of_inning ? state.away_name : state.home_name} batting.</div>
<div className="leagueoruser">{state.leagueoruser} (<Link to={"/game/" + props.gameId}>share</Link>)</div>
</div>
</div>
);
}
function Team(props: {name: string, score: number}) {
return (
<div className="team">
<div className="team_name">{ props.name }</div>
<div className="score">{ props.score }</div>
</div>
);
}
function Base(props: {name: string | null}) {
return (
<img className="base" alt={ props.name ?? "" } src={ props.name ? base_filled : base_empty }/>
);
}
function Out(props: {thisOut: number, totalOuts: number}) {
return <img className="out" alt="" src={props.thisOut <= props.totalOuts ? out_filled : out_empty}/>;
}
export default Game;

View File

@ -0,0 +1,37 @@
#game_container {
margin-top: 3rem;
margin-left: 1rem;
margin-right: 1rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-around;
}
.history_box {
width: 100%;
margin-top: 3rem;
padding: 1rem;
padding-top: 0.5rem;
background: var(--background-main);
border-radius: 0.25rem;
width: 100%;
min-width: 32rem;
max-width: 44rem;
box-sizing: border-box;
border: 4px solid;
border-radius: 4px;
border-color: var(--highlight);
border-top: none;
border-right: none;
border-bottom: none;
}
.history_title {
font-size: 14pt;
}
.history_update {
height: 4rem;
margin: 0.5rem;
}

View File

@ -0,0 +1,62 @@
import React, {useState, useRef, useLayoutEffect} from 'react';
import twemoji from 'twemoji';
import ReactRouter from 'react-router';
import {GameState, useListener} from './GamesUtil';
import './GamePage.css';
import Game from './Game';
import {getUID} from './util';
function GamePage(props: ReactRouter.RouteComponentProps<{id: string}>) {
let [game, setGame] = useState<[string, GameState]|undefined>(undefined);
let history = useRef<[number, string, string][]>([]);
useListener((newGames) => {
let newGame = newGames.find((gamePair) => gamePair[0] === props.match.params.id);
setGame(newGame);
console.log(newGame);
if (newGame !== undefined && newGame[1].start_delay < 0 && newGame[1].end_delay > 8) {
history.current.unshift([getUID(), newGame[1].update_emoji, newGame[1].update_text]);
if (history.current.length > 8) {
history.current.pop();
}
}
});
if (game === undefined) {
return <div id="game_container">The game you're looking for either doesn't exist or has already ended.</div>
}
return (
<div id="game_container">
<Game gameId={game[0]} state={game[1]}/>
{ history.current.length > 0 ?
<GameHistory history={history.current}/> :
null
}
</div>
);
}
function GameHistory(props: {history: [number, string, string][]}) {
let self = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
if (self.current) {
twemoji.parse(self.current);
}
})
return (
<div className="history_box" ref={self}>
<div className="history_title">History</div>
{props.history.map((update) => (
<div className="update history_update" key={update[0]}>
<div className="update_emoji">{update[1]}</div>
<div className="update_text">{update[2]}</div>
</div>
))}
</div>
);
}
export default GamePage;

View File

@ -1,14 +1,20 @@
.container { .container {
display: grid; display: grid;
grid-template-columns: repeat(3, minmax(500px, 1fr)); grid-template-columns: repeat(auto-fill, minmax(32rem, 1fr));
grid-gap: 50px 30px; /*space between rows, then columns*/ grid-gap: 50px 30px; /*space between rows, then columns*/
align-items: center;
justify-items: center;
grid-auto-flow: row; grid-auto-flow: row;
} }
.container > div { .slot_container {
min-height: 325px; display: flex;
justify-content: space-around;
}
.emptyslot, .game {
min-height: 18.75rem;
max-width: 44rem;
min-width: 32rem;
width: 100%;
} }
#filters { #filters {
@ -21,15 +27,15 @@
} }
#filters > * { #filters > * {
padding: 4px 8px; padding: 0.25rem 0.5rem;
margin: 0px 8px; margin: 0rem 0.5rem;
font-size: 16pt; font-size: 16pt;
background: rgba(0,0,0,0); background: rgba(0,0,0,0);
} }
#filters > .filter { #filters > .filter {
border-radius: 8px; border-radius: 0.5rem;
min-width: 100px; min-width: 6.25rem;
text-align: center; text-align: center;
border: none; border: none;
color: white; color: white;
@ -45,21 +51,19 @@
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
width: 100%; width: 100%;
height: 75px; height: 4.5rem;
} }
#footer > div { #footer > div {
text-align: center; text-align: center;
font-size: 20px; font-size: 16pt;
position: relative; position: relative;
top: 5px; top: 0.25rem;
} }
.emptyslot { .emptyslot {
border: 2px dashed white; border: 2px dashed white;
border-radius: 15px; border-radius: 15px;
align-self: stretch;
justify-self: stretch;
text-align: center; text-align: center;
color: white; color: white;
} }
@ -68,24 +72,8 @@
.container { .container {
display: grid; display: grid;
grid-template-columns: repeat(1, minmax(700px, 90%)); grid-template-columns: repeat(1, minmax(700px, 90%));
grid-template-rows: 400px;
grid-gap: 50px 30px; /*space between rows, then columns*/
align-items: center;
justify-items: center;
grid-auto-rows: 400px;
grid-auto-flow: row;
position: absolute; position: absolute;
left: 50%; left: 50%;
transform: translate(-50%, 0); transform: translate(-50%, 0);
} }
.emptyslot {
border: none;
border-radius: 15px;
align-self: stretch;
justify-self: stretch;
text-align: center;
color: white;
flex: 1;
}
} }

142
simmadome/src/GamesPage.tsx Normal file
View File

@ -0,0 +1,142 @@
import React, {useState, useRef, useEffect, useLayoutEffect} from 'react';
import {GameState, GameList, useListener} from './GamesUtil';
import {Link} from 'react-router-dom';
import './GamesPage.css';
import Game from './Game';
function GamesPage() {
let [search, setSearch] = useState(window.location.search);
useEffect(() => {
setSearch(window.location.search);
//eslint-disable-next-line react-hooks/exhaustive-deps
}, [window.location.search])
let searchparams = new URLSearchParams(search);
let filter = searchparams.get('league') ?? ""
let [games, setGames] = useState<[string, GameState][]>([]);
useListener(setGames);
let filters = useRef(filter !== "" ? [filter] : []);
games.forEach((game) => { if (game[1].is_league && !filters.current.includes(game[1].leagueoruser)) { filters.current.push(game[1].leagueoruser) }});
filters.current = filters.current.filter((f) => games.find((game) => game && game[1].is_league && game[1].leagueoruser === f) || f === filter);
let gameList = useRef<(string | null)[]>([]);
let filterGames = games.filter((game, i) => filter === "" || game[1].leagueoruser === filter);
updateList(gameList.current, filterGames, searchparams.get('game'));
return (
<>
<Filters filterList={filters.current} selectedFilter={filter} />
<Grid gameList={gameList.current.map((val) => val !== null ? filterGames.find((game) => game[0] === val) as [string, GameState] : null )}/>
<Footer has_games={filterGames.length > 0}/>
</>
);
}
// adds and removes games from list to keep it up to date, without relocating games already in place
function updateList(gameList: (string | null)[], games: [string, GameState][], firstGame: string | null) {
// insert firstGame into first slot, if necessary
if (firstGame !== null && games.find((game) => game[0] === firstGame)) {
if (gameList.includes(firstGame)) {
gameList[gameList.indexOf(firstGame)] = null;
}
gameList[0] = firstGame;
}
//remove games no longer present
for (let i = 0; i < gameList.length; i ++) {
if (gameList[i] !== null && games.findIndex((val) => val[0] === gameList[i]) < 0) {
gameList[i] = null;
}
}
// add games not present
for (let game of games) {
if (!gameList.find((val) => val !== null && val === game[0])) {
let firstEmpty = gameList.indexOf(null);
if (firstEmpty < 0) {
gameList.push(game[0])
} else {
gameList[firstEmpty] = game[0];
}
}
}
//remove trailing empty cells
while (gameList[gameList.length-1] === null) {
gameList.pop();
}
}
function Filters (props: {filterList: string[], selectedFilter: string}) {
function Filter(innerprops: {title: string, filter:string} ) {
let search = new URLSearchParams();
search.append('league', innerprops.filter);
return (
<Link to={innerprops.filter !== "" ? "/?" + search.toString() : "/"} className="filter" id={innerprops.filter === props.selectedFilter ? "selected_filter" : ""}>
{innerprops.title}
</Link>
);
}
return (
<div id="filters">
<div>Filter:</div>
<Filter title="All" filter="" key="" />
{props.filterList.map((filter: string) =>
<Filter title={filter} filter={filter} key={filter} />
)}
</div>
);
}
function Grid(props: { gameList: GameList }) {
let self: React.RefObject<HTMLElement> = useRef(null);
let [numcols, setNumcols] = useState(3);
let newList = [...props.gameList];
while (newList.length === 0 || newList.length % numcols !== 0) {
newList.push(null);
}
function getCols() {
if (self.current !== null) {
//this is a hack, but there's weirdly no "real" way to get the number of columns
return window.getComputedStyle(self.current).getPropertyValue('grid-template-columns').split(' ').length;
} else {
return 3;
}
}
//set num cols after page loads, then add listener to update if window resizes
useLayoutEffect(() => {
setNumcols(getCols());
window.addEventListener('resize', (event) => {
setNumcols(getCols());
})
}, [])
let emptyKey = 0;
return (
<section className="container" id="container" ref={self}>
{newList.map((game) => (
<div className="slot_container" key={game ? game[0] : emptyKey++}>
{game ? <Game gameId={game[0]} state={game[1]}/> : <div className="emptyslot"/>}
</div>
))}
</section>
);
}
function Footer(props: { has_games: boolean }) {
let text = props.has_games ? "" : "No games right now. Why not head over to Discord and start one?";
return (
<div id="footer">
<div>{text}</div>
</div>
);
}
export default GamesPage;

View File

@ -0,0 +1,42 @@
import {useLayoutEffect} from 'react';
import io from 'socket.io-client';
interface GameState {
bases: (string | null)[];
outs: number;
display_top_of_inning: boolean
display_inning: number
max_innings: number
title: string
weather_emoji: string
weather_text: string
away_name: string
away_score: number
home_name: string
home_score: number
pitcher: string
batter: string
update_emoji: string
update_text: string
is_league: boolean
leagueoruser: string
start_delay: number
end_delay: number
}
type GameList = ([id: string, game: GameState] | null)[];
// connects to the given url (or host if none) and waits for state updates
const useListener = (onUpdate: (update: [string, GameState][]) => void, url: string | null = null) => {
useLayoutEffect(() => {
let socket = url ? io(url) : io();
socket.on('connect', () => socket.emit('recieved', {}));
socket.on('states_update', onUpdate);
return () => {socket.disconnect()};
//eslint-disable-next-line react-hooks/exhaustive-deps
}, [url])
}
export { useListener };
export type { GameState, GameList };

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

Before

Width:  |  Height:  |  Size: 8.9 KiB

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 256 KiB

View File

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

BIN
simmadome/src/img/twitter.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

111
simmadome/src/index.css Normal file
View File

@ -0,0 +1,111 @@
@import url('https://fonts.googleapis.com/css2?family=Alegreya&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Goldman:wght@700&display=swap');
:root {
--background-main: #2f3136;
--background-secondary: #4f545c;
--background-tertiary: #202225;
--background-accent: #40444b;
--highlight: rgb(113, 54, 138); /*matteo purple™*/
--accent-red: #f04747;
--accent-green: rgb(67, 181, 129);
}
body {
background-image: url("img/naturalblack.png");
}
/* Background pattern from Toptal Subtle Patterns */
* {
font-family: 'Alegreya', serif;
color: white;
}
h2 {
text-align: center;
}
.link{
position: relative;
top: 10px;
}
.h1 {
margin: auto;
width: 45%;
color: white;
}
.page_header {
color: white;
font-family: 'Goldman', cursive;
text-decoration: none;
}
#header {
width: 100%;
height: max-content;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#header .page_header {
margin: auto;
}
#link_div {
text-align: right;
position: absolute;
top: 1rem;
right: 2rem;
display: flex;
}
.github_logo, .twitter_logo, .patreon_container {
height: 2rem;
width: 2rem;
margin-left: 0.75rem;
}
.patreon_container {
border-radius: 1rem;
background: #FF424D;
}
.patreon_logo {
box-sizing: border-box;
padding: 0.35rem;
height: 2rem;
width: 2rem;
position: relative;
left: 0.1rem;
bottom: 0.05rem;
}
a {
background-color: transparent;
text-decoration: underline;
}
a:link, a:visited {
color: lightblue;
}
a:hover {
color: white;
}
#utility_links {
position: absolute;
top: 1rem;
left: 2rem;
}
img.emoji {
height: 1em;
width: 1em;
margin: 0 .05em 0 .1em;
vertical-align: -0.1em;
}

57
simmadome/src/index.tsx Normal file
View File

@ -0,0 +1,57 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import './index.css';
import GamesPage from './GamesPage';
import GamePage from './GamePage';
import CreateLeague from './CreateLeague';
import discordlogo from "./img/discord.png";
import reportWebVitals from './reportWebVitals';
import patreonLogo from './img/patreon.png';
import githubLogo from './img/github.png';
import twitterLogo from './img/twitter.png';
ReactDOM.render(
<React.StrictMode>
<Router>
<Header />
<Switch>
<Route path="/game/:id" component={GamePage}/>
<Route path="/create_league" component={CreateLeague} />
<Route path="/" component={GamesPage}/>
</Switch>
</Router>
</React.StrictMode>,
document.getElementById('root')
);
function Header() {
return (
<div id="header">
<div id="link_div">
<a href="https://www.patreon.com/sixteen" className="patreon_link" target="_blank" rel="noopener noreferrer">
<div className="patreon_container">
<img className="patreon_logo" src={patreonLogo} alt="Patreon"/>
</div>
</a>
<a href="https://github.com/Sakimori/matteo-the-prestige" className="github_link" target="_blank" rel="noopener noreferrer">
<img className="github_logo" src={githubLogo} alt="Github"/>
</a>
<a href="https://twitter.com/intent/follow?screen_name=SIBR_XVI" className="twitter_link" target="_blank" rel="noopener noreferrer">
<img className="twitter_logo" src={twitterLogo} alt="Twitter"/>
</a>
</div>
<div id="utility_links">
<Link to="/create_league">Create a League</Link>
</div>
<a href="/" className="page_header"><h2 className="page_header" style={{fontSize:"50px"} as React.CSSProperties}>THE SIMMADOME</h2></a>
<h2 className="page_header">Join SIBR on <a href="https://discord.gg/UhAajY2NCW" className="link"><img src={discordlogo} alt="" height="30"/></a> to start your own games!</h2>
</div>
);
}
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

1
simmadome/src/react-app-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="react-scripts" />

View File

@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

34
simmadome/src/util.tsx Normal file
View File

@ -0,0 +1,34 @@
function removeIndex(arr: any[], index: number) {
return arr.slice(0, index).concat(arr.slice(index+1));
}
function replaceIndex<T>(arr: T[], index: number, val: T) {
return arr.slice(0, index).concat([val]).concat(arr.slice(index+1));
}
function append<T>(arr: T[], val: T) {
return arr.concat([val]);
}
function arrayOf<T>(length: number, func: (i: number) => T): T[] {
var out: T[] = [];
for (var i = 0; i < length; i++) {
out.push(func(i));
}
return out;
}
function shallowClone<T>(obj: T): T {
return Object.assign({}, obj);
}
let getUID = function() { // does NOT generate UUIDs. Meant to create list keys ONLY
let id = 0;
return function() { return id++ }
}()
type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never;
//type DistributivePick<T, K extends keyof T> = T extends any ? Pick<T, K> : never;
export {removeIndex, replaceIndex, append, arrayOf, shallowClone, getUID};
export type {DistributiveOmit};

26
simmadome/tsconfig.json Normal file
View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}

View File

@ -6,4 +6,4 @@ SELECT name,
ROUND(strikeouts_given*27.0/(outs_pitched*1.0),3) as kper9, ROUND(strikeouts_given*27.0/(outs_pitched*1.0),3) as kper9,
ROUND(strikeouts_given*1.0/walks_allowed*1.0,3) as kperbb ROUND(strikeouts_given*1.0/walks_allowed*1.0,3) as kperbb
FROM stats WHERE outs_pitched > 150 FROM stats WHERE outs_pitched > 150
ORDER BY bbper9 ASC; ORDER BY era ASC;

View File

@ -1,64 +0,0 @@
@import url('https://fonts.googleapis.com/css2?family=Alegreya&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Goldman:wght@700&display=swap');
body {
background-image: url("prism.png");
}
/* Background pattern from Toptal Subtle Patterns */
div, button, h1, h2, a {
font-family: 'Alegreya', serif;
color: white;
}
h2 {
text-align: center;
}
.link{
position: relative;
top: 10px;
}
.h1 {
margin: auto;
width: 45%;
color: white;
}
.page_header {
color: white;
font-family: 'Goldman', cursive;
}
#header {
width: 100%;
height: max-content;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#header > .page_header {
margin: auto
}
#link_div {
text-align: right;
position: absolute;
top: 0px;
right: 30px;
}
#link_div > a {
background-color: transparent;
text-decoration: underline;
}
#link_div > a:link, #link_div > a:visited {
color: lightblue;
}
#link_div > a:hover {
color: white;
}

View File

@ -1,9 +0,0 @@
#game_container {
margin-top: 50px;
display: flex;
justify-content: space-around;
}
.game {
width: 33%;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

View File

@ -1,23 +0,0 @@
$(document).ready(function (){
var socket = io.connect();
socket.on('connect', function () {
console.log("connected")
socket.emit('recieved', {});
});
socket.on("states_update", function (json) { //json is an object containing all game updates
console.log(json)
var searchparams = new URLSearchParams(window.location.search);
var exists = false;
for (game of json) {
if (searchparams.get('timestamp') == game.timestamp) {
$('.game').html(game.html);
exists = true;
}
}
if (!exists) {
// inform the user the game has ended
}
});
});

View File

@ -1,167 +0,0 @@
var socket = io.connect();
var lastupdate;
var grid;
$(document).ready(function (){
grid = document.getElementById("container")
socket.on('connect', function () {
socket.emit('recieved', {});
});
socket.on("states_update", function (json) { //json is an object containing all game updates
lastupdate = json;
updateGames(json, $('#selected_filter').text());
updateLeagues(json);
});
});
const updateGames = (json, filter) => {
filterjson = [];
for (var game of json) {
if (game.league == filter || filter == "All") {
filterjson.push(game);
}
}
if (filterjson.length == 0) {
$('#footer div').html("No games right now. Why not head over to Discord and start one?");
} else {
$('#footer div').html("");
}
var searchparams = new URLSearchParams(window.location.search);
if (searchparams.has('game') && filterjson.some(x => x.timestamp == searchparams.get('game')) && grid.children[0].timestamp != searchparams.get('game')) {
var game = filterjson.find(x => x.timestamp == searchparams.get('game'))
var oldbox = Array.prototype.slice.call(grid.children).find(x => x.timestamp == game.timestamp)
if (oldbox) { clearBox(oldbox) }
insertGame(0, game)
}
//replace games that have ended with empty slots
for (var slotnum = 0; slotnum < grid.children.length; slotnum++) {
if (grid.children[slotnum].className == "game" && !filterjson.some((x) => x.timestamp == grid.children[slotnum].timestamp)) {
clearBox(grid.children[slotnum])
}
}
for (var game of filterjson) {
//updates game in list
for (var slotnum = 0; slotnum < grid.children.length; slotnum++) {
if (grid.children[slotnum].timestamp == game.timestamp) {
insertGame(slotnum, game);
};
};
//adds game to list if not there already
if (!Array.prototype.slice.call(grid.children).some(x => x.timestamp == game.timestamp)) {
for (var slotnum = 0; true; slotnum++) { //this is really a while loop but shh don't tell anyone
if (slotnum >= grid.children.length) {
for (var i = 0; i < 3; i ++) {
insertEmpty(grid);
}
}
if (grid.children[slotnum].className == "emptyslot") {
insertGame(slotnum, game);
break;
};
};
}
};
//remove last rows if not needed
while (grid.children[grid.children.length-1].className == "emptyslot" &&
grid.children[grid.children.length-2].className == "emptyslot" &&
grid.children[grid.children.length-3].className == "emptyslot" &&
grid.children.length > 3) {
for (var i = 0; i < 3; i++) {
grid.removeChild(grid.children[grid.children.length-1]);
}
}
}
const insertEmpty = (grid) => {
var newBox = document.createElement("DIV");
newBox.className = "emptyslot";
grid.appendChild(newBox);
}
const insertGame = (gridboxnum, game) => {
var thisBox = grid.children[gridboxnum];
thisBox.innerHTML = game.html;
thisBox.className = "game";
thisBox.timestamp = game.timestamp;
};
const insertLeague = (league) => {
var btn = document.createElement("BUTTON");
btn.className = "filter";
btn.innerHTML = league;
$('#filters').append(btn);
return btn;
}
const clearBox = (box) => {
box.className = "emptyslot";
box.timestamp = null;
box.innerHTML = "";
}
const updateLeagues = (games) => {
//get all leagues
var leagues = []
for (var game of games) {
if (game.league != "" && !leagues.includes(game.league)) {
leagues.push(game.league)
}
}
//remove leagues no longer present
$('#filters .filter').each(function(index) {
if (!leagues.includes($(this).text())) {
if (this.id != 'selected_filter' && $(this).text() != "All") { //don't remove the currently selected filter or the "all" filter
$(this).remove();
}
} else {
leagues.splice(leagues.indexOf($(this).text()), 1);
}
})
// add leagues not already present
for (var league of leagues) { // we removed the entries that are already there in the loop above
insertLeague(league)
}
//add click handlers to each filter
$('#filters .filter').each(function(index) {
this.onclick = function() {
if ($('#filters #selected_filter').text() == 'All') {
updateGames([], ""); // clear grid when switching off of All, to make games collapse to top
}
$('#filters #selected_filter').attr('id', '');
this.id = 'selected_filter';
var search = new URLSearchParams();
search.append('league', this.textContent);
history.pushState({}, "", "/" + (this.textContent != 'All' ? "?" + search.toString() : ""));
updateGames(lastupdate, this.textContent);
}
})
}
window.onpopstate = function(e) {
var searchparams = new URLSearchParams(window.location.search);
updateLeagues(lastupdate);
$('#filters #selected_filter').attr('id', '');
if (searchparams.has('league')) {
var filter_found = false
$('#filters .filter').each(function(i) { if (this.textContent == searchparams.get('league')) { this.id = 'selected_filter'; filter_found = true }});
if (!filter_found) { insertLeague(searchparams.get('league')).id = 'selected_filter' }
updateGames(lastupdate, searchparams.get('league'));
} else {
$('#filters .filter').each(function(i) { if (this.textContent == 'All') { this.id = 'selected_filter' }})
updateGames(lastupdate, "All");
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

BIN
templates/.DS_Store vendored

Binary file not shown.

View File

@ -1,6 +1,7 @@
<html lang="en-US"> <html lang="en-US">
<head> <head>
<script src="//code.jquery.com/jquery-3.5.1.min.js"></script> <script src="//code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://twemoji.maxcdn.com/v/latest/twemoji.min.js" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js"></script>
<script type="text/javascript" async src="https://platform.twitter.com/widgets.js"></script> <script type="text/javascript" async src="https://platform.twitter.com/widgets.js"></script>
@ -18,12 +19,10 @@
<body> <body>
<div id="header"> <div id="header">
<div id="link_div"> <div id="link_div">
<a href="https://www.patreon.com/sixteen" class="link" target="_blank" rel="noopener noreferrer">Patreon</a><br /> <a href="https://github.com/kevroded/matteo-the-prestige" class="link" target="_blank" rel="noopener noreferrer">Github</a><br />
<a href="https://github.com/Sakimori/matteo-the-prestige" class="link" target="_blank" rel="noopener noreferrer">Github</a><br />
<a href="https://twitter.com/intent/follow?screen_name=SIBR_XVI" class="link" target="_blank" rel="noopener noreferrer">Twitter</a>
</div> </div>
<h2 class="page_header" style="font-size: 50px;">THE SIMMADOME</h2> <a href="/" class="page_header"><h2 class="page_header" style="font-size: 50px;">THE SIMMADOME</h2></a>
<h2 class="page_header">Join SIBR on <a href="https://discord.gg/UhAajY2NCW" class="link"><img src="static/discord.png" height="30"></a> to start your own games!</h2> <h2 class="page_header">Games available via the blaseball channel <img src="static/discord.png" height="30"></h2>
</div> </div>
{% block body %}{% endblock %} {% block body %}{% endblock %}
</body> </body>

View File

@ -1,11 +0,0 @@
{% extends "base.html" %}
{% block head_tags %}
<link rel="stylesheet" href="/static/css/game.css">
<link rel="stylesheet" href="/static/css/game_page.css">
<script type="text/javascript" src="static/js/game_loader.js"></script>
{% endblock %}
{% block body %}
<div id="game_container">
<div class="game"></div>
</div>
{% endblock %}

View File

@ -1,56 +0,0 @@
{% macro base(number) -%}
src={% if state.bases[number] %}"/static/img/base_filled.png" alt="{{state.bases[number]}}"{% else %}"/static/img/base_empty.png"{% endif %}
{%- endmacro %}
{% macro out(number) -%}
{% if number <= state.outs %}/static/img/out_out.png{% else %}/static/img/out_in.png{% endif %}
{%- endmacro %}
<div class="header">
<div class="inning">Inning: {% if state.display_top_of_inning == true %}🔼{% else %}🔽{% endif %} {{ state.display_inning }}/{{ state.max_innings }}</div>
<div class="weather">{{ state.weather_emoji }} {{ state.weather_text }}</div>
</div>
<div class="body">
<div class="teams">
<div class="team">
<div class="team_name">{{ state.away_name }}</div>
<div class="score">{{ state.away_score }}</div>
</div>
<div class="team">
<div class="team_name">{{ state.home_name }}</div>
<div class="score">{{ state.home_score }}</div>
</div>
</div>
<div class="info">
<div class="field">
<img class="base base_2" {{ base(2) }}/>
<div style="display: flex;">
<img class="base base_3" {{ base(3) }}/>
<img class="base base_1" {{ base(1) }}/>
</div>
</div>
<div class="outs">
<div class="outs_title">OUTS</div>
<div class="outs_count">
<img class="out" src="{{ out(1) }}"/>
<img class="out" src="{{ out(2) }}"/>
</div>
</div>
</div>
<div class="players">
<div class="player pitcher">
<div class="player_type">PITCHER</div>
<div class="player_name pitcher_name">{{ state.pitcher }}</div>
</div>
<div class="player batter">
<div class="player_type">BATTER</div>
<div class="player_name batter_name">{{ state.batter }}</div>
</div>
</div>
<div class="update">
<div class="update_emoji">{{ state.update_emoji }}</div>
<div class="update_text">{{ state.update_text }}</div>
</div>
</div>
<div class="footer">
<div class="batting">{% if state.display_top_of_inning == true %}{{ state.away_name }}{% else %}{{ state.home_name }}{% endif %} batting.</div>
<div class="leagueoruser">{{ state.leagueoruser }} (<a href="/game?timestamp={{ timestamp }}">share</a>)</div>
</div>

View File

@ -1,21 +0,0 @@
{% extends "base.html" %}
{% block head_tags %}
<link rel="stylesheet" href="/static/css/games_page.css">
<link rel="stylesheet" href="/static/css/game.css">
<script type="text/javascript" src="static/js/grid_loader.js"></script>
{% endblock %}
{% block body %}
<div id="filters">
<div>Filter:</div>
<button class="filter" {% if not league %}id="selected_filter"{% endif %}>All</button>
{% if league %}<button class="filter" id="selected_filter">{{ league }}</button>{% endif %}
</div>
<section class="container" id="container">
<div class="emptyslot"></div>
<div class="emptyslot"></div>
<div class="emptyslot"></div>
</section>
<div id="footer">
<div></div>
</div>
{% endblock %}

View File

@ -32,6 +32,9 @@
<Compile Include="leagues.py"> <Compile Include="leagues.py">
<SubType>Code</SubType> <SubType>Code</SubType>
</Compile> </Compile>
<Compile Include="league_storage.py">
<SubType>Code</SubType>
</Compile>
<Compile Include="main_controller.py"> <Compile Include="main_controller.py">
<SubType>Code</SubType> <SubType>Code</SubType>
</Compile> </Compile>
@ -61,10 +64,6 @@
<Content Include="ids" /> <Content Include="ids" />
<Content Include="matteo.db" /> <Content Include="matteo.db" />
<Content Include="static\discord.png" /> <Content Include="static\discord.png" />
<Content Include="static\game.html" />
<Content Include="static\games_page.css" />
<Content Include="static\loader.js" />
<Content Include="static\prism.png" />
<Content Include="templates\game.html" /> <Content Include="templates\game.html" />
<Content Include="templates\index.html" /> <Content Include="templates\index.html" />
</ItemGroup> </ItemGroup>

153
the_draft.py Normal file
View File

@ -0,0 +1,153 @@
from collections import namedtuple
import games
import json
import uuid
import onomancer
DRAFT_SIZE = 20
REFRESH_DRAFT_SIZE = 4 # fewer players remaining than this and the list refreshes
DRAFT_ROUNDS = 13
Participant = namedtuple('Participant', ['handle', 'team'])
BOOKMARK = Participant(handle="bookmark", team=None) # keep track of start/end of draft round
class Draft:
"""
Represents a draft party with n participants constructing their team from a pool
of names.
"""
@classmethod
def make_draft(cls):
draft = cls()
return draft
def __init__(self):
self._id = str(uuid.uuid4())[:6]
self._participants = []
self._active_participant = BOOKMARK # draft mutex
self._players = onomancer.get_names(limit=DRAFT_SIZE)
self._round = 0
@property
def round(self):
"""
Current draft round. 1 indexed.
"""
return self._round
@property
def active_drafter(self):
"""
Handle of whomever is currently up to draft.
"""
return self._active_participant.handle
@property
def active_drafting_team(self):
return self._active_participant.team.name
def add_participant(self, handle, team_name, slogan):
"""
A participant is someone participating in this draft. Initializes an empty team for them
in memory.
`handle`: discord @ handle, for ownership and identification
"""
team = games.team()
team.name = team_name
team.slogan = slogan
self._participants.append(Participant(handle=handle, team=team))
def start_draft(self):
"""
Call after adding all participants and confirming they're good to go.
"""
self.advance_draft()
def refresh_players(self):
self._players = onomancer.get_names(limit=DRAFT_SIZE)
def advance_draft(self):
"""
The participant list is treated as a circular queue with the head being popped off
to act as the draftign mutex.
"""
if self._active_participant == BOOKMARK:
self._round += 1
self._participants.append(self._active_participant)
self._active_participant = self._participants.pop(0)
def get_draftees(self):
return list(self._players.keys())
def draft_player(self, handle, player_name):
"""
`handle` is the participant's discord handle.
"""
if self._active_participant.handle != handle:
raise ValueError(f'{self._active_participant.handle} is drafting, not you')
player_name = player_name.strip()
player = self._players.get(player_name)
if not player:
# might be some whitespace shenanigans
for name, stats in self._players.items():
if name.replace('\xa0', ' ').strip().lower() == player_name.lower():
player = stats
break
else:
# still not found
raise ValueError(f'Player `{player_name}` not in draft list')
del self._players[player['name']]
if len(self._players) <= REFRESH_DRAFT_SIZE:
self.refresh_players()
if self._round < DRAFT_ROUNDS:
self._active_participant.team.add_lineup(games.player(json.dumps(player)))
elif self._round == DRAFT_ROUNDS:
self._active_participant.team.add_pitcher(games.player(json.dumps(player)))
self.advance_draft()
if self._active_participant == BOOKMARK:
self.advance_draft()
return player
def get_teams(self):
teams = []
if self._active_participant != BOOKMARK:
teams.append((self._active_participant.handle, self._active_participant.team))
for participant in self._participants:
if participant != BOOKMARK:
teams.append((participant.handle, participant.team))
return teams
def finish_draft(self):
for handle, team in self.get_teams():
success = games.save_team(team, int(handle[3:-1]))
if not success:
raise Exception(f'Error saving team for {handle}')
if __name__ == '__main__':
# extremely robust testing OC do not steal
DRAFT_ROUNDS = 2
draft = Draft.make_draft()
draft.add_participant('@bluh', 'Bluhstein Bluhs', 'bluh bluh bluh')
draft.add_participant('@what', 'Barcelona IDK', 'huh')
draft.start_draft()
while draft.round <= DRAFT_ROUNDS:
print(draft.get_draftees())
cmd = input(f'{draft.round} {draft.active_drafter}:')
drafter, player = cmd.split(' ', 1)
try:
draft.draft_player(drafter, player)
except ValueError as e:
print(e)
print(draft.get_teams())

File diff suppressed because it is too large Load Diff