@ywkrlerche/richardwho 1.0.36 → 1.0.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (452) hide show
  1. package/app.js +1316 -332
  2. package/config.js +10 -0
  3. package/games.json +1 -1
  4. package/index.html +165 -76
  5. package/logos/gn-101.webp +0 -0
  6. package/logos/gn-105.webp +0 -0
  7. package/logos/gn-107.webp +0 -0
  8. package/logos/gn-110.webp +0 -0
  9. package/logos/gn-113.webp +0 -0
  10. package/logos/gn-115.webp +0 -0
  11. package/logos/gn-116.webp +0 -0
  12. package/logos/gn-118.webp +0 -0
  13. package/logos/gn-120.webp +0 -0
  14. package/logos/gn-121.webp +0 -0
  15. package/logos/gn-122.webp +0 -0
  16. package/logos/gn-127.webp +0 -0
  17. package/logos/gn-128.webp +0 -0
  18. package/logos/gn-13.webp +0 -0
  19. package/logos/gn-130.webp +0 -0
  20. package/logos/gn-14.webp +0 -0
  21. package/logos/gn-148.webp +0 -0
  22. package/logos/gn-149.webp +0 -0
  23. package/logos/gn-15.webp +0 -0
  24. package/logos/gn-150.webp +0 -0
  25. package/logos/gn-151.webp +0 -0
  26. package/logos/gn-152.webp +0 -0
  27. package/logos/gn-153.webp +0 -0
  28. package/logos/gn-156.webp +0 -0
  29. package/logos/gn-158.webp +0 -0
  30. package/logos/gn-159.webp +0 -0
  31. package/logos/gn-16.webp +0 -0
  32. package/logos/gn-162.webp +0 -0
  33. package/logos/gn-165.webp +0 -0
  34. package/logos/gn-167.webp +0 -0
  35. package/logos/gn-17.webp +0 -0
  36. package/logos/gn-173.webp +0 -0
  37. package/logos/gn-174.webp +0 -0
  38. package/logos/gn-175.webp +0 -0
  39. package/logos/gn-178.webp +0 -0
  40. package/logos/gn-179.webp +0 -0
  41. package/logos/gn-18.webp +0 -0
  42. package/logos/gn-180.webp +0 -0
  43. package/logos/gn-188.webp +0 -0
  44. package/logos/gn-19.webp +0 -0
  45. package/logos/gn-190.webp +0 -0
  46. package/logos/gn-192.webp +0 -0
  47. package/logos/gn-193.webp +0 -0
  48. package/logos/gn-197.webp +0 -0
  49. package/logos/gn-199.webp +0 -0
  50. package/logos/gn-20.webp +0 -0
  51. package/logos/gn-202.webp +0 -0
  52. package/logos/gn-203.webp +0 -0
  53. package/logos/gn-204.webp +0 -0
  54. package/logos/gn-205.webp +0 -0
  55. package/logos/gn-207.webp +0 -0
  56. package/logos/gn-208.webp +0 -0
  57. package/logos/gn-21.webp +0 -0
  58. package/logos/gn-210.webp +0 -0
  59. package/logos/gn-22.webp +0 -0
  60. package/logos/gn-239.webp +0 -0
  61. package/logos/gn-240.webp +0 -0
  62. package/logos/gn-242.webp +0 -0
  63. package/logos/gn-25.webp +0 -0
  64. package/logos/gn-253.webp +0 -0
  65. package/logos/gn-255.webp +0 -0
  66. package/logos/gn-256.webp +0 -0
  67. package/logos/gn-258.webp +0 -0
  68. package/logos/gn-259.webp +0 -0
  69. package/logos/gn-26.webp +0 -0
  70. package/logos/gn-260.webp +0 -0
  71. package/logos/gn-273.webp +0 -0
  72. package/logos/gn-279.webp +0 -0
  73. package/logos/gn-28.webp +0 -0
  74. package/logos/gn-280.webp +0 -0
  75. package/logos/gn-281.webp +0 -0
  76. package/logos/gn-282.webp +0 -0
  77. package/logos/gn-29.webp +0 -0
  78. package/logos/gn-30.webp +0 -0
  79. package/logos/gn-300.webp +0 -0
  80. package/logos/gn-302.webp +0 -0
  81. package/logos/gn-304.webp +0 -0
  82. package/logos/gn-306.webp +0 -0
  83. package/logos/gn-308.webp +0 -0
  84. package/logos/gn-309.webp +0 -0
  85. package/logos/gn-31.webp +0 -0
  86. package/logos/gn-311.webp +0 -0
  87. package/logos/gn-312.webp +0 -0
  88. package/logos/gn-313.webp +0 -0
  89. package/logos/gn-315.webp +0 -0
  90. package/logos/gn-316.webp +0 -0
  91. package/logos/gn-317.webp +0 -0
  92. package/logos/gn-318.webp +0 -0
  93. package/logos/gn-319.webp +0 -0
  94. package/logos/gn-32.webp +0 -0
  95. package/logos/gn-320.webp +0 -0
  96. package/logos/gn-321.webp +0 -0
  97. package/logos/gn-322.webp +0 -0
  98. package/logos/gn-323.webp +0 -0
  99. package/logos/gn-324.webp +0 -0
  100. package/logos/gn-325.webp +0 -0
  101. package/logos/gn-326.webp +0 -0
  102. package/logos/gn-327.webp +0 -0
  103. package/logos/gn-328.webp +0 -0
  104. package/logos/gn-329.webp +0 -0
  105. package/logos/gn-335.webp +0 -0
  106. package/logos/gn-336.webp +0 -0
  107. package/logos/gn-337.webp +0 -0
  108. package/logos/gn-344.webp +0 -0
  109. package/logos/gn-345.webp +0 -0
  110. package/logos/gn-346.webp +0 -0
  111. package/logos/gn-347.webp +0 -0
  112. package/logos/gn-349.webp +0 -0
  113. package/logos/gn-351.webp +0 -0
  114. package/logos/gn-352.webp +0 -0
  115. package/logos/gn-354.webp +0 -0
  116. package/logos/gn-358.webp +0 -0
  117. package/logos/gn-359.webp +0 -0
  118. package/logos/gn-361.webp +0 -0
  119. package/logos/gn-363.webp +0 -0
  120. package/logos/gn-364.webp +0 -0
  121. package/logos/gn-365.webp +0 -0
  122. package/logos/gn-366.webp +0 -0
  123. package/logos/gn-367.webp +0 -0
  124. package/logos/gn-368.webp +0 -0
  125. package/logos/gn-37.webp +0 -0
  126. package/logos/gn-370.webp +0 -0
  127. package/logos/gn-371.webp +0 -0
  128. package/logos/gn-372.webp +0 -0
  129. package/logos/gn-373.webp +0 -0
  130. package/logos/gn-374.webp +0 -0
  131. package/logos/gn-375.webp +0 -0
  132. package/logos/gn-377.webp +0 -0
  133. package/logos/gn-378.webp +0 -0
  134. package/logos/gn-379.webp +0 -0
  135. package/logos/gn-380.webp +0 -0
  136. package/logos/gn-382.webp +0 -0
  137. package/logos/gn-383.webp +0 -0
  138. package/logos/gn-384.webp +0 -0
  139. package/logos/gn-386.webp +0 -0
  140. package/logos/gn-389.webp +0 -0
  141. package/logos/gn-391.webp +0 -0
  142. package/logos/gn-392.webp +0 -0
  143. package/logos/gn-393.webp +0 -0
  144. package/logos/gn-394.webp +0 -0
  145. package/logos/gn-397.webp +0 -0
  146. package/logos/gn-398.webp +0 -0
  147. package/logos/gn-399.webp +0 -0
  148. package/logos/gn-400.webp +0 -0
  149. package/logos/gn-401.webp +0 -0
  150. package/logos/gn-403.webp +0 -0
  151. package/logos/gn-405.webp +0 -0
  152. package/logos/gn-409.webp +0 -0
  153. package/logos/gn-410.webp +0 -0
  154. package/logos/gn-411.webp +0 -0
  155. package/logos/gn-413.webp +0 -0
  156. package/logos/gn-414.webp +0 -0
  157. package/logos/gn-415.webp +0 -0
  158. package/logos/gn-417.webp +0 -0
  159. package/logos/gn-418.webp +0 -0
  160. package/logos/gn-42.webp +0 -0
  161. package/logos/gn-420.webp +0 -0
  162. package/logos/gn-428.webp +0 -0
  163. package/logos/gn-429.webp +0 -0
  164. package/logos/gn-43.webp +0 -0
  165. package/logos/gn-431.webp +0 -0
  166. package/logos/gn-432.webp +0 -0
  167. package/logos/gn-433.webp +0 -0
  168. package/logos/gn-434.webp +0 -0
  169. package/logos/gn-437.webp +0 -0
  170. package/logos/gn-440.webp +0 -0
  171. package/logos/gn-442.webp +0 -0
  172. package/logos/gn-443.webp +0 -0
  173. package/logos/gn-448.webp +0 -0
  174. package/logos/gn-449.webp +0 -0
  175. package/logos/gn-45.webp +0 -0
  176. package/logos/gn-451.webp +0 -0
  177. package/logos/gn-452.webp +0 -0
  178. package/logos/gn-453.webp +0 -0
  179. package/logos/gn-455.webp +0 -0
  180. package/logos/gn-456.webp +0 -0
  181. package/logos/gn-459.webp +0 -0
  182. package/logos/gn-46.webp +0 -0
  183. package/logos/gn-460.webp +0 -0
  184. package/logos/gn-461.webp +0 -0
  185. package/logos/gn-462.webp +0 -0
  186. package/logos/gn-463.webp +0 -0
  187. package/logos/gn-466.webp +0 -0
  188. package/logos/gn-469.webp +0 -0
  189. package/logos/gn-47.webp +0 -0
  190. package/logos/gn-471.webp +0 -0
  191. package/logos/gn-474.webp +0 -0
  192. package/logos/gn-475.webp +0 -0
  193. package/logos/gn-476.webp +0 -0
  194. package/logos/gn-477.webp +0 -0
  195. package/logos/gn-478.webp +0 -0
  196. package/logos/gn-479.webp +0 -0
  197. package/logos/gn-48.webp +0 -0
  198. package/logos/gn-480.webp +0 -0
  199. package/logos/gn-481.webp +0 -0
  200. package/logos/gn-482.webp +0 -0
  201. package/logos/gn-483.webp +0 -0
  202. package/logos/gn-484.webp +0 -0
  203. package/logos/gn-485.webp +0 -0
  204. package/logos/gn-486.webp +0 -0
  205. package/logos/gn-487.webp +0 -0
  206. package/logos/gn-488.webp +0 -0
  207. package/logos/gn-489.webp +0 -0
  208. package/logos/gn-492.webp +0 -0
  209. package/logos/gn-495.webp +0 -0
  210. package/logos/gn-496.webp +0 -0
  211. package/logos/gn-497.webp +0 -0
  212. package/logos/gn-498.webp +0 -0
  213. package/logos/gn-499.webp +0 -0
  214. package/logos/gn-500.webp +0 -0
  215. package/logos/gn-502.webp +0 -0
  216. package/logos/gn-503.webp +0 -0
  217. package/logos/gn-504.webp +0 -0
  218. package/logos/gn-509.webp +0 -0
  219. package/logos/gn-511.webp +0 -0
  220. package/logos/gn-512.webp +0 -0
  221. package/logos/gn-513.webp +0 -0
  222. package/logos/gn-514.webp +0 -0
  223. package/logos/gn-516.webp +0 -0
  224. package/logos/gn-518.webp +0 -0
  225. package/logos/gn-519.webp +0 -0
  226. package/logos/gn-520.webp +0 -0
  227. package/logos/gn-521.webp +0 -0
  228. package/logos/gn-522.webp +0 -0
  229. package/logos/gn-525.webp +0 -0
  230. package/logos/gn-526.webp +0 -0
  231. package/logos/gn-527.webp +0 -0
  232. package/logos/gn-529.webp +0 -0
  233. package/logos/gn-530.webp +0 -0
  234. package/logos/gn-531.webp +0 -0
  235. package/logos/gn-532.webp +0 -0
  236. package/logos/gn-534.webp +0 -0
  237. package/logos/gn-536.webp +0 -0
  238. package/logos/gn-538.webp +0 -0
  239. package/logos/gn-539.webp +0 -0
  240. package/logos/gn-54.webp +0 -0
  241. package/logos/gn-540.webp +0 -0
  242. package/logos/gn-541.webp +0 -0
  243. package/logos/gn-542.webp +0 -0
  244. package/logos/gn-543.webp +0 -0
  245. package/logos/gn-544.webp +0 -0
  246. package/logos/gn-546.webp +0 -0
  247. package/logos/gn-551.webp +0 -0
  248. package/logos/gn-552.webp +0 -0
  249. package/logos/gn-553.webp +0 -0
  250. package/logos/gn-554.webp +0 -0
  251. package/logos/gn-555.webp +0 -0
  252. package/logos/gn-556.webp +0 -0
  253. package/logos/gn-558.webp +0 -0
  254. package/logos/gn-559.webp +0 -0
  255. package/logos/gn-560.webp +0 -0
  256. package/logos/gn-561.webp +0 -0
  257. package/logos/gn-562.webp +0 -0
  258. package/logos/gn-563.webp +0 -0
  259. package/logos/gn-564.webp +0 -0
  260. package/logos/gn-565.webp +0 -0
  261. package/logos/gn-567.webp +0 -0
  262. package/logos/gn-568.webp +0 -0
  263. package/logos/gn-569.webp +0 -0
  264. package/logos/gn-570.webp +0 -0
  265. package/logos/gn-571.webp +0 -0
  266. package/logos/gn-572.webp +0 -0
  267. package/logos/gn-573.webp +0 -0
  268. package/logos/gn-574.webp +0 -0
  269. package/logos/gn-576.webp +0 -0
  270. package/logos/gn-577.webp +0 -0
  271. package/logos/gn-578.webp +0 -0
  272. package/logos/gn-580.webp +0 -0
  273. package/logos/gn-581.webp +0 -0
  274. package/logos/gn-582.webp +0 -0
  275. package/logos/gn-583.webp +0 -0
  276. package/logos/gn-584.webp +0 -0
  277. package/logos/gn-587.webp +0 -0
  278. package/logos/gn-59.webp +0 -0
  279. package/logos/gn-594.webp +0 -0
  280. package/logos/gn-595.webp +0 -0
  281. package/logos/gn-597.webp +0 -0
  282. package/logos/gn-598.webp +0 -0
  283. package/logos/gn-6.webp +0 -0
  284. package/logos/gn-60.webp +0 -0
  285. package/logos/gn-600.webp +0 -0
  286. package/logos/gn-601.webp +0 -0
  287. package/logos/gn-603.webp +0 -0
  288. package/logos/gn-604.webp +0 -0
  289. package/logos/gn-605.webp +0 -0
  290. package/logos/gn-608.webp +0 -0
  291. package/logos/gn-609.webp +0 -0
  292. package/logos/gn-61.webp +0 -0
  293. package/logos/gn-610.webp +0 -0
  294. package/logos/gn-613.webp +0 -0
  295. package/logos/gn-614.webp +0 -0
  296. package/logos/gn-615.webp +0 -0
  297. package/logos/gn-616.webp +0 -0
  298. package/logos/gn-617.webp +0 -0
  299. package/logos/gn-618.webp +0 -0
  300. package/logos/gn-619.webp +0 -0
  301. package/logos/gn-62.webp +0 -0
  302. package/logos/gn-620.webp +0 -0
  303. package/logos/gn-621.webp +0 -0
  304. package/logos/gn-622.webp +0 -0
  305. package/logos/gn-629.webp +0 -0
  306. package/logos/gn-630.webp +0 -0
  307. package/logos/gn-631.webp +0 -0
  308. package/logos/gn-632.webp +0 -0
  309. package/logos/gn-633.webp +0 -0
  310. package/logos/gn-634.webp +0 -0
  311. package/logos/gn-635.webp +0 -0
  312. package/logos/gn-636.webp +0 -0
  313. package/logos/gn-637.webp +0 -0
  314. package/logos/gn-638.webp +0 -0
  315. package/logos/gn-639.webp +0 -0
  316. package/logos/gn-640.webp +0 -0
  317. package/logos/gn-641.webp +0 -0
  318. package/logos/gn-642.webp +0 -0
  319. package/logos/gn-643.webp +0 -0
  320. package/logos/gn-644.webp +0 -0
  321. package/logos/gn-645.webp +0 -0
  322. package/logos/gn-646.webp +0 -0
  323. package/logos/gn-647.webp +0 -0
  324. package/logos/gn-648.webp +0 -0
  325. package/logos/gn-656.webp +0 -0
  326. package/logos/gn-658.webp +0 -0
  327. package/logos/gn-659.webp +0 -0
  328. package/logos/gn-661.webp +0 -0
  329. package/logos/gn-663.webp +0 -0
  330. package/logos/gn-664.webp +0 -0
  331. package/logos/gn-665.webp +0 -0
  332. package/logos/gn-666.webp +0 -0
  333. package/logos/gn-668.webp +0 -0
  334. package/logos/gn-670.webp +0 -0
  335. package/logos/gn-673.webp +0 -0
  336. package/logos/gn-674.webp +0 -0
  337. package/logos/gn-675.webp +0 -0
  338. package/logos/gn-676.webp +0 -0
  339. package/logos/gn-677.webp +0 -0
  340. package/logos/gn-678.webp +0 -0
  341. package/logos/gn-679.webp +0 -0
  342. package/logos/gn-689.webp +0 -0
  343. package/logos/gn-690.webp +0 -0
  344. package/logos/gn-691.webp +0 -0
  345. package/logos/gn-692.webp +0 -0
  346. package/logos/gn-695.webp +0 -0
  347. package/logos/gn-697.webp +0 -0
  348. package/logos/gn-699.webp +0 -0
  349. package/logos/gn-700.webp +0 -0
  350. package/logos/gn-701.webp +0 -0
  351. package/logos/gn-703.webp +0 -0
  352. package/logos/gn-704.webp +0 -0
  353. package/logos/gn-707.webp +0 -0
  354. package/logos/gn-709.webp +0 -0
  355. package/logos/gn-712.webp +0 -0
  356. package/logos/gn-714.webp +0 -0
  357. package/logos/gn-715.webp +0 -0
  358. package/logos/gn-719.webp +0 -0
  359. package/logos/gn-720.webp +0 -0
  360. package/logos/gn-721.webp +0 -0
  361. package/logos/gn-722.webp +0 -0
  362. package/logos/gn-725.webp +0 -0
  363. package/logos/gn-727.webp +0 -0
  364. package/logos/gn-728.webp +0 -0
  365. package/logos/gn-729.webp +0 -0
  366. package/logos/gn-730.webp +0 -0
  367. package/logos/gn-731.webp +0 -0
  368. package/logos/gn-733.webp +0 -0
  369. package/logos/gn-735.webp +0 -0
  370. package/logos/gn-736.webp +0 -0
  371. package/logos/gn-737.webp +0 -0
  372. package/logos/gn-738.webp +0 -0
  373. package/logos/gn-740.webp +0 -0
  374. package/logos/gn-743.webp +0 -0
  375. package/logos/gn-744.webp +0 -0
  376. package/logos/gn-746.webp +0 -0
  377. package/logos/gn-747.webp +0 -0
  378. package/logos/gn-748.webp +0 -0
  379. package/logos/gn-750.webp +0 -0
  380. package/logos/gn-751.webp +0 -0
  381. package/logos/gn-753.webp +0 -0
  382. package/logos/gn-755.webp +0 -0
  383. package/logos/gn-756.webp +0 -0
  384. package/logos/gn-758.webp +0 -0
  385. package/logos/gn-759.webp +0 -0
  386. package/logos/gn-760.webp +0 -0
  387. package/logos/gn-761.webp +0 -0
  388. package/logos/gn-762.webp +0 -0
  389. package/logos/gn-763.webp +0 -0
  390. package/logos/gn-764.webp +0 -0
  391. package/logos/gn-765.webp +0 -0
  392. package/logos/gn-766.webp +0 -0
  393. package/logos/gn-767.webp +0 -0
  394. package/logos/gn-768.webp +0 -0
  395. package/logos/gn-769.webp +0 -0
  396. package/logos/gn-770.webp +0 -0
  397. package/logos/gn-773.webp +0 -0
  398. package/logos/gn-774.webp +0 -0
  399. package/logos/gn-775.webp +0 -0
  400. package/logos/gn-777.webp +0 -0
  401. package/logos/gn-780.webp +0 -0
  402. package/logos/gn-781.webp +0 -0
  403. package/logos/gn-783.webp +0 -0
  404. package/logos/gn-784.webp +0 -0
  405. package/logos/gn-79.webp +0 -0
  406. package/logos/gn-790.webp +0 -0
  407. package/logos/gn-793.webp +0 -0
  408. package/logos/gn-795.webp +0 -0
  409. package/logos/gn-796.webp +0 -0
  410. package/logos/gn-797.webp +0 -0
  411. package/logos/gn-798.webp +0 -0
  412. package/logos/gn-799.webp +0 -0
  413. package/logos/gn-80.webp +0 -0
  414. package/logos/gn-800.webp +0 -0
  415. package/logos/gn-801.webp +0 -0
  416. package/logos/gn-802.webp +0 -0
  417. package/logos/gn-806.webp +0 -0
  418. package/logos/gn-807.webp +0 -0
  419. package/logos/gn-808.webp +0 -0
  420. package/logos/gn-813.webp +0 -0
  421. package/logos/gn-815.webp +0 -0
  422. package/logos/gn-816.webp +0 -0
  423. package/logos/gn-817.webp +0 -0
  424. package/logos/gn-818.webp +0 -0
  425. package/logos/gn-834.webp +0 -0
  426. package/logos/gn-836.webp +0 -0
  427. package/logos/gn-837.webp +0 -0
  428. package/logos/gn-838.webp +0 -0
  429. package/logos/gn-839.webp +0 -0
  430. package/logos/gn-84.webp +0 -0
  431. package/logos/gn-840.webp +0 -0
  432. package/logos/gn-843.webp +0 -0
  433. package/logos/gn-844.webp +0 -0
  434. package/logos/gn-845.webp +0 -0
  435. package/logos/gn-852.webp +0 -0
  436. package/logos/gn-853.webp +0 -0
  437. package/logos/gn-860.webp +0 -0
  438. package/logos/gn-862.webp +0 -0
  439. package/logos/gn-863.webp +0 -0
  440. package/logos/gn-864.webp +0 -0
  441. package/logos/gn-87.webp +0 -0
  442. package/logos/gn-91.webp +0 -0
  443. package/logos/gn-92.webp +0 -0
  444. package/logos/gn-95.webp +0 -0
  445. package/logos/trivia-connections.webp +0 -0
  446. package/logos/trivia-globle.webp +0 -0
  447. package/logos/trivia-grid-baseball.webp +0 -0
  448. package/logos/trivia-grid-football.webp +0 -0
  449. package/logos/trivia-krillion.webp +0 -0
  450. package/logos/trivia-wordle.webp +0 -0
  451. package/package.json +1 -1
  452. package/style.css +423 -76
package/app.js CHANGED
@@ -10,7 +10,6 @@
10
10
  const THEME_KEY = "rug-theme";
11
11
  const PER_ROW_KEY = "rug-per-row";
12
12
  const MAX_RECENT = 6;
13
- const MARQUEE_SPEED = 38; // pixels per second
14
13
 
15
14
  const TAG_EMOJI = {
16
15
  Minecraft: "⛏️", Racing: "🏎️", Sports: "⚽", Shooter: "🎯", Horror: "👻", Clicker: "👆",
@@ -26,7 +25,7 @@
26
25
  const els = {
27
26
  homeView: $("view-home"), gamesView: $("view-games"), homeInput: $("home-input"), homeSub: $("home-sub"),
28
27
  grid: $("grid"), search: $("search"), sort: $("sort"), chips: $("chips"), count: $("count"), empty: $("empty"),
29
- allTitle: $("all-title"), footerCount: $("footer-count"),
28
+ allTitle: $("all-title"),
30
29
  recentBlock: $("recent-block"), recentRow: $("recent-row"),
31
30
  popularBlock: $("popular-block"), marquee: $("marquee"), marqueeTrack: $("marquee-track"),
32
31
  player: $("player"), frame: $("game-frame"), playerTitle: $("player-title"),
@@ -91,7 +90,7 @@
91
90
  return `<button class="tile" type="button" data-id="${escapeHtml(game.id)}" title="${escapeHtml(game.desc || game.name)}">
92
91
  <span class="tile-art" style="background:${gradient(game)}">${escapeHtml(initials(game.name))}</span>
93
92
  ${url ? `<span class="tile-art"><img src="${url}" alt="" loading="${eager ? "eager" : "lazy"}" decoding="async" onerror="this.parentNode.remove()"></span>` : ""}
94
- ${popular ? `<span class="badge">Popular</span>` : ""}
93
+ ${popular ? `<span class="badge">Popular</span>` : ""}${liveBadge(game)}
95
94
  <span class="tile-label">${escapeHtml(game.name)}</span>
96
95
  </button>`;
97
96
  }
@@ -106,7 +105,7 @@
106
105
  const counts = tagCounts();
107
106
  const tags = ["All", ...Object.keys(counts).sort((a, b) => counts[b] - counts[a])];
108
107
  els.chips.innerHTML = tags.map((t) =>
109
- `<button class="tab" role="tab" type="button" data-tag="${escapeHtml(t)}" aria-selected="${t === activeTag}">${t === "All" ? "All games" : (TAG_EMOJI[t] || "") + " " + escapeHtml(t)}<small>${t === "All" ? games.length : counts[t]}</small></button>`
108
+ `<button class="tab" role="tab" type="button" data-tag="${escapeHtml(t)}" aria-selected="${t === activeTag}">${t === "All" ? "All" : escapeHtml(t)}</button>`
110
109
  ).join("");
111
110
  }
112
111
 
@@ -134,11 +133,12 @@
134
133
  // Strips are for browsing; hide them while searching or filtering
135
134
  const browsing = !raw && activeTag === "All";
136
135
  els.popularBlock.hidden = !browsing;
136
+ $("gotd").hidden = !browsing || !$("gotd").children.length;
137
137
  els.recentBlock.hidden = !browsing || !els.recentRow.children.length;
138
138
  }
139
139
 
140
140
  function renderRecent() {
141
- const recent = store.get(RECENT_KEY, []).map((id) => byId.get(id)).filter(Boolean);
141
+ const recent = store.get(RECENT_KEY, []).map((id) => byId.get(id)).filter((g) => g && !g.hidden);
142
142
  els.recentRow.innerHTML = recent.map((g) => tileHtml(g, { eager: true })).join("");
143
143
  els.recentBlock.hidden = recent.length === 0 || !!els.search.value.trim() || activeTag !== "All";
144
144
  }
@@ -161,27 +161,182 @@
161
161
  store.set(PER_ROW_KEY, n);
162
162
  }
163
163
 
164
- // ---------- Popular games: a smooth, endless sideways glide ----------
164
+ // ---------- Popular games: an endless sideways glide ----------
165
+ // Done in CSS (a transform the graphics chip moves on its own), so it costs nothing per frame here
166
+ // and stops by itself whenever the Games page is hidden. Pauses while pointed at.
165
167
  function startMarquee() {
166
- const list = POPULAR.map((id) => byId.get(id)).filter(Boolean);
168
+ const list = popularList(18);
167
169
  if (!list.length) { els.popularBlock.hidden = true; return; }
168
- const set = list.map((g) => tileHtml(g, { popular: true, eager: true })).join("");
169
- els.marqueeTrack.innerHTML = set + set; // two copies so the loop never shows a gap
170
- const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
171
- let offset = 0, last = 0;
172
- function step(t) {
173
- const dt = last ? Math.min(64, t - last) : 0;
174
- last = t;
175
- // Pause while pointed at or keyboard-focused (checked live, so it can never get stuck paused)
176
- const paused = els.marquee.matches(":hover") || els.marquee.contains(document.activeElement);
177
- const half = els.marqueeTrack.scrollWidth / 2; // width of one copy (gap included); 0 while hidden
178
- if (!paused && !reduce && half > 0 && els.player.hidden) {
179
- offset = (offset + (MARQUEE_SPEED * dt) / 1000) % half;
180
- els.marqueeTrack.style.transform = `translate3d(${-offset}px,0,0)`;
170
+ const set = list.map((g) => tileHtml(g, { popular: true })).join("");
171
+ els.marqueeTrack.innerHTML = set + set; // two copies, so sliding by exactly one copy loops with no gap
172
+ els.marqueeTrack.style.setProperty("--glide", `${list.length * 9}s`);
173
+ }
174
+
175
+ // ---------- Popular = what people actually play ----------
176
+ // Every game start adds 1 to stats/plays/<game> in Firebase (at most once per 15s per person, checked by the
177
+ // database). While someone has a game open they're listed under stats/playing/<game>/<their id>, removed
178
+ // when they close it or leave. Until enough plays are counted, the hand-picked POPULAR list fills the gaps.
179
+ const community = { plays: {}, playing: {}, user: null, playingRef: null, shown: "" };
180
+ const fbKey = (id) => String(id).replace(/[.#$[\]/%]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
181
+ const playsOf = (g) => community.plays[fbKey(g.id)] || 0;
182
+ const playingOf = (g) => community.playing[fbKey(g.id)] || 0;
183
+ function popularList(n) {
184
+ const counted = games.filter((g) => playsOf(g) > 0).sort((a, b) => playsOf(b) - playsOf(a));
185
+ const picked = POPULAR.map((id) => byId.get(id)).filter(Boolean);
186
+ return [...new Set([...counted, ...picked])].slice(0, n);
187
+ }
188
+ // "🔥 3 playing" on every tile of a game someone has open right now
189
+ function liveBadge(g) {
190
+ const n = playingOf(g);
191
+ return n > 0 ? `<span class="live-badge">🔥 ${n} playing</span>` : "";
192
+ }
193
+ function updateLiveBadges() {
194
+ document.querySelectorAll(".tile[data-id]").forEach((t) => {
195
+ const g = byId.get(t.dataset.id);
196
+ if (!g) return;
197
+ const html = liveBadge(g), old = t.querySelector(".live-badge");
198
+ if (old) old.remove();
199
+ if (html) t.insertAdjacentHTML("beforeend", html);
200
+ });
201
+ }
202
+ // Re-draw the Popular strip and home buttons only when the order actually changes (so the glide doesn't jump)
203
+ function refreshPopular() {
204
+ const ids = popularList(18).map((g) => g.id).join(",");
205
+ if (ids === community.shown) return;
206
+ community.shown = ids;
207
+ startMarquee();
208
+ renderHomeApps();
209
+ updateLiveBadges();
210
+ }
211
+ async function startCommunity() {
212
+ const app = await getFirebase();
213
+ if (!app) return;
214
+ const db = app.database();
215
+ let t = 0;
216
+ db.ref("stats/plays").on("value", (s) => { community.plays = s.val() || {}; clearTimeout(t); t = setTimeout(refreshPopular, 300); });
217
+ db.ref("stats/playing").on("value", (s) => {
218
+ const counts = {};
219
+ s.forEach((g) => { counts[g.key] = g.numChildren(); });
220
+ community.playing = counts;
221
+ updateLiveBadges();
222
+ });
223
+ }
224
+ async function signedInUser(app) {
225
+ const auth = app.auth();
226
+ return auth.currentUser || new Promise((ok) => { const off = auth.onAuthStateChanged((u) => { if (u) { off(); ok(u); } }); });
227
+ }
228
+ async function notePlayStart(game) {
229
+ const app = await getFirebase();
230
+ if (!app) return;
231
+ try {
232
+ const user = await signedInUser(app);
233
+ const db = app.database(), FV = window.firebase.database.ServerValue;
234
+ notePlayStop();
235
+ const ref = community.playingRef = db.ref(`stats/playing/${fbKey(game.id)}/${user.uid}`);
236
+ ref.onDisconnect().remove();
237
+ ref.set(true).catch(() => {});
238
+ // one combined write: the database refuses it if this person counted a play under 15s ago
239
+ await db.ref().update({ [`stats/plays/${fbKey(game.id)}`]: FV.increment(1), [`stats/playLast/${user.uid}`]: FV.TIMESTAMP });
240
+ } catch { /* too soon after the last one, or offline: not counted */ }
241
+ }
242
+ function notePlayStop() {
243
+ const ref = community.playingRef;
244
+ if (!ref) return;
245
+ community.playingRef = null;
246
+ ref.onDisconnect().cancel().catch(() => {});
247
+ ref.remove().catch(() => {});
248
+ }
249
+
250
+ // ---------- Game of the day: a different game every day, the same one for everybody ----------
251
+ function renderGameOfDay() {
252
+ const pool = games.filter((g) => logoUrl(g) && g.desc);
253
+ if (!pool.length) return;
254
+ const g = pool[(dayNumber() * 2654435761 >>> 0) % pool.length]; // spread out, so neighbors in A–Z don't follow each other
255
+ $("gotd").innerHTML = `<button class="gotd-card" type="button" data-id="${escapeHtml(g.id)}">
256
+ <span class="gotd-art"><img src="${logoUrl(g)}" alt="" decoding="async"></span>
257
+ <span class="gotd-text"><span class="gotd-label">🎯 Game of the day</span><span class="gotd-name">${escapeHtml(g.name)}</span>
258
+ <span class="gotd-desc">${escapeHtml(g.desc)}</span><span class="gotd-play">Play now ▶</span></span></button>`;
259
+ $("gotd").hidden = false;
260
+ }
261
+
262
+ // ---------- Home: shortcut tiles for popular games under the search bar ----------
263
+ function renderHomeApps() {
264
+ const list = popularList(12);
265
+ $("home-apps").innerHTML = list.map((g) => {
266
+ const url = logoUrl(g);
267
+ const art = url ? `<img src="${url}" alt="" decoding="async">` : `<span style="background:${gradient(g)}">${escapeHtml(initials(g.name).slice(0, 2))}</span>`;
268
+ return `<button class="home-app" type="button" data-id="${escapeHtml(g.id)}" title="${escapeHtml(g.name)}"><span class="home-app-icon">${art}</span><span class="home-app-name">${escapeHtml(g.name)}</span></button>`;
269
+ }).join("");
270
+ }
271
+
272
+ // ---------- Halloween: decorations on the home page, all of October ----------
273
+ // Drawn once (SVG, emoji and gradients); only the bats and the ghost move, using cheap transforms.
274
+ function cobweb(flip) {
275
+ const R = 260, spokes = 8, rings = 9;
276
+ const pt = (a, r) => [Math.cos(a) * r, Math.sin(a) * r];
277
+ let d = "";
278
+ for (let i = 0; i < spokes; i++) { const [x, y] = pt((i / (spokes - 1)) * Math.PI / 2, R); d += `M0 0L${x.toFixed(1)} ${y.toFixed(1)}`; }
279
+ for (let k = 1; k <= rings; k++) {
280
+ const r = (k / rings) * R * 0.95;
281
+ for (let i = 0; i < spokes - 1; i++) {
282
+ const a1 = (i / (spokes - 1)) * Math.PI / 2, a2 = ((i + 1) / (spokes - 1)) * Math.PI / 2;
283
+ const [x1, y1] = pt(a1, r), [x2, y2] = pt(a2, r), [cx, cy] = pt((a1 + a2) / 2, r * 0.86); // sags toward the corner
284
+ d += `M${x1.toFixed(1)} ${y1.toFixed(1)}Q${cx.toFixed(1)} ${cy.toFixed(1)} ${x2.toFixed(1)} ${y2.toFixed(1)}`;
181
285
  }
182
- requestAnimationFrame(step);
183
286
  }
184
- requestAnimationFrame(step);
287
+ return `<svg class="web ${flip ? "right" : "left"}" viewBox="0 0 270 270"><path d="${d}"/></svg>`;
288
+ }
289
+ // ---------- Themes (Settings → Theme): Auto picks Halloween in October, Christmas in December, else Black ----------
290
+ const THEMES = ["auto", "black", "white", "halloween", "christmas"];
291
+ function resolveTheme(t) {
292
+ if (THEMES.includes(t) && t !== "auto") return t;
293
+ const m = new Date().getMonth();
294
+ return m === 9 ? "halloween" : m === 11 ? "christmas" : "black";
295
+ }
296
+ function applySiteTheme(choice) {
297
+ const t = resolveTheme(choice);
298
+ const root = document.documentElement;
299
+ root.dataset.theme = t === "white" ? "light" : "dark";
300
+ root.classList.toggle("halloween", t === "halloween");
301
+ root.classList.toggle("christmas", t === "christmas");
302
+ $("theme-color").content = { white: "#f6f6f8", halloween: "#110820", christmas: "#0b1424" }[t] || "#000000";
303
+ if (t === "halloween" && !document.querySelector(".spooky")) buildHalloween(); // scenery is only drawn once it's needed
304
+ if (t === "christmas" && !document.querySelector(".xmas")) buildChristmas();
305
+ }
306
+ function buildChristmas() {
307
+ const colors = ["#ef4444", "#facc15", "#22c55e", "#3b82f6"];
308
+ const bulbs = Array.from({ length: 26 }, (_, i) => `<i style="left:${(i + .5) * (100 / 26)}%;top:${10 + Math.sin(i * 1.3) * 5}px;--c:${colors[i % 4]};animation-delay:${(i % 5) * -.45}s"></i>`).join("");
309
+ const tree = (x, h) => `<path d="M${x} ${200 - h}l${h * .32} ${h * .45}h-${h * .12}l${h * .22} ${h * .3}h-${h * .1}l${h * .25} ${h * .25}h-${h * 1.34}l${h * .25}-${h * .25}h-${h * .1}l${h * .22}-${h * .3}h-${h * .12}Z"/>`;
310
+ $("view-home").insertAdjacentHTML("afterbegin", `<div class="xmas" aria-hidden="true">
311
+ <div class="lights"><svg viewBox="0 0 100 10" preserveAspectRatio="none"><path d="M0 2Q8 9 16 3T32 3 48 3 64 3 80 3 100 3"/></svg>${bulbs}</div>
312
+ <div class="snow s1"></div><div class="snow s2"></div>
313
+ <svg class="hills" viewBox="0 0 1600 240" preserveAspectRatio="xMidYMax slice">
314
+ <g class="pines">${tree(120, 120)}${tree(230, 80)}${tree(1380, 140)}${tree(1500, 90)}</g>
315
+ <path class="snowbank" d="M0 200C200 170 420 190 640 180S1100 165 1300 182 1520 186 1600 176V240H0Z"/>
316
+ </svg>
317
+ <span class="xmas-tree">🎄</span><span class="gift g1">🎁</span><span class="gift g2">🎁</span><span class="snowman">☃️</span>
318
+ </div>`);
319
+ }
320
+ function buildHalloween() {
321
+ const bat = `<svg viewBox="0 0 64 28"><path d="M32 8c2-4 3-6 3-8 1 3 2 5 3 6 5-4 14-6 26-2-6 2-9 6-10 12-4-3-8-3-11 0-2-3-5-4-8-3l-3 4-3-4c-3-1-6 0-8 3-3-3-7-3-11 0C9 10 6 6 0 4c12-4 21-2 26 2 1-1 2-3 3-6 0 2 1 4 3 8Z"/></svg>`;
322
+ $("view-home").insertAdjacentHTML("afterbegin", `<div class="spooky" aria-hidden="true">
323
+ <div class="stars"></div>
324
+ ${cobweb(false)}${cobweb(true)}
325
+ <div class="spider"><span>🕷️</span></div>
326
+ <div class="moon"></div>
327
+ <div class="ghost">👻</div>
328
+ <div class="bat b1">${bat}</div><div class="bat b2">${bat}</div><div class="bat b3">${bat}</div>
329
+ <svg class="graveyard" viewBox="0 0 1600 240" preserveAspectRatio="xMidYMax slice">
330
+ <path class="ground" d="M0 190C220 160 420 175 640 168S1100 150 1300 165 1520 170 1600 160V240H0Z"/>
331
+ <g class="dark">
332
+ <path d="M180 200V120M180 140l-50-40M180 125l45-45M150 116l-26 4M205 96l24-6M180 160l40-12" stroke-width="9" stroke-linecap="round"/>
333
+ <path d="M600 190v-26a16 16 0 0 1 32 0v26ZM700 186v-34a20 20 0 0 1 40 0v34ZM790 190v-22a14 14 0 0 1 28 0v22ZM880 192v-36h8v-14h12v14h8v36Z"/>
334
+ <path d="M1300 200V118l40-40 40 40v12h24V100l30-30 30 30v-8h14v22l30 30v56Z"/>
335
+ </g>
336
+ <g class="windows"><rect x="1332" y="120" width="14" height="22" rx="7"/><rect x="1420" y="128" width="12" height="16"/><rect x="1446" y="128" width="12" height="16"/><path d="M1384 200v-26a12 12 0 0 1 24 0v26Z"/><rect x="1500" y="160" width="12" height="12"/></g>
337
+ </svg>
338
+ <span class="pumpkin p1">🎃</span><span class="pumpkin p2">🎃</span><span class="pumpkin p3">🎃</span>
339
+ </div>`);
185
340
  }
186
341
 
187
342
  // ---------- Game loading ----------
@@ -386,6 +541,7 @@
386
541
 
387
542
  function stopGame() {
388
543
  stats.stopPlay();
544
+ notePlayStop();
389
545
  if (!currentLoad) return;
390
546
  currentLoad.controller.abort();
391
547
  currentLoad = null;
@@ -406,11 +562,11 @@
406
562
  }
407
563
 
408
564
  // ---------- Routing: "" home, #games, #recent, #play/<id> ----------
409
- const VIEW_ORDER = ["home", "games", "chat", "stats", "live", "settings", "changelog"];
565
+ const VIEW_ORDER = ["home", "games", "trivia", "ai", "chat", "stats", "settings", "changelog"];
410
566
  let lastView = null;
411
567
  function viewFor(hash) {
412
568
  return hash === "#games" || hash === "#recent" ? "games" : hash === "#settings" ? "settings" : hash === "#chat" ? "chat"
413
- : hash === "#stats" ? "stats" : hash === "#changelog" ? "changelog" : hash === "#live" ? "live" : "home";
569
+ : hash === "#stats" ? "stats" : hash === "#changelog" ? "changelog" : hash === "#ai" ? "ai" : hash === "#trivia" ? "trivia" : "home";
414
570
  }
415
571
  // Switching pages: the old page slides out while the new one slides in (down the side bar = upward,
416
572
  // up the side bar = downward). Uses the browser's view transitions; older browsers just switch.
@@ -427,7 +583,6 @@
427
583
  const m = location.hash.match(/^#play\/(.+)$/);
428
584
  const game = m && byId.get(decodeURIComponent(m[1]));
429
585
  if (game) {
430
- if (live.viewer) stopWatching(); // a game covers the Live page: stop the stream's sound too
431
586
  els.player.hidden = false;
432
587
  document.body.classList.add("playing");
433
588
  addRecent(game.id);
@@ -435,6 +590,7 @@
435
590
  if (dockOpen()) openChat();
436
591
  if (currentLoad?.id !== game.id) {
437
592
  loadGame(game);
593
+ notePlayStart(game);
438
594
  track(`Play: ${game.name}`, { name: "play_game", params: { game_name: game.name, game_category: game.tag } });
439
595
  }
440
596
  return;
@@ -451,9 +607,17 @@
451
607
  lastView = view;
452
608
  $("view-stats").hidden = view !== "stats";
453
609
  $("view-changelog").hidden = view !== "changelog";
454
- $("view-live").hidden = view !== "live";
455
- if (view === "live") { openChat(); renderLive(); }
456
- else if (live.viewer) stopWatching(); // leaving the Live page stops the stream (and its sound); Watch live rejoins
610
+ $("view-ai").hidden = view !== "ai";
611
+ $("view-trivia").hidden = view !== "trivia";
612
+ if (view !== "trivia") { // leaving: stop the clock, close any puzzle site, and a half-done quiz starts over next time
613
+ stopTriviaTimer();
614
+ closeTriviaSite();
615
+ if (!$("trivia-play").hidden) triviaScreen("setup");
616
+ trivia.daily = false; // a daily challenge left halfway is used up (one try a day)
617
+ $("trivia-daily").hidden = false;
618
+ renderDaily();
619
+ }
620
+ if (view === "ai") { renderAi(); setTimeout(() => $("ai-input").focus(), 50); }
457
621
  if (view === "changelog") renderChangelog();
458
622
  placeChatBox();
459
623
  if (view === "settings") { renderSettings(); renderAdmin(); }
@@ -510,22 +674,24 @@
510
674
  setInterval(clockTick, 1000);
511
675
  }
512
676
 
513
- function applyTheme(t) {
514
- document.documentElement.dataset.theme = t;
515
- $("theme-color").content = t === "dark" ? "#000000" : "#f6f6f8"; // phone browser bar matches the page
516
- $("theme-btn").title = t === "dark" ? "Switch to light mode" : "Switch to dark mode";
517
- try { localStorage.setItem(THEME_KEY, t); } catch {}
518
- }
677
+ // The theme lives in settings.theme now; the old light/dark switch's saved value is cleared
519
678
  function initTheme() {
520
- applyTheme(document.documentElement.dataset.theme === "light" ? "light" : "dark");
521
- $("theme-btn").addEventListener("click", () =>
522
- applyTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark"));
679
+ try { localStorage.removeItem(THEME_KEY); } catch {}
680
+ applySiteTheme(settings.theme);
523
681
  }
524
682
 
525
683
  // ---------- What's new (changelog) ----------
526
684
  // Newest first. Add an entry here with every publish; its version should match package.json.
527
685
  // Each has: new (features), games (added/removed/fixed games), fixes (bugs). Leave a list out if empty.
528
686
  const CHANGELOG = [
687
+ { version: "1.0.38", date: "2026-10-29",
688
+ new: ["Daily trivia challenge: the same 10 questions for everyone, one try a day, with a leaderboard", "A quick tour of the site for first-time visitors (replay it from Settings)"],
689
+ fixes: ["Trimmed the trivia puzzle list to the best ones"] },
690
+ { version: "1.0.37", date: "2026-10-29",
691
+ new: ["🤖 AI chat: ask anything, and it can look at pictures too", "A cleaner Games page: search on top, categories in one row", "🎃 Halloween look on the home page, plus quick buttons for popular games", "Hide the side bar with the arrow at its bottom", "🎨 Themes in Settings: Auto, Black, White, Halloween and Christmas",
692
+ "🔥 Popular games are now the ones people actually play, and games show how many are playing right now", "🎯 Game of the day on the Games page",
693
+ "📊 Polls in chat", "Trivia: a quick quiz with NFL, NBA and MLB (all 92 teams, players, easy to hard) and 11 more topics, plus daily puzzle games", "🔊 The soundboard now has its own button in the side bar", "Chat titles have been removed", "Live streaming has been removed"],
694
+ fixes: ["The site loads much faster: game pictures are about 6x smaller", "Smoother on Chromebooks: the background no longer animates", "Quicker page switching and loading screen", "Chat names are no longer censored (only slurs are hidden)", "Words with a K in them were wrongly being hidden in chat","The admin code works even when the chat is locked"] },
529
695
  { version: "1.0.36", date: "2026-10-28",
530
696
  new: ["🎁 Send gifts during live streams: they pop up on the stream for everyone (one gift a minute)"],
531
697
  fixes: ["Nickname and title boxes aren't cut off in the live chat anymore"] },
@@ -773,7 +939,6 @@
773
939
  document.title = tabTitle(els.player.hidden ? "" : els.playerTitle.textContent);
774
940
  const keys = CFG.panicKeys.map((k) => (k === " " ? "Space" : k)).join(" or ");
775
941
  $("panic-btn").title = `Panic (${keys})`;
776
- document.querySelector(".corner-links span").innerHTML = `${CFG.panicKeys.map((k) => `<kbd>${escapeHtml(k === " " ? "Space" : k)}</kbd>`).join(" or ")} panic`;
777
942
  renderBookmark();
778
943
  }
779
944
 
@@ -811,11 +976,10 @@
811
976
  $("set-panic-custom-row").hidden = preset;
812
977
  $("set-panic-custom").value = preset ? "" : CFG.panicUrl;
813
978
  $("set-panic-key").textContent = CFG.panicKeys.map((k) => (k === " " ? "Space" : k)).join(" or ");
814
- $("set-theme").value = document.documentElement.dataset.theme;
979
+ $("set-theme").value = THEMES.includes(settings.theme) ? settings.theme : "auto";
815
980
  $("set-clock").value = clockIs24 ? "24" : "12";
816
981
  $("set-per-row").value = String(store.get(PER_ROW_KEY, 6));
817
982
  $("set-typing").checked = settings.typing !== false;
818
- $("set-boot").checked = settings.boot !== false;
819
983
  }
820
984
 
821
985
  function bindSettings() {
@@ -853,11 +1017,10 @@
853
1017
  if (e.key !== "Escape" && e.key.length === 1) { settings.panicKey = e.key; saveSettings(); }
854
1018
  renderSettings();
855
1019
  }, true);
856
- $("set-theme").addEventListener("change", (e) => applyTheme(e.target.value));
1020
+ $("set-theme").addEventListener("change", (e) => { settings.theme = e.target.value; saveSettings(); applySiteTheme(settings.theme); });
857
1021
  $("set-clock").addEventListener("change", (e) => setClock24(e.target.value === "24"));
858
1022
  $("set-per-row").addEventListener("change", (e) => setPerRow(Number(e.target.value)));
859
1023
  $("set-typing").addEventListener("change", (e) => { settings.typing = e.target.checked; saveSettings(); startTypingPlaceholder(); });
860
- $("set-boot").addEventListener("change", (e) => { settings.boot = e.target.checked; saveSettings(); });
861
1024
  $("set-reset-stats").addEventListener("click", () => {
862
1025
  if (!confirm("Reset your stats and achievements on this device?")) return;
863
1026
  stats.data = null;
@@ -872,8 +1035,8 @@
872
1035
  });
873
1036
  $("set-reset").addEventListener("click", () => {
874
1037
  settings = { disguise: "classroom", typing: true, boot: true };
1038
+ applySiteTheme("auto");
875
1039
  saveSettings();
876
- applyTheme("dark");
877
1040
  setClock24(false);
878
1041
  setPerRow(6);
879
1042
  startTypingPlaceholder();
@@ -1081,12 +1244,24 @@
1081
1244
  function extraWords() {
1082
1245
  return String(chat.settings.words || "").split(/[\n,]+/).map((w) => plain(w).trim()).filter((w) => w.length >= 2);
1083
1246
  }
1084
- function isBadWord(word) {
1247
+ // Names and titles only lose slurs and hate symbols; ordinary swears and rude words in a name are left alone
1248
+ const SLUR_ANYWHERE = ["nigg", "faggot", "fagot", "retard", "chink", "chingchong", "kike", "wetback", "tranny", "raghead",
1249
+ "towelhead", "beaner", "jigaboo", "porch monkey", "heil", "white power", "whitepower", "kkk", "1488"];
1250
+ const SLUR_WHOLE_WORD = ["fag", "fags", "nig", "spic", "gook", "coon"];
1251
+ function isBadWord(word, slursOnly = false) {
1085
1252
  const p = plain(word).replace(/ /g, ""), w = tight(word);
1086
1253
  if (!w || SAFE_WORDS.includes(p)) return false;
1254
+ const whole = slursOnly ? SLUR_WHOLE_WORD : BAD_WHOLE_WORD;
1255
+ const anywhere = slursOnly ? SLUR_ANYWHERE : [...BAD_ANYWHERE, ...extraWords()];
1087
1256
  // whole-word list: check before and after squashing, since squashing turns "ass" into "as"
1088
- return BAD_WHOLE_WORD.includes(p) || BAD_WHOLE_WORD.includes(w) ||
1089
- [...BAD_ANYWHERE, ...extraWords()].some((b) => w.includes(tight(b)));
1257
+ if (whole.includes(p) || whole.includes(w)) return true;
1258
+ // Entries with numbers ("1488") are matched as typed; ones that squash to almost nothing ("kkk" -> "k")
1259
+ // are matched unsquashed, or every word with a k in it would be hidden
1260
+ return anywhere.some((b) => (/\d/.test(b) ? String(word).toLowerCase().includes(b)
1261
+ : tight(b).length >= 3 ? w.includes(tight(b)) : p.includes(plain(b).replace(/ /g, ""))));
1262
+ }
1263
+ function maskSlurs(text) {
1264
+ return String(text).split(/(\s+)/).map((w) => (/\S/.test(w) && isBadWord(w, true) ? maskWord(w) : w)).join("");
1090
1265
  }
1091
1266
  // Nothing is ever blocked: swear words just get their middle letters hidden ("f**k").
1092
1267
  // The owner's extra word list (Settings → Tools) is hidden the same way.
@@ -1110,7 +1285,7 @@
1110
1285
  const name = String(raw).replace(/\s+/g, " ").trim();
1111
1286
  if (!name) return { error: "Pick a nickname." };
1112
1287
  if ([...name].length > 16) return { error: "Nicknames can be up to 16 characters." };
1113
- return { name: maskText(name) };
1288
+ return { name: maskSlurs(name) };
1114
1289
  }
1115
1290
 
1116
1291
  const chat = {
@@ -1118,6 +1293,7 @@
1118
1293
  settings: {}, // owner's live settings: slowMode (s), locked, words
1119
1294
  mutedUntil: 0, banned: false,
1120
1295
  flags: {}, // message key -> number of people who reported it
1296
+ votes: {}, // poll message key -> { voter id: option number }
1121
1297
  lastText: "", lastTextAt: 0,
1122
1298
  room: "main", // "main" (the Chat page / beside games) or "live" (beside the live stream)
1123
1299
  };
@@ -1153,7 +1329,6 @@
1153
1329
  chat.started = true;
1154
1330
  $("chat-form").hidden = false;
1155
1331
  $("chat-name").value = store.get("rug-chat-name", "");
1156
- $("chat-title").value = store.get("rug-chat-title", "");
1157
1332
  chatNote("Connecting…");
1158
1333
  try {
1159
1334
  await ensureUser(app);
@@ -1162,7 +1337,6 @@
1162
1337
  return;
1163
1338
  }
1164
1339
  if (chat.admin) setAdminName();
1165
- if (!$("view-live").hidden) renderLive(); // now we know whether this is the owner (Go live panel)
1166
1340
  chatNote("");
1167
1341
  const log = $("chat-log");
1168
1342
  log.innerHTML = `<p class="chat-empty" id="chat-empty">No messages yet. Say hi!</p>`;
@@ -1190,7 +1364,7 @@
1190
1364
  }
1191
1365
  async function sweepOldMessages(db) {
1192
1366
  const dayAgo = Date.now() - 86400000;
1193
- for (const path of ["chat/messages", "live/chat/messages"]) {
1367
+ for (const path of ["chat/messages"]) {
1194
1368
  try {
1195
1369
  const old = await db.ref(path).orderByChild("ts").endAt(dayAgo).limitToFirst(200).once("value");
1196
1370
  const changes = {};
@@ -1252,18 +1426,20 @@
1252
1426
  } else if (typeof m.sticker === "string" && STICKERS.includes(m.sticker)) {
1253
1427
  body = `<img class="chat-sticker" src="${STICKER_URL(m.sticker)}" alt="sticker" width="96" height="96" loading="lazy">`; } else if (typeof m.img === "string" && /^data:image\/(webp|jpeg);base64,[A-Za-z0-9+/=]+$/.test(m.img)) {
1254
1428
  body = `<button class="chat-photo-btn" type="button" data-act="view" title="Open photo"><img class="chat-photo" src="${m.img}" alt="Photo from ${escapeHtml(m.name)}" loading="lazy"></button>`;
1429
+ } else if (m.poll && typeof m.poll.q === "string" && pollOptions(m.poll).length >= 2) {
1430
+ body = pollHtml(key, m.poll);
1255
1431
  } else return null;
1256
1432
  const t = new Date(m.ts || Date.now());
1257
1433
  const div = document.createElement("div");
1258
1434
  const mine = m.uid === chat.uid;
1259
- div.className = "chat-msg" + (mine ? " me" : "") + (m.img ? " photo" : "") + (m.sticker ? " sticker" : "");
1435
+ div.className = "chat-msg" + (mine ? " me" : "") + (m.img ? " photo" : "") + (m.sticker ? " sticker" : "") + (m.poll ? " has-poll" : "");
1436
+ if (m.poll) div.pollData = m.poll; // kept so the bars can be redrawn as votes come in
1260
1437
  div.dataset.key = key;
1261
1438
  div.dataset.uid = m.uid || "";
1262
1439
  div.dataset.name = m.name;
1263
1440
  if (typeof m.text === "string") div.dataset.text = m.text;
1264
1441
  if (!mine && typeof m.text === "string" && mentionsMe(m.text)) div.classList.add("mention");
1265
- const title = typeof m.title === "string" && m.title.trim() ? `<span class="chat-title-pill">${escapeHtml(maskText(m.title))}</span>` : "";
1266
- div.innerHTML = `${m.admin ? `<span class="badge-admin">⭐ ADMIN</span>` : ""}${title}<span class="who" title="Mention">${escapeHtml(maskText(m.name))}</span>` +
1442
+ div.innerHTML = `${m.admin ? `<span class="badge-admin">⭐ ADMIN</span>` : ""}<span class="who" title="Mention">${escapeHtml(maskSlurs(m.name))}</span>` +
1267
1443
  `${body}<span class="when">${t.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}</span>` +
1268
1444
  `<span class="msg-acts">` +
1269
1445
  `<button class="mod act-delete" type="button" data-act="delete" title="Delete message">🗑</button>` +
@@ -1274,6 +1450,42 @@
1274
1450
  applyFlags(div);
1275
1451
  return div;
1276
1452
  }
1453
+ // ---------- Polls: anyone can post one; everyone gets one vote (click again to take it back) ----------
1454
+ // Votes live at chat/votes/<message>/<voter> = option number
1455
+ function pollOptions(poll) {
1456
+ return Object.values(poll.o || {}).filter((o) => typeof o === "string" && o.trim()).slice(0, 4);
1457
+ }
1458
+ function pollHtml(key, poll) {
1459
+ const opts = pollOptions(poll), byVoter = chat.votes[key] || {};
1460
+ const votes = Object.values(byVoter), total = votes.length, my = byVoter[chat.uid];
1461
+ return `<div class="poll"><p class="poll-q">📊 ${escapeHtml(maskText(poll.q))}</p>` + opts.map((o, i) => {
1462
+ const n = votes.filter((v) => v === i).length, pct = total ? Math.round((n * 100) / total) : 0;
1463
+ return `<button class="poll-opt${my === i ? " on" : ""}" type="button" data-act="vote" data-i="${i}">` +
1464
+ `<span class="poll-bar" style="width:${pct}%"></span><span class="poll-label">${escapeHtml(maskText(o))}</span><span class="poll-n">${pct}%</span></button>`;
1465
+ }).join("") + `<p class="poll-total">${total} vote${total === 1 ? "" : "s"}${my === undefined ? " · tap to vote" : ""}</p></div>`;
1466
+ }
1467
+ function updatePolls() {
1468
+ $("chat-log").querySelectorAll(".chat-msg.has-poll").forEach((row) => {
1469
+ const old = row.querySelector(".poll");
1470
+ if (old && row.pollData) old.outerHTML = pollHtml(row.dataset.key, row.pollData);
1471
+ });
1472
+ }
1473
+ function bindPolls() {
1474
+ const maker = $("poll-maker"), btn = $("poll-btn");
1475
+ const show = (on) => { maker.hidden = !on; btn.setAttribute("aria-expanded", on); if (on) $("poll-q").focus(); };
1476
+ btn.addEventListener("click", () => show(maker.hidden));
1477
+ $("poll-cancel").addEventListener("click", () => show(false));
1478
+ maker.addEventListener("submit", async (e) => {
1479
+ e.preventDefault();
1480
+ const q = $("poll-q").value.replace(/\s+/g, " ").trim();
1481
+ const opts = [...maker.querySelectorAll(".poll-o")].map((i) => i.value.replace(/\s+/g, " ").trim()).filter(Boolean);
1482
+ if (!q || opts.length < 2) { chatNote("A poll needs a question and at least 2 options.", true); return; }
1483
+ if (await postMessage({ poll: { q: maskText(q).slice(0, 100), o: opts.map((o) => maskText(o).slice(0, 40)) } })) {
1484
+ maker.reset();
1485
+ show(false);
1486
+ }
1487
+ });
1488
+ }
1277
1489
  function applyFlags(div) {
1278
1490
  const n = chat.flags[div.dataset.key] || 0;
1279
1491
  div.classList.toggle("flagged", n >= HIDE_AFTER_REPORTS);
@@ -1283,6 +1495,7 @@
1283
1495
 
1284
1496
  // Live chat state: owner settings (slow mode, lock, extra words), my mute/ban, and report counts
1285
1497
  function watchChatState(db) {
1498
+ db.ref("chat/votes").on("value", (s) => { chat.votes = s.val() || {}; updatePolls(); });
1286
1499
  db.ref("chat/settings").on("value", (s) => {
1287
1500
  chat.settings = s.val() || {};
1288
1501
  updateChatStatus();
@@ -1318,7 +1531,7 @@
1318
1531
  function slowSeconds() { return chat.admin ? 0 : Number(chat.settings.slowMode) || 0; } // no cooldown unless the owner turns on slow mode
1319
1532
  function updateChatStatus() {
1320
1533
  const why = blockedReason();
1321
- ["chat-text", "chat-send", "emoji-btn", "photo-btn", "cam-btn"].forEach((id) => { if ($(id)) $(id).disabled = !!why; });
1534
+ ["chat-text", "emoji-btn", "photo-btn", "cam-btn"] /* Send stays clickable: the admin code works even when chat is locked */.forEach((id) => { if ($(id)) $(id).disabled = !!why; });
1322
1535
  const slow = Number(chat.settings.slowMode) || 0;
1323
1536
  $("chat-status").textContent = why || (chat.settings.locked ? "🔒 Chat is locked (only you can post)" : slow ? `🐢 Slow mode: one message every ${slow}s` : "");
1324
1537
  $("chat-status").classList.toggle("err", !!why);
@@ -1395,6 +1608,13 @@
1395
1608
  const row = btn.closest(".chat-msg");
1396
1609
  const act = btn.dataset.act, uid = row.dataset.uid, name = row.dataset.name, key = row.dataset.key;
1397
1610
  if (act === "view") { openPhoto(row.querySelector("img").src); return; }
1611
+ if (act === "vote") {
1612
+ if (!chat.uid) return;
1613
+ const i = Number(btn.dataset.i), mineNow = (chat.votes[key] || {})[chat.uid];
1614
+ try { await (await getFirebase()).database().ref(`chat/votes/${key}/${chat.uid}`).set(mineNow === i ? null : i); }
1615
+ catch { chatNote(blockedReason() || "Your vote didn't count. Try again.", true); }
1616
+ return;
1617
+ }
1398
1618
  const mine = uid && uid === chat.uid;
1399
1619
  const db = (await getFirebase()).database();
1400
1620
  try {
@@ -1704,8 +1924,8 @@
1704
1924
  await renderAdmin();
1705
1925
  });
1706
1926
  $("admin-clear").addEventListener("click", async () => {
1707
- if (!chat.admin || !confirm("Delete every chat message for everyone (regular chat and live chat)?")) return;
1708
- try { await (await getFirebase()).database().ref().update({ "chat/messages": null, "live/chat/messages": null }); } // both rooms
1927
+ if (!chat.admin || !confirm("Delete every chat message for everyone?")) return;
1928
+ try { await (await getFirebase()).database().ref("chat/messages").remove(); }
1709
1929
  catch { alert("Couldn't clear the chat."); }
1710
1930
  });
1711
1931
  }
@@ -1748,15 +1968,13 @@
1748
1968
  const n = chatSender();
1749
1969
  if (!n) return false;
1750
1970
  if (!chat.admin) store.set("rug-chat-name", n.name); // never save the admin code as a remembered name
1751
- const title = maskText($("chat-title").value.replace(/\s+/g, " ").trim()).slice(0, 20);
1752
- store.set("rug-chat-title", title);
1753
1971
  const db = app.database();
1754
1972
  const key = db.ref(roomPath("messages")).push().key;
1755
1973
  const TS = window.firebase.database.ServerValue.TIMESTAMP;
1756
1974
  chat.lastSent = Date.now();
1757
1975
  try {
1758
1976
  await db.ref().update({
1759
- [roomPath(`messages/${key}`)]: { name: n.name, ts: TS, uid: chat.uid, ...fields, ...(title ? { title } : {}), ...(chat.admin ? { admin: true } : {}) },
1977
+ [roomPath(`messages/${key}`)]: { name: n.name, ts: TS, uid: chat.uid, ...fields, ...(chat.admin ? { admin: true } : {}) },
1760
1978
  [`chat/last/${chat.uid}`]: TS,
1761
1979
  });
1762
1980
  stats.bump("chatSent");
@@ -1864,238 +2082,1018 @@
1864
2082
  $("quotes-approved").addEventListener("click", act);
1865
2083
  }
1866
2084
 
1867
- // ---------- Live stream ----------
1868
- // The owner streams their screen (with its sound), camera and mic straight to each viewer's browser
1869
- // (WebRTC). The database only carries the connection set-up messages:
1870
- // live/state { on, screen, cam, ts } (stream ids, so viewers know which video is which)
1871
- // live/viewers/<id> { join, offer, answer, oice/*, vice/* } one entry per watching browser
1872
- // Each viewer gets its own copy of the stream from the owner's computer, so a handful of viewers is
1873
- // fine; dozens would need a streaming server.
1874
- const ICE = { iceServers: [{ urls: ["stun:stun.l.google.com:19302", "stun:stun1.l.google.com:19302"] }] };
1875
- const live = { state: null, streams: null, peers: new Map(), viewer: null, audioCtx: null };
1876
- async function startLiveWatch() {
1877
- const app = await getFirebase();
1878
- if (!app) return;
1879
- app.database().ref("live/state").on("value", (s) => {
1880
- const st = s.val();
1881
- const wasOn = !!live.state;
1882
- live.state = st && st.on ? st : null;
1883
- document.querySelector('.rail-btn[data-nav="live"]').classList.toggle("is-live", !!live.state);
1884
- if (live.state && !wasOn && !live.streams) toast("🔴 Richard is live! Open Live in the side bar to watch.");
1885
- if (!live.state) stopWatching();
1886
- if (!$("view-live").hidden) renderLive();
1887
- }, () => {});
1888
- }
1889
- function renderLive() {
1890
- const on = !!live.state, mine = !!live.streams;
1891
- $("live-pill").hidden = !on;
1892
- $("live-owner").hidden = !chat.admin;
1893
- $("live-go").textContent = mine ? "■ End stream" : "🔴 Go live";
1894
- $("live-lede").textContent = mine ? "You're live. Everyone on the site can watch."
1895
- : on ? "Richard is live right now." : "Nobody's live right now. When Richard goes live, it shows up here.";
1896
- $("live-overlay").hidden = mine || !!live.viewer;
1897
- $("live-overlay-text").textContent = on ? "Richard is live" : "Not live right now";
1898
- $("live-watch").hidden = !on || mine;
1899
- renderGifts();
1900
- if (on) watchGifts();
1901
- updateViewerCount();
1902
- }
1903
-
1904
- // -- owner side --
1905
- async function goLive() {
1906
- if (live.streams) { await endLive(); return; }
1907
- const useScreen = $("live-use-screen").checked, useCam = $("live-use-cam").checked, useMic = $("live-use-mic").checked;
1908
- if (!useScreen && !useCam) { toast("Pick Screen or Camera (or both)."); return; }
2085
+ // ---------- Trivia: a quick quiz plus daily puzzle sites ----------
2086
+ // Questions come from Open Trivia Database (free, CC BY-SA 4.0). A session token stops repeats; if the
2087
+ // service can't be reached, a small built-in set is used instead.
2088
+ const TRIVIA_TOPICS = [["Anything", 0], ["NFL", "nfl"], ["NBA", "nba"], ["MLB", "mlb"], ["General", 9], ["Sports", 21], ["Video games", 15], ["Science", 17], ["Geography", 22],
2089
+ ["History", 23], ["Movies", 11], ["Music", 12], ["Animals", 27], ["Computers", 18], ["TV", 14]];
2090
+ const TRIVIA_LEVELS = [["Any", ""], ["Easy", "easy"], ["Medium", "medium"], ["Hard", "hard"]];
2091
+ const TRIVIA_KINDS = [["All", "all"], ["Players only", "players"], ["Teams & rules", "teams"]];
2092
+ const TRIVIA_SECONDS = 15, TRIVIA_COUNT = 10, TRIVIA_BEST_KEY = "rug-trivia-best";
2093
+ // The fallback set: [question, right answer, wrong answers...]
2094
+ const TRIVIA_BACKUP = [
2095
+ ["How many players does a football team have on the field at once?", "11", "9", "10", "12"],
2096
+ ["Which planet is known as the Red Planet?", "Mars", "Venus", "Jupiter", "Mercury"],
2097
+ ["What is the largest ocean on Earth?", "Pacific", "Atlantic", "Indian", "Arctic"],
2098
+ ["How many sides does a hexagon have?", "6", "5", "7", "8"],
2099
+ ["Which gas do plants take in from the air to make food?", "Carbon dioxide", "Oxygen", "Nitrogen", "Helium"],
2100
+ ["What is the capital of Japan?", "Tokyo", "Kyoto", "Osaka", "Seoul"],
2101
+ ["How many points is a touchdown worth (before the extra point)?", "6", "3", "7", "2"],
2102
+ ["Which animal is the largest mammal?", "Blue whale", "Elephant", "Giraffe", "Orca"],
2103
+ ["What is 12 × 12?", "144", "124", "132", "156"],
2104
+ ["Which continent is Egypt in?", "Africa", "Asia", "Europe", "South America"],
2105
+ ["How many minutes are in a day?", "1,440", "1,200", "2,400", "960"],
2106
+ ["What is the freezing point of water in Fahrenheit?", "32°F", "0°F", "100°F", "12°F"],
2107
+ ["Which country has the most people?", "India", "China", "USA", "Brazil"],
2108
+ ["In basketball, how many points is a shot from behind the arc?", "3", "2", "4", "1"],
2109
+ ["What is the hardest natural substance?", "Diamond", "Gold", "Iron", "Quartz"],
2110
+ ];
2111
+ // League quizzes (written for this site, not from the question service).
2112
+ // Each: [level e/m/h, kind t (teams, rules, history) or p (players), question, right answer, wrong answers...]
2113
+ const TRIVIA_LEAGUES = {
2114
+ nfl: [
2115
+ ["e", "t", "How many points is a field goal worth?", "3", "2", "1", "6"],
2116
+ ["e", "t", "How many points is a touchdown worth, before the extra point?", "6", "7", "5", "3"],
2117
+ ["e", "t", "How many yards are there between the two goal lines?", "100", "120", "110", "90"],
2118
+ ["e", "t", "How many players does each team have on the field at once?", "11", "10", "12", "9"],
2119
+ ["e", "t", "Which team plays its home games at Lambeau Field?", "Green Bay Packers", "Chicago Bears", "Minnesota Vikings", "Detroit Lions"],
2120
+ ["e", "t", "Which city are the Chiefs from?", "Kansas City", "St. Louis", "Denver", "Oklahoma City"],
2121
+ ["e", "t", "What are the NFL's two conferences called?", "AFC and NFC", "East and West", "American and National League", "Atlantic and Pacific"],
2122
+ ["e", "t", "How many downs does the offense get to gain 10 yards?", "4", "3", "5", "6"],
2123
+ ["e", "t", "What is it called when the quarterback is tackled behind the line of scrimmage?", "A sack", "A safety", "A fumble", "A blitz"],
2124
+ ["e", "t", "Which NFL team plays in New Orleans?", "Saints", "Pelicans", "Jaguars", "Buccaneers"],
2125
+ ["e", "t", "Which player snaps the ball to the quarterback?", "Center", "Guard", "Tackle", "Tight end"],
2126
+ ["e", "t", "Which NFL team plays in Seattle?", "Seahawks", "Sonics", "Mariners", "Sounders"],
2127
+ ["e", "t", "Which NFL team is from Buffalo?", "Bills", "Bisons", "Sabres", "Bulls"],
2128
+ ["m", "t", "How many teams are in the NFL?", "32", "30", "28", "34"],
2129
+ ["m", "t", "How many points is a safety worth?", "2", "1", "3", "6"],
2130
+ ["m", "t", "Which team's defense was nicknamed the \"Steel Curtain\"?", "Pittsburgh Steelers", "Chicago Bears", "Baltimore Ravens", "Cleveland Browns"],
2131
+ ["m", "t", "What trophy does the Super Bowl winner get?", "Vince Lombardi Trophy", "Stanley Cup", "Larry O'Brien Trophy", "Heisman Trophy"],
2132
+ ["m", "t", "How many minutes long is a regulation NFL game?", "60", "48", "90", "40"],
2133
+ ["m", "t", "Which team is nicknamed \"America's Team\"?", "Dallas Cowboys", "New York Giants", "Washington Commanders", "Pittsburgh Steelers"],
2134
+ ["m", "t", "In football, what is a \"Hail Mary\"?", "A long, desperate pass", "A trick kick", "A two-point try", "A goal-line stand"],
2135
+ ["m", "t", "How many timeouts does each team get per half?", "3", "2", "4", "5"],
2136
+ ["m", "t", "What does PAT stand for?", "Point after touchdown", "Pass and tackle", "Penalty against team", "Play after timeout"],
2137
+ ["m", "t", "In the NFL Draft, which team usually picks first?", "The team with the worst record", "The Super Bowl champion", "The team with the oldest roster", "Whoever wins a coin toss"],
2138
+ ["m", "t", "How many points is a two-point conversion worth?", "2", "1", "3", "6"],
2139
+ ["m", "t", "Which team moved from Oakland to Las Vegas?", "Raiders", "Chargers", "Rams", "Cardinals"],
2140
+ ["h", "t", "Which team won Super Bowl I?", "Green Bay Packers", "Kansas City Chiefs", "New York Jets", "Dallas Cowboys"],
2141
+ ["h", "t", "Which team had a perfect season, Super Bowl included, in 1972?", "Miami Dolphins", "New England Patriots", "Dallas Cowboys", "Oakland Raiders"],
2142
+ ["h", "t", "In what year was the first Super Bowl played?", "1967", "1960", "1970", "1958"],
2143
+ ["h", "t", "The Tennessee Titans used to be called what?", "Houston Oilers", "Memphis Showboats", "Nashville Stars", "Houston Texans"],
2144
+ ["h", "t", "How wide is an NFL field, sideline to sideline?", "53⅓ yards", "50 yards", "60 yards", "45 yards"],
2145
+ ["h", "t", "Which team has played in the most Super Bowls?", "New England Patriots", "Dallas Cowboys", "Pittsburgh Steelers", "Denver Broncos"],
2146
+ ["h", "t", "Where did the Rams play before moving back to Los Angeles in 2016?", "St. Louis", "Anaheim", "San Diego", "Oakland"],
2147
+ ["e", "p", "Which quarterback has won the most Super Bowls?", "Tom Brady", "Joe Montana", "Terry Bradshaw", "Patrick Mahomes"],
2148
+ ["e", "p", "Patrick Mahomes plays quarterback for which team?", "Kansas City Chiefs", "Buffalo Bills", "Dallas Cowboys", "Cincinnati Bengals"],
2149
+ ["e", "p", "What position does Travis Kelce play?", "Tight end", "Wide receiver", "Running back", "Linebacker"],
2150
+ ["e", "p", "Aaron Rodgers spent most of his career with which team?", "Green Bay Packers", "New York Jets", "Chicago Bears", "Minnesota Vikings"],
2151
+ ["e", "p", "Tom Brady won his first Super Bowl with which team?", "New England Patriots", "Tampa Bay Buccaneers", "Miami Dolphins", "New York Jets"],
2152
+ ["e", "p", "What position does Josh Allen of the Bills play?", "Quarterback", "Running back", "Kicker", "Linebacker"],
2153
+ ["e", "p", "Lamar Jackson plays for which team?", "Baltimore Ravens", "Pittsburgh Steelers", "Miami Dolphins", "Philadelphia Eagles"],
2154
+ ["e", "p", "Joe Burrow plays quarterback for which team?", "Cincinnati Bengals", "Cleveland Browns", "Detroit Lions", "Houston Texans"],
2155
+ ["e", "p", "Peyton Manning finished his career with which team?", "Denver Broncos", "Indianapolis Colts", "Tennessee Titans", "New York Giants"],
2156
+ ["e", "p", "Eli Manning played his whole career for which team?", "New York Giants", "New York Jets", "Indianapolis Colts", "San Diego Chargers"],
2157
+ ["m", "p", "Peyton Manning won his first Super Bowl with which team?", "Indianapolis Colts", "Denver Broncos", "Tennessee Titans", "New York Giants"],
2158
+ ["m", "p", "Tom Brady finished his career with which team?", "Tampa Bay Buccaneers", "New England Patriots", "Miami Dolphins", "Las Vegas Raiders"],
2159
+ ["m", "p", "Jerry Rice mostly played which position?", "Wide receiver", "Running back", "Quarterback", "Tight end"],
2160
+ ["m", "p", "Which player was nicknamed \"Sweetness\"?", "Walter Payton", "Barry Sanders", "Emmitt Smith", "Jim Brown"],
2161
+ ["m", "p", "Which quarterback led the 49ers to four Super Bowl wins in the 1980s?", "Joe Montana", "Steve Young", "Dan Marino", "John Elway"],
2162
+ ["m", "p", "Which player was nicknamed \"Prime Time\"?", "Deion Sanders", "Randy Moss", "Michael Irvin", "Terrell Owens"],
2163
+ ["m", "p", "Which running back was nicknamed \"Beast Mode\"?", "Marshawn Lynch", "Adrian Peterson", "LaDainian Tomlinson", "Derrick Henry"],
2164
+ ["m", "p", "Ray Lewis spent his whole career with which team?", "Baltimore Ravens", "Cleveland Browns", "Pittsburgh Steelers", "Cincinnati Bengals"],
2165
+ ["m", "p", "Which receiver was nicknamed \"Megatron\"?", "Calvin Johnson", "Randy Moss", "Julio Jones", "Larry Fitzgerald"],
2166
+ ["m", "p", "J.J. Watt mainly played which position?", "Defensive end", "Linebacker", "Cornerback", "Offensive tackle"],
2167
+ ["h", "p", "Who has the most career rushing yards in NFL history?", "Emmitt Smith", "Walter Payton", "Barry Sanders", "Jim Brown"],
2168
+ ["h", "p", "Who has the most career receiving yards in NFL history?", "Jerry Rice", "Larry Fitzgerald", "Terrell Owens", "Randy Moss"],
2169
+ ["h", "p", "Who has thrown the most career touchdown passes?", "Tom Brady", "Drew Brees", "Peyton Manning", "Brett Favre"],
2170
+ ["h", "p", "Who has the most career sacks since sacks became official in 1982?", "Bruce Smith", "Reggie White", "Lawrence Taylor", "Michael Strahan"],
2171
+ ["h", "p", "Who holds the single-season rushing record of 2,105 yards?", "Eric Dickerson", "Adrian Peterson", "Barry Sanders", "O.J. Simpson"],
2172
+ ["h", "p", "Who holds the single-season passing yards record (5,477)?", "Peyton Manning", "Drew Brees", "Patrick Mahomes", "Tom Brady"],
2173
+ ["h", "p", "Who was the first overall pick in the 2020 NFL Draft?", "Joe Burrow", "Justin Herbert", "Tua Tagovailoa", "Trevor Lawrence"],
2174
+ ["h", "p", "Barry Sanders played his whole career for which team?", "Detroit Lions", "Chicago Bears", "Dallas Cowboys", "Minnesota Vikings"],
2175
+ ["h", "p", "Who caught \"The Catch\" from Joe Montana in the 1982 NFC Championship?", "Dwight Clark", "Jerry Rice", "Roger Craig", "John Taylor"],
2176
+ ["h", "p", "Who was the MVP of Super Bowl I?", "Bart Starr", "Johnny Unitas", "Joe Namath", "Vince Lombardi"],
2177
+ ["h", "p", "Which defensive player won NFL MVP in 1986?", "Lawrence Taylor", "Reggie White", "Mike Singletary", "Howie Long"],
2178
+ ],
2179
+ nba: [
2180
+ ["e", "t", "How many players does each team have on the court at once?", "5", "6", "4", "7"],
2181
+ ["e", "t", "How many points is a free throw worth?", "1", "2", "3", "0.5"],
2182
+ ["e", "t", "How high is the rim off the floor?", "10 feet", "9 feet", "11 feet", "12 feet"],
2183
+ ["e", "t", "Which team is from Golden State?", "Warriors", "Kings", "Clippers", "Suns"],
2184
+ ["e", "t", "Which city are the Heat from?", "Miami", "Phoenix", "Houston", "Orlando"],
2185
+ ["e", "t", "What is it called when a player moves their feet without dribbling?", "Traveling", "Double dribble", "Goaltending", "Carrying"],
2186
+ ["e", "t", "Which NBA team plays in San Antonio?", "Spurs", "Rockets", "Mavericks", "Thunder"],
2187
+ ["e", "t", "Which NBA team is from Toronto?", "Raptors", "Maple Leafs", "Blue Jays", "Huskies"],
2188
+ ["e", "t", "Which team plays at Madison Square Garden?", "New York Knicks", "Brooklyn Nets", "Boston Celtics", "Philadelphia 76ers"],
2189
+ ["e", "t", "Which NBA team is from Denver?", "Nuggets", "Broncos", "Rockies", "Avalanche"],
2190
+ ["m", "t", "How many teams are in the NBA?", "30", "32", "28", "24"],
2191
+ ["m", "t", "How many minutes long is an NBA quarter?", "12", "10", "15", "20"],
2192
+ ["m", "t", "How many fouls does it take for a player to foul out?", "6", "5", "4", "7"],
2193
+ ["m", "t", "How many seconds is the NBA shot clock?", "24", "30", "35", "20"],
2194
+ ["m", "t", "Which team has won the most NBA championships?", "Boston Celtics", "Los Angeles Lakers", "Chicago Bulls", "Golden State Warriors"],
2195
+ ["m", "t", "What is a triple-double?", "10 or more in three stat categories", "Three dunks in a row", "Scoring 30 points", "Three straight wins"],
2196
+ ["m", "t", "How many wins does it take to win the NBA Finals?", "4", "3", "5", "7"],
2197
+ ["m", "t", "In basketball, what is \"the paint\"?", "The lane near the basket", "The three-point line", "The center circle", "The bench area"],
2198
+ ["m", "t", "The Larry O'Brien Trophy goes to whom?", "The NBA champion", "The MVP", "The top rookie", "The best defender"],
2199
+ ["h", "t", "Which team won the first league title, in 1947?", "Philadelphia Warriors", "Boston Celtics", "Minneapolis Lakers", "New York Knicks"],
2200
+ ["h", "t", "How far is the three-point line at the top of the arc?", "23 feet 9 inches", "22 feet", "25 feet", "20 feet 6 inches"],
2201
+ ["h", "t", "Which team moved from Seattle to Oklahoma City in 2008?", "SuperSonics", "Kings", "Grizzlies", "Hornets"],
2202
+ ["h", "t", "In what year did the NBA add the three-point line?", "1979", "1967", "1984", "1990"],
2203
+ ["h", "t", "How many seconds does a player have to shoot a free throw?", "10", "5", "8", "15"],
2204
+ ["h", "t", "Who did the Celtics beat in the 2008 NBA Finals?", "Los Angeles Lakers", "San Antonio Spurs", "Detroit Pistons", "Dallas Mavericks"],
2205
+ ["e", "p", "Michael Jordan won all six of his titles with which team?", "Chicago Bulls", "Washington Wizards", "Detroit Pistons", "Boston Celtics"],
2206
+ ["e", "p", "Kobe Bryant spent his whole career with which team?", "Los Angeles Lakers", "Los Angeles Clippers", "Charlotte Hornets", "Philadelphia 76ers"],
2207
+ ["e", "p", "Stephen Curry is best known for what?", "Three-point shooting", "Blocking shots", "Dunking", "Rebounding"],
2208
+ ["e", "p", "What position did Shaquille O'Neal play?", "Center", "Point guard", "Shooting guard", "Small forward"],
2209
+ ["e", "p", "Which player was nicknamed \"The Black Mamba\"?", "Kobe Bryant", "Kevin Durant", "Allen Iverson", "Tim Duncan"],
2210
+ ["e", "p", "Stephen Curry has played his whole career for which team?", "Golden State Warriors", "Charlotte Hornets", "Sacramento Kings", "Phoenix Suns"],
2211
+ ["e", "p", "LeBron James is often called what?", "King James", "The Answer", "The Mailman", "The Dream"],
2212
+ ["e", "p", "Who famously wore number 23 for the Chicago Bulls?", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Derrick Rose"],
2213
+ ["e", "p", "Victor Wembanyama plays for which team?", "San Antonio Spurs", "Houston Rockets", "Orlando Magic", "Detroit Pistons"],
2214
+ ["e", "p", "Kevin Durant goes by which two letters?", "KD", "KG", "KB", "KT"],
2215
+ ["m", "p", "Who is the NBA's all-time leading scorer?", "LeBron James", "Kareem Abdul-Jabbar", "Michael Jordan", "Kobe Bryant"],
2216
+ ["m", "p", "Which team drafted LeBron James?", "Cleveland Cavaliers", "Miami Heat", "Los Angeles Lakers", "New York Knicks"],
2217
+ ["m", "p", "Who is nicknamed \"The Greek Freak\"?", "Giannis Antetokounmpo", "Nikola Jokić", "Luka Dončić", "Joel Embiid"],
2218
+ ["m", "p", "Magic Johnson played his whole career for which team?", "Los Angeles Lakers", "Orlando Magic", "Detroit Pistons", "Boston Celtics"],
2219
+ ["m", "p", "Luka Dončić was traded in 2025 to which team?", "Los Angeles Lakers", "New York Knicks", "Miami Heat", "Boston Celtics"],
2220
+ ["m", "p", "Kevin Durant won his first title with which team?", "Golden State Warriors", "Oklahoma City Thunder", "Brooklyn Nets", "Phoenix Suns"],
2221
+ ["m", "p", "Tim Duncan spent his whole career with which team?", "San Antonio Spurs", "Houston Rockets", "Dallas Mavericks", "Utah Jazz"],
2222
+ ["m", "p", "Dirk Nowitzki spent his whole career with which team?", "Dallas Mavericks", "San Antonio Spurs", "Sacramento Kings", "Milwaukee Bucks"],
2223
+ ["m", "p", "Nikola Jokić plays for which team?", "Denver Nuggets", "Philadelphia 76ers", "Minnesota Timberwolves", "Utah Jazz"],
2224
+ ["m", "p", "Larry Bird played his whole career for which team?", "Boston Celtics", "Indiana Pacers", "Los Angeles Lakers", "Detroit Pistons"],
2225
+ ["h", "p", "How many points did Wilt Chamberlain score in his record single game?", "100", "81", "73", "92"],
2226
+ ["h", "p", "Kareem Abdul-Jabbar's famous shot was called what?", "The skyhook", "The fadeaway", "The floater", "The alley-oop"],
2227
+ ["h", "p", "Who has the most career assists in NBA history?", "John Stockton", "Chris Paul", "Jason Kidd", "Magic Johnson"],
2228
+ ["h", "p", "Who has the most career rebounds in NBA history?", "Wilt Chamberlain", "Bill Russell", "Kareem Abdul-Jabbar", "Dennis Rodman"],
2229
+ ["h", "p", "How many championships did Bill Russell win as a player?", "11", "8", "6", "10"],
2230
+ ["h", "p", "Who was the first overall pick in the 2003 NBA Draft?", "LeBron James", "Carmelo Anthony", "Darko Miličić", "Dwyane Wade"],
2231
+ ["h", "p", "Who scored 81 points in a single game in 2006?", "Kobe Bryant", "LeBron James", "Allen Iverson", "Tracy McGrady"],
2232
+ ["h", "p", "Who has the most career blocked shots in NBA history?", "Hakeem Olajuwon", "Dikembe Mutombo", "Shaquille O'Neal", "Tim Duncan"],
2233
+ ["h", "p", "Which player was nicknamed \"The Mailman\"?", "Karl Malone", "John Stockton", "Charles Barkley", "Patrick Ewing"],
2234
+ ["h", "p", "Who was the 2023 NBA Finals MVP?", "Nikola Jokić", "Jimmy Butler", "Stephen Curry", "Jamal Murray"],
2235
+ ],
2236
+ mlb: [
2237
+ ["e", "t", "How many players does the fielding team have on the field?", "9", "10", "11", "8"],
2238
+ ["e", "t", "How many innings are in a regulation game?", "9", "7", "8", "10"],
2239
+ ["e", "t", "How many strikes make a strikeout?", "3", "2", "4", "5"],
2240
+ ["e", "t", "How many balls make a walk?", "4", "3", "5", "6"],
2241
+ ["e", "t", "Which team plays at Fenway Park?", "Boston Red Sox", "New York Yankees", "Chicago White Sox", "Baltimore Orioles"],
2242
+ ["e", "t", "Which team plays at Wrigley Field?", "Chicago Cubs", "Chicago White Sox", "Milwaukee Brewers", "St. Louis Cardinals"],
2243
+ ["e", "t", "What is a grand slam?", "A home run with the bases loaded", "Four home runs in a game", "A triple play", "Hitting for the cycle"],
2244
+ ["e", "t", "What are MLB's two leagues?", "American League and National League", "East and West", "AFC and NFC", "Major and Minor League"],
2245
+ ["e", "t", "How many outs are in each half-inning?", "3", "2", "4", "6"],
2246
+ ["e", "t", "Which player crouches behind home plate and catches the pitches?", "Catcher", "Umpire", "Shortstop", "Pitcher"],
2247
+ ["e", "t", "Which MLB team is from Toronto?", "Blue Jays", "Raptors", "Maple Leafs", "Argonauts"],
2248
+ ["e", "t", "Which MLB team is from Houston?", "Astros", "Rangers", "Rockets", "Texans"],
2249
+ ["m", "t", "How many teams are in MLB?", "30", "32", "28", "26"],
2250
+ ["m", "t", "How far apart are the bases?", "90 feet", "60 feet", "100 feet", "75 feet"],
2251
+ ["m", "t", "Which team has won the most World Series?", "New York Yankees", "St. Louis Cardinals", "Boston Red Sox", "Los Angeles Dodgers"],
2252
+ ["m", "t", "In what year did the Cubs end their 108-year World Series drought?", "2016", "2004", "2010", "2019"],
2253
+ ["m", "t", "What is \"the Green Monster\"?", "Fenway Park's left-field wall", "The Mariners' mascot", "A trick pitch", "The World Series trophy"],
2254
+ ["m", "t", "Which team moved to Los Angeles from Brooklyn?", "Dodgers", "Angels", "Giants", "Padres"],
2255
+ ["m", "t", "What does a pitcher's ERA measure?", "Earned runs allowed per 9 innings", "Errors per game", "Strikeouts per inning", "Pitches per at-bat"],
2256
+ ["m", "t", "What song do fans sing during the seventh-inning stretch?", "Take Me Out to the Ball Game", "Sweet Caroline", "Centerfield", "We Will Rock You"],
2257
+ ["m", "t", "What is a no-hitter?", "A game where a team gets no hits", "A game with no home runs", "A game with no runs", "A game with no errors"],
2258
+ ["m", "t", "What is it called when a batter hits a single, double, triple and home run in one game?", "Hitting for the cycle", "A grand slam", "A golden sombrero", "A perfect game"],
2259
+ ["m", "t", "What is a perfect game?", "No batter on the other team reaches base", "A game with no errors", "A shutout win", "Striking out every batter"],
2260
+ ["m", "t", "Which team plays at Oracle Park?", "San Francisco Giants", "Oakland Athletics", "San Diego Padres", "Seattle Mariners"],
2261
+ ["h", "t", "How far is the pitcher's rubber from home plate?", "60 feet 6 inches", "50 feet", "66 feet", "90 feet"],
2262
+ ["h", "t", "Which team won the first World Series, in 1903?", "Boston Americans", "Pittsburgh Pirates", "New York Giants", "Chicago Cubs"],
2263
+ ["h", "t", "In what year did the Red Sox end the \"Curse of the Bambino\"?", "2004", "1986", "2007", "2013"],
2264
+ ["h", "t", "Which team moved from Montreal to Washington in 2005?", "Nationals", "Senators", "Orioles", "Marlins"],
2265
+ ["h", "t", "How many stitches are on a baseball?", "108", "96", "120", "88"],
2266
+ ["e", "p", "Who broke baseball's color barrier in 1947?", "Jackie Robinson", "Willie Mays", "Satchel Paige", "Larry Doby"],
2267
+ ["e", "p", "Shohei Ohtani is famous for doing what at a top level?", "Both pitching and hitting", "Stealing bases", "Catching", "Switch-hitting"],
2268
+ ["e", "p", "Babe Ruth is best remembered playing for which team?", "New York Yankees", "Boston Red Sox", "Boston Braves", "Chicago Cubs"],
2269
+ ["e", "p", "Aaron Judge plays for which team?", "New York Yankees", "Boston Red Sox", "Los Angeles Dodgers", "Houston Astros"],
2270
+ ["e", "p", "Shohei Ohtani signed with which team in 2023?", "Los Angeles Dodgers", "Los Angeles Angels", "San Diego Padres", "Toronto Blue Jays"],
2271
+ ["e", "p", "Derek Jeter played his whole career for which team?", "New York Yankees", "New York Mets", "Boston Red Sox", "Miami Marlins"],
2272
+ ["e", "p", "Mike Trout plays for which team?", "Los Angeles Angels", "Los Angeles Dodgers", "Philadelphia Phillies", "Seattle Mariners"],
2273
+ ["e", "p", "Babe Ruth was nicknamed what?", "The Bambino", "The Iron Horse", "Mr. October", "The Say Hey Kid"],
2274
+ ["e", "p", "Ken Griffey Jr. is best known for playing with which team?", "Seattle Mariners", "Cincinnati Reds", "Atlanta Braves", "Chicago White Sox"],
2275
+ ["e", "p", "Albert Pujols became a star with which team?", "St. Louis Cardinals", "Chicago Cubs", "Los Angeles Angels", "Houston Astros"],
2276
+ ["m", "p", "Who holds the record for most career home runs?", "Barry Bonds", "Hank Aaron", "Babe Ruth", "Alex Rodriguez"],
2277
+ ["m", "p", "Cal Ripken Jr. spent his whole career with which team?", "Baltimore Orioles", "New York Yankees", "Boston Red Sox", "Texas Rangers"],
2278
+ ["m", "p", "What number did Jackie Robinson wear, now retired by every MLB team?", "42", "24", "21", "44"],
2279
+ ["m", "p", "Babe Ruth started his career as what kind of player?", "Pitcher", "Catcher", "Shortstop", "Center fielder"],
2280
+ ["m", "p", "Which player was nicknamed \"Mr. October\"?", "Reggie Jackson", "Derek Jeter", "David Ortiz", "Mickey Mantle"],
2281
+ ["m", "p", "In what year did Hank Aaron break Babe Ruth's home run record?", "1974", "1968", "1980", "1961"],
2282
+ ["m", "p", "Who was nicknamed \"The Iron Horse\"?", "Lou Gehrig", "Cal Ripken Jr.", "Joe DiMaggio", "Ty Cobb"],
2283
+ ["m", "p", "Mariano Rivera pitched his whole career for which team?", "New York Yankees", "Boston Red Sox", "Atlanta Braves", "Texas Rangers"],
2284
+ ["m", "p", "How many home runs did Aaron Judge hit in 2022 to set the American League record?", "62", "61", "60", "65"],
2285
+ ["m", "p", "Ichiro Suzuki started his MLB career with which team?", "Seattle Mariners", "New York Yankees", "Miami Marlins", "Los Angeles Dodgers"],
2286
+ ["h", "p", "Who has the most career hits in MLB history?", "Pete Rose", "Ty Cobb", "Derek Jeter", "Ichiro Suzuki"],
2287
+ ["h", "p", "Who holds the record for most home runs in one season?", "Barry Bonds", "Mark McGwire", "Aaron Judge", "Roger Maris"],
2288
+ ["h", "p", "Who has the most career strikeouts as a pitcher?", "Nolan Ryan", "Randy Johnson", "Roger Clemens", "Walter Johnson"],
2289
+ ["h", "p", "Who has the most career wins as a pitcher?", "Cy Young", "Walter Johnson", "Greg Maddux", "Warren Spahn"],
2290
+ ["h", "p", "Who had a record 56-game hitting streak in 1941?", "Joe DiMaggio", "Ted Williams", "Ty Cobb", "Lou Gehrig"],
2291
+ ["h", "p", "Who was the last player to hit .400 in a season?", "Ted Williams", "Tony Gwynn", "George Brett", "Rod Carew"],
2292
+ ["h", "p", "How many games in a row did Cal Ripken Jr. play?", "2,632", "2,130", "2,000", "3,001"],
2293
+ ["h", "p", "Who threw the only perfect game in World Series history?", "Don Larsen", "Sandy Koufax", "Roy Halladay", "Whitey Ford"],
2294
+ ["h", "p", "Who has the most career stolen bases?", "Rickey Henderson", "Lou Brock", "Ty Cobb", "Tim Raines"],
2295
+ ["h", "p", "Who has the most career saves?", "Mariano Rivera", "Trevor Hoffman", "Lee Smith", "Dennis Eckersley"],
2296
+ ],
2297
+ };
2298
+
2299
+ // Team quizzes are built from these facts: [name, division, home field (null when it was just renamed or is
2300
+ // changing), two players most tied to the team, and optionally where the team played before]
2301
+ // ONE_TEAM: players who spent their whole career with one team; only they are used as wrong answers,
2302
+ // so a "wrong" choice can never secretly have played for the team being asked about.
2303
+ const TEAM_FACTS = {
2304
+ nfl: {
2305
+ venue: "stadium",
2306
+ teams: [
2307
+ ["Buffalo Bills", "AFC East", "Highmark Stadium", ["Jim Kelly", "Bruce Smith"]],
2308
+ ["Miami Dolphins", "AFC East", "Hard Rock Stadium", ["Dan Marino", "Bob Griese"]],
2309
+ ["New England Patriots", "AFC East", "Gillette Stadium", ["Tom Brady", "Tedy Bruschi"]],
2310
+ ["New York Jets", "AFC East", "MetLife Stadium", ["Joe Namath", "Curtis Martin"]],
2311
+ ["Baltimore Ravens", "AFC North", "M&T Bank Stadium", ["Ray Lewis", "Ed Reed"], "Cleveland"],
2312
+ ["Cincinnati Bengals", "AFC North", "Paycor Stadium", ["Ken Anderson", "Anthony Muñoz"]],
2313
+ ["Cleveland Browns", "AFC North", "Huntington Bank Field", ["Jim Brown", "Otto Graham"]],
2314
+ ["Pittsburgh Steelers", "AFC North", "Acrisure Stadium", ["Terry Bradshaw", "Joe Greene"]],
2315
+ ["Houston Texans", "AFC South", "NRG Stadium", ["Andre Johnson", "J.J. Watt"]],
2316
+ ["Indianapolis Colts", "AFC South", "Lucas Oil Stadium", ["Peyton Manning", "Johnny Unitas"], "Baltimore"],
2317
+ ["Jacksonville Jaguars", "AFC South", "EverBank Stadium", ["Tony Boselli", "Fred Taylor"]],
2318
+ ["Tennessee Titans", "AFC South", "Nissan Stadium", ["Eddie George", "Steve McNair"], "Houston"],
2319
+ ["Denver Broncos", "AFC West", "Empower Field at Mile High", ["John Elway", "Terrell Davis"]],
2320
+ ["Kansas City Chiefs", "AFC West", "Arrowhead Stadium", ["Patrick Mahomes", "Derrick Thomas"]],
2321
+ ["Las Vegas Raiders", "AFC West", "Allegiant Stadium", ["Marcus Allen", "Tim Brown"], "Oakland"],
2322
+ ["Los Angeles Chargers", "AFC West", "SoFi Stadium", ["LaDainian Tomlinson", "Junior Seau"], "San Diego"],
2323
+ ["Dallas Cowboys", "NFC East", "AT&T Stadium", ["Troy Aikman", "Emmitt Smith"]],
2324
+ ["New York Giants", "NFC East", "MetLife Stadium", ["Lawrence Taylor", "Eli Manning"]],
2325
+ ["Philadelphia Eagles", "NFC East", "Lincoln Financial Field", ["Brian Dawkins", "Reggie White"]],
2326
+ ["Washington Commanders", "NFC East", "Northwest Stadium", ["Darrell Green", "Joe Theismann"]],
2327
+ ["Chicago Bears", "NFC North", "Soldier Field", ["Walter Payton", "Dick Butkus"]],
2328
+ ["Detroit Lions", "NFC North", "Ford Field", ["Barry Sanders", "Calvin Johnson"]],
2329
+ ["Green Bay Packers", "NFC North", "Lambeau Field", ["Brett Favre", "Bart Starr"]],
2330
+ ["Minnesota Vikings", "NFC North", "U.S. Bank Stadium", ["Randy Moss", "Adrian Peterson"]],
2331
+ ["Atlanta Falcons", "NFC South", "Mercedes-Benz Stadium", ["Matt Ryan", "Michael Vick"]],
2332
+ ["Carolina Panthers", "NFC South", "Bank of America Stadium", ["Cam Newton", "Steve Smith Sr."]],
2333
+ ["New Orleans Saints", "NFC South", "Caesars Superdome", ["Drew Brees", "Archie Manning"]],
2334
+ ["Tampa Bay Buccaneers", "NFC South", "Raymond James Stadium", ["Derrick Brooks", "Warren Sapp"]],
2335
+ ["Arizona Cardinals", "NFC West", "State Farm Stadium", ["Larry Fitzgerald", "Kurt Warner"], "St. Louis"],
2336
+ ["San Francisco 49ers", "NFC West", "Levi's Stadium", ["Joe Montana", "Jerry Rice"]],
2337
+ ["Seattle Seahawks", "NFC West", "Lumen Field", ["Steve Largent", "Russell Wilson"]],
2338
+ ["Los Angeles Rams", "NFC West", "SoFi Stadium", ["Aaron Donald", "Eric Dickerson"], "St. Louis"],
2339
+ ],
2340
+ // cities a team also played in long ago, never offered as wrong answers for it
2341
+ oldHomes: { "Arizona Cardinals": ["Chicago"], "Las Vegas Raiders": ["Los Angeles"], "Los Angeles Rams": ["Cleveland", "Anaheim"] },
2342
+ oneTeam: { "Dan Marino": "Miami Dolphins", "Bob Griese": "Miami Dolphins", "Jim Kelly": "Buffalo Bills", "Ray Lewis": "Baltimore Ravens",
2343
+ "Terry Bradshaw": "Pittsburgh Steelers", "Joe Greene": "Pittsburgh Steelers", "Walter Payton": "Chicago Bears", "Dick Butkus": "Chicago Bears",
2344
+ "Barry Sanders": "Detroit Lions", "Calvin Johnson": "Detroit Lions", "Bart Starr": "Green Bay Packers", "Troy Aikman": "Dallas Cowboys",
2345
+ "Lawrence Taylor": "New York Giants", "Eli Manning": "New York Giants", "Derrick Brooks": "Tampa Bay Buccaneers", "John Elway": "Denver Broncos",
2346
+ "Terrell Davis": "Denver Broncos", "Derrick Thomas": "Kansas City Chiefs", "Steve Largent": "Seattle Seahawks", "Darrell Green": "Washington Commanders",
2347
+ "Tedy Bruschi": "New England Patriots", "Larry Fitzgerald": "Arizona Cardinals", "Aaron Donald": "Los Angeles Rams", "Ken Anderson": "Cincinnati Bengals",
2348
+ "Anthony Muñoz": "Cincinnati Bengals", "Jim Brown": "Cleveland Browns", "Otto Graham": "Cleveland Browns", "Tony Boselli": "Jacksonville Jaguars" },
2349
+ },
2350
+ nba: {
2351
+ venue: "arena",
2352
+ teams: [
2353
+ ["Boston Celtics", "Atlantic", "TD Garden", ["Larry Bird", "Bill Russell"]],
2354
+ ["Brooklyn Nets", "Atlantic", "Barclays Center", ["Jason Kidd", "Vince Carter"], "New Jersey"],
2355
+ ["New York Knicks", "Atlantic", "Madison Square Garden", ["Patrick Ewing", "Walt Frazier"]],
2356
+ ["Philadelphia 76ers", "Atlantic", null, ["Allen Iverson", "Julius Erving"], "Syracuse"],
2357
+ ["Toronto Raptors", "Atlantic", "Scotiabank Arena", ["Vince Carter", "Kyle Lowry"]],
2358
+ ["Chicago Bulls", "Central", "United Center", ["Michael Jordan", "Scottie Pippen"]],
2359
+ ["Cleveland Cavaliers", "Central", null, ["LeBron James", "Zydrunas Ilgauskas"]],
2360
+ ["Detroit Pistons", "Central", "Little Caesars Arena", ["Isiah Thomas", "Joe Dumars"], "Fort Wayne"],
2361
+ ["Indiana Pacers", "Central", "Gainbridge Fieldhouse", ["Reggie Miller", "Rik Smits"]],
2362
+ ["Milwaukee Bucks", "Central", "Fiserv Forum", ["Giannis Antetokounmpo", "Kareem Abdul-Jabbar"]],
2363
+ ["Atlanta Hawks", "Southeast", "State Farm Arena", ["Dominique Wilkins", "Trae Young"], "St. Louis"],
2364
+ ["Charlotte Hornets", "Southeast", "Spectrum Center", ["Kemba Walker", "Muggsy Bogues"]],
2365
+ ["Miami Heat", "Southeast", "Kaseya Center", ["Dwyane Wade", "Alonzo Mourning"]],
2366
+ ["Orlando Magic", "Southeast", "Kia Center", ["Shaquille O'Neal", "Dwight Howard"]],
2367
+ ["Washington Wizards", "Southeast", "Capital One Arena", ["Wes Unseld", "Elvin Hayes"], "Baltimore"],
2368
+ ["Denver Nuggets", "Northwest", "Ball Arena", ["Nikola Jokić", "Alex English"]],
2369
+ ["Minnesota Timberwolves", "Northwest", "Target Center", ["Kevin Garnett", "Anthony Edwards"]],
2370
+ ["Oklahoma City Thunder", "Northwest", "Paycom Center", ["Shai Gilgeous-Alexander", "Kevin Durant"], "Seattle"],
2371
+ ["Portland Trail Blazers", "Northwest", "Moda Center", ["Clyde Drexler", "Damian Lillard"]],
2372
+ ["Utah Jazz", "Northwest", "Delta Center", ["Karl Malone", "John Stockton"], "New Orleans"],
2373
+ ["Golden State Warriors", "Pacific", "Chase Center", ["Stephen Curry", "Wilt Chamberlain"], "Philadelphia"],
2374
+ ["Los Angeles Clippers", "Pacific", "Intuit Dome", ["Blake Griffin", "Chris Paul"], "San Diego"],
2375
+ ["Los Angeles Lakers", "Pacific", "Crypto.com Arena", ["Magic Johnson", "Kobe Bryant"], "Minneapolis"],
2376
+ ["Phoenix Suns", "Pacific", null, ["Steve Nash", "Charles Barkley"]],
2377
+ ["Sacramento Kings", "Pacific", "Golden 1 Center", ["Chris Webber", "Peja Stojaković"], "Kansas City"],
2378
+ ["Dallas Mavericks", "Southwest", "American Airlines Center", ["Dirk Nowitzki", "Luka Dončić"]],
2379
+ ["Houston Rockets", "Southwest", "Toyota Center", ["Hakeem Olajuwon", "Yao Ming"], "San Diego"],
2380
+ ["Memphis Grizzlies", "Southwest", "FedExForum", ["Ja Morant", "Marc Gasol"], "Vancouver"],
2381
+ ["New Orleans Pelicans", "Southwest", "Smoothie King Center", ["Anthony Davis", "Zion Williamson"]],
2382
+ ["San Antonio Spurs", "Southwest", "Frost Bank Center", ["Tim Duncan", "David Robinson"]],
2383
+ ],
2384
+ oldHomes: { "Golden State Warriors": ["San Francisco", "Oakland"], "Sacramento Kings": ["Cincinnati", "Rochester", "Omaha"], "Los Angeles Clippers": ["Buffalo"],
2385
+ "Atlanta Hawks": ["Milwaukee", "Tri-Cities"], "Washington Wizards": ["Chicago"], "Brooklyn Nets": ["New York"] },
2386
+ oneTeam: { "Larry Bird": "Boston Celtics", "Bill Russell": "Boston Celtics", "Kobe Bryant": "Los Angeles Lakers", "Magic Johnson": "Los Angeles Lakers",
2387
+ "Tim Duncan": "San Antonio Spurs", "David Robinson": "San Antonio Spurs", "Dirk Nowitzki": "Dallas Mavericks", "Reggie Miller": "Indiana Pacers",
2388
+ "Rik Smits": "Indiana Pacers", "John Stockton": "Utah Jazz", "Stephen Curry": "Golden State Warriors", "Isiah Thomas": "Detroit Pistons",
2389
+ "Joe Dumars": "Detroit Pistons", "Wes Unseld": "Washington Wizards", "Yao Ming": "Houston Rockets", "Nikola Jokić": "Denver Nuggets",
2390
+ "Giannis Antetokounmpo": "Milwaukee Bucks", "Anthony Edwards": "Minnesota Timberwolves" },
2391
+ },
2392
+ mlb: {
2393
+ venue: "ballpark",
2394
+ teams: [
2395
+ ["Baltimore Orioles", "AL East", "Oriole Park at Camden Yards", ["Cal Ripken Jr.", "Brooks Robinson"], "St. Louis"],
2396
+ ["Boston Red Sox", "AL East", "Fenway Park", ["Ted Williams", "David Ortiz"]],
2397
+ ["New York Yankees", "AL East", "Yankee Stadium", ["Babe Ruth", "Derek Jeter"]],
2398
+ ["Tampa Bay Rays", "AL East", null, ["Evan Longoria", "Carl Crawford"]],
2399
+ ["Toronto Blue Jays", "AL East", "Rogers Centre", ["Roberto Alomar", "José Bautista"]],
2400
+ ["Chicago White Sox", "AL Central", null, ["Frank Thomas", "Paul Konerko"]],
2401
+ ["Cleveland Guardians", "AL Central", "Progressive Field", ["Bob Feller", "Jim Thome"]],
2402
+ ["Detroit Tigers", "AL Central", "Comerica Park", ["Al Kaline", "Miguel Cabrera"]],
2403
+ ["Kansas City Royals", "AL Central", "Kauffman Stadium", ["George Brett", "Salvador Pérez"]],
2404
+ ["Minnesota Twins", "AL Central", "Target Field", ["Kirby Puckett", "Joe Mauer"], "Washington"],
2405
+ ["Houston Astros", "AL West", null, ["Craig Biggio", "Jeff Bagwell"]],
2406
+ ["Los Angeles Angels", "AL West", "Angel Stadium", ["Mike Trout", "Tim Salmon"]],
2407
+ ["Athletics", "AL West", null, ["Rickey Henderson", "Reggie Jackson"], "Oakland"],
2408
+ ["Seattle Mariners", "AL West", "T-Mobile Park", ["Ken Griffey Jr.", "Ichiro Suzuki"]],
2409
+ ["Texas Rangers", "AL West", "Globe Life Field", ["Iván Rodríguez", "Nolan Ryan"]],
2410
+ ["Atlanta Braves", "NL East", "Truist Park", ["Hank Aaron", "Chipper Jones"], "Milwaukee"],
2411
+ ["Miami Marlins", "NL East", "loanDepot park", ["Giancarlo Stanton", "Jeff Conine"]],
2412
+ ["New York Mets", "NL East", "Citi Field", ["Tom Seaver", "Mike Piazza"]],
2413
+ ["Philadelphia Phillies", "NL East", "Citizens Bank Park", ["Mike Schmidt", "Bryce Harper"]],
2414
+ ["Washington Nationals", "NL East", "Nationals Park", ["Ryan Zimmerman", "Max Scherzer"], "Montreal"],
2415
+ ["Chicago Cubs", "NL Central", "Wrigley Field", ["Ernie Banks", "Ryne Sandberg"]],
2416
+ ["Cincinnati Reds", "NL Central", "Great American Ball Park", ["Johnny Bench", "Pete Rose"]],
2417
+ ["Milwaukee Brewers", "NL Central", "American Family Field", ["Robin Yount", "Ryan Braun"], "Seattle"],
2418
+ ["Pittsburgh Pirates", "NL Central", "PNC Park", ["Roberto Clemente", "Willie Stargell"]],
2419
+ ["St. Louis Cardinals", "NL Central", "Busch Stadium", ["Stan Musial", "Albert Pujols"]],
2420
+ ["Arizona Diamondbacks", "NL West", "Chase Field", ["Randy Johnson", "Luis Gonzalez"]],
2421
+ ["Colorado Rockies", "NL West", "Coors Field", ["Todd Helton", "Larry Walker"]],
2422
+ ["Los Angeles Dodgers", "NL West", "Dodger Stadium", ["Sandy Koufax", "Clayton Kershaw"], "Brooklyn"],
2423
+ ["San Diego Padres", "NL West", "Petco Park", ["Tony Gwynn", "Trevor Hoffman"]],
2424
+ ["San Francisco Giants", "NL West", "Oracle Park", ["Willie Mays", "Barry Bonds"], "New York"],
2425
+ ],
2426
+ oldHomes: { "Baltimore Orioles": ["Milwaukee"], "Atlanta Braves": ["Boston"], "Athletics": ["Kansas City", "Philadelphia"] },
2427
+ oneTeam: { "Cal Ripken Jr.": "Baltimore Orioles", "Brooks Robinson": "Baltimore Orioles", "Ted Williams": "Boston Red Sox", "Derek Jeter": "New York Yankees",
2428
+ "Lou Gehrig": "New York Yankees", "Mariano Rivera": "New York Yankees", "Al Kaline": "Detroit Tigers", "George Brett": "Kansas City Royals",
2429
+ "Salvador Pérez": "Kansas City Royals", "Kirby Puckett": "Minnesota Twins", "Joe Mauer": "Minnesota Twins", "Mike Trout": "Los Angeles Angels",
2430
+ "Tim Salmon": "Los Angeles Angels", "Chipper Jones": "Atlanta Braves", "Tony Gwynn": "San Diego Padres", "Ernie Banks": "Chicago Cubs",
2431
+ "Johnny Bench": "Cincinnati Reds", "Robin Yount": "Milwaukee Brewers", "Roberto Clemente": "Pittsburgh Pirates", "Willie Stargell": "Pittsburgh Pirates",
2432
+ "Stan Musial": "St. Louis Cardinals", "Sandy Koufax": "Los Angeles Dodgers", "Clayton Kershaw": "Los Angeles Dodgers", "Todd Helton": "Colorado Rockies",
2433
+ "Ryan Zimmerman": "Washington Nationals", "Bob Feller": "Cleveland Guardians", "Craig Biggio": "Houston Astros", "Jeff Bagwell": "Houston Astros",
2434
+ "Mike Schmidt": "Philadelphia Phillies", "Edgar Martínez": "Seattle Mariners", "Ryan Braun": "Milwaukee Brewers" },
2435
+ },
2436
+ };
2437
+ // First season of each franchise (wherever it started). Wrong year choices are always 8+ years away, so
2438
+ // franchises with two possible "start" years (a league switch, a renamed club) can't make a wrong answer right.
2439
+ const TEAM_FIRST_SEASON = {
2440
+ nfl: { "Buffalo Bills": 1960, "Miami Dolphins": 1966, "New England Patriots": 1960, "New York Jets": 1960, "Baltimore Ravens": 1996,
2441
+ "Cincinnati Bengals": 1968, "Cleveland Browns": 1946, "Pittsburgh Steelers": 1933, "Houston Texans": 2002, "Indianapolis Colts": 1953,
2442
+ "Jacksonville Jaguars": 1995, "Tennessee Titans": 1960, "Denver Broncos": 1960, "Kansas City Chiefs": 1960, "Las Vegas Raiders": 1960,
2443
+ "Los Angeles Chargers": 1960, "Dallas Cowboys": 1960, "New York Giants": 1925, "Philadelphia Eagles": 1933, "Washington Commanders": 1932,
2444
+ "Chicago Bears": 1920, "Detroit Lions": 1930, "Green Bay Packers": 1921, "Minnesota Vikings": 1961, "Atlanta Falcons": 1966,
2445
+ "Carolina Panthers": 1995, "New Orleans Saints": 1967, "Tampa Bay Buccaneers": 1976, "Arizona Cardinals": 1920, "San Francisco 49ers": 1946,
2446
+ "Seattle Seahawks": 1976, "Los Angeles Rams": 1937 },
2447
+ nba: { "Boston Celtics": 1946, "Brooklyn Nets": 1967, "New York Knicks": 1946, "Philadelphia 76ers": 1946, "Toronto Raptors": 1995,
2448
+ "Chicago Bulls": 1966, "Cleveland Cavaliers": 1970, "Detroit Pistons": 1941, "Indiana Pacers": 1967, "Milwaukee Bucks": 1968,
2449
+ "Atlanta Hawks": 1946, "Charlotte Hornets": 1988, "Miami Heat": 1988, "Orlando Magic": 1989, "Washington Wizards": 1961,
2450
+ "Denver Nuggets": 1967, "Minnesota Timberwolves": 1989, "Oklahoma City Thunder": 1967, "Portland Trail Blazers": 1970, "Utah Jazz": 1974,
2451
+ "Golden State Warriors": 1946, "Los Angeles Clippers": 1970, "Los Angeles Lakers": 1947, "Phoenix Suns": 1968, "Sacramento Kings": 1945,
2452
+ "Dallas Mavericks": 1980, "Houston Rockets": 1967, "Memphis Grizzlies": 1995, "New Orleans Pelicans": 2002, "San Antonio Spurs": 1967 },
2453
+ mlb: { "Baltimore Orioles": 1901, "Boston Red Sox": 1901, "New York Yankees": 1903, "Tampa Bay Rays": 1998, "Toronto Blue Jays": 1977,
2454
+ "Chicago White Sox": 1901, "Cleveland Guardians": 1901, "Detroit Tigers": 1901, "Kansas City Royals": 1969, "Minnesota Twins": 1901,
2455
+ "Houston Astros": 1962, "Los Angeles Angels": 1961, "Athletics": 1901, "Seattle Mariners": 1977, "Texas Rangers": 1961,
2456
+ "Atlanta Braves": 1876, "Miami Marlins": 1993, "New York Mets": 1962, "Philadelphia Phillies": 1883, "Washington Nationals": 1969,
2457
+ "Chicago Cubs": 1876, "Cincinnati Reds": 1882, "Milwaukee Brewers": 1969, "Pittsburgh Pirates": 1882, "St. Louis Cardinals": 1882,
2458
+ "Arizona Diamondbacks": 1998, "Colorado Rockies": 1993, "Los Angeles Dodgers": 1884, "San Diego Padres": 1969, "San Francisco Giants": 1883 },
2459
+ };
2460
+ const NBA_EAST = ["Atlantic", "Central", "Southeast"];
2461
+ const conferenceOf = (league, div) => (league === "nba" ? (NBA_EAST.includes(div) ? "East" : "West") : div.split(" ")[0]);
2462
+ // Turns one team's facts into a quiz at the chosen level ("" mixes all three):
2463
+ // easy: its division, its best-known legend, a division rival and its home field, each against choices from the other conference
2464
+ // medium: the same facts against close choices (same conference), plus its second legend
2465
+ // hard: its first season, where it used to play, the odd one out of its division, and stars against same-conference stars
2466
+ function teamQuestions(league, teamName, level = "") {
2467
+ const L = TEAM_FACTS[league], teams = L.teams, t = teams.find((x) => x[0] === teamName);
2468
+ const [name, div, venue, stars, oldCity] = t;
2469
+ const conf = conferenceOf(league, div);
2470
+ const pick = (list, n) => shuffle(list.slice()).slice(0, n);
2471
+ const sameConf = (x) => conferenceOf(league, x[1]) === conf, otherConf = (x) => !sameConf(x);
2472
+ const teamOf = (n) => teams.find((x) => x[0] === n);
2473
+ const qs = [];
2474
+ const add = (lv, q, right, wrong) => { if (wrong.length >= 3) qs.push({ lv, q, right, topic: name, answers: shuffle([right, ...wrong.slice(0, 3)]) }); };
2475
+ // stars that only ever played for some other team (so they can't be right by accident)
2476
+ const otherStars = (filter) => Object.entries(L.oneTeam)
2477
+ .filter(([p, team]) => team !== name && !stars.includes(p) && filter(teamOf(team))).map(([p]) => p);
2478
+ const rivals = teams.filter((x) => x[1] === div && x[0] !== name);
2479
+ const divisions = [...new Set(teams.map((x) => x[1]))].filter((d) => d !== div);
2480
+ const venues = (filter) => [...new Set(teams.filter((x) => x[2] && x[2] !== venue && filter(x)).map((x) => x[2]))];
2481
+
2482
+ // easy
2483
+ add("e", `Which division do the ${name} play in?`, div, pick(divisions.filter((d) => conferenceOf(league, d) !== conf), 3));
2484
+ add("e", `Which of these players is a ${name} legend?`, stars[0], pick(otherStars(otherConf), 3));
2485
+ add("e", `Which team is in the same division as the ${name}?`, pick(rivals, 1)[0][0], pick(teams.filter(otherConf), 3).map((x) => x[0]));
2486
+ if (venue) add("e", `Which team plays its home games at ${venue}?`, name, pick(teams.filter((x) => otherConf(x) && x[2] !== venue), 3).map((x) => x[0]));
2487
+ // medium
2488
+ add("m", `Which division do the ${name} play in?`, div, pick(divisions.filter((d) => conferenceOf(league, d) === conf), 3).concat(pick(divisions, 3)).filter((d, i, all) => all.indexOf(d) === i));
2489
+ add("m", `Which of these players is a ${name} legend?`, stars[1], pick(otherStars(() => true), 3));
2490
+ if (venue) add("m", `What is the ${name}' home ${L.venue}?`, venue, pick(venues(() => true), 3));
2491
+ add("m", `Which team is in the same division as the ${name}?`, pick(rivals, 1)[0][0], pick(teams.filter((x) => sameConf(x) && x[1] !== div), 3).map((x) => x[0]));
2492
+ // hard
2493
+ const year = TEAM_FIRST_SEASON[league][name];
2494
+ if (year) {
2495
+ const years = [...new Set(Object.values(TEAM_FIRST_SEASON[league]))].filter((y) => Math.abs(y - year) >= 8);
2496
+ const wrong = [];
2497
+ for (const y of shuffle(years)) if (wrong.every((w) => Math.abs(w - y) >= 4) && wrong.length < 3) wrong.push(y);
2498
+ add("h", `In what year did the ${name} franchise play its first season?`, String(year), wrong.map(String));
2499
+ }
2500
+ if (oldCity) {
2501
+ const avoid = [oldCity, ...((L.oldHomes || {})[name] || [])];
2502
+ const cities = [...new Set(teams.map((x) => x[4]).filter(Boolean).concat(["Kansas City", "Seattle", "Montreal", "Oakland", "St. Louis", "Baltimore", "San Diego"]))]
2503
+ .filter((c) => !avoid.includes(c) && !name.startsWith(c));
2504
+ add("h", `The ${name} franchise used to play in which city?`, oldCity, pick(cities, 3));
2505
+ }
2506
+ const outsider = pick(teams.filter((x) => sameConf(x) && x[1] !== div), 1)[0];
2507
+ if (rivals.length >= 3) add("h", `Which of these teams is NOT in the same division as the ${name}?`, outsider[0], pick(rivals, 3).map((x) => x[0]));
2508
+ add("h", `Which of these players is a ${name} legend?`, stars[1], pick(otherStars(sameConf), 3));
2509
+ if (venue) add("h", `What is the ${name}' home ${L.venue}?`, venue, pick(venues(sameConf), 3));
2510
+
2511
+ // plus any regular league question that's about this team ("Steel Curtain" for the Steelers), at its own level
2512
+ const words = name.split(" "), two = /^(Sox|Jays|Blazers)$/.test(words.at(-1));
2513
+ const nick = words.slice(two ? -2 : -1).join(" ");
2514
+ const about = new RegExp(`\\b${nick.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`);
2515
+ for (const [l, , q, right, ...wrong] of TRIVIA_LEAGUES[league]) {
2516
+ if ((about.test(q) || about.test(right)) && !(venue && q.includes(venue))) // its home field is asked about already
2517
+ qs.push({ lv: l, q, right, topic: name, answers: shuffle([right, ...wrong]) });
2518
+ }
2519
+ const lv = level ? level[0] : "";
2520
+ let out = qs.filter((q) => !lv || q.lv === lv);
2521
+ if (!lv) out = shuffle(out).filter((q, i, all) => all.findIndex((o) => o.q === q.q) === i); // "Any": each kind of question once
2522
+ return shuffle(out).slice(0, TRIVIA_COUNT);
2523
+ }
2524
+
2525
+ // Puzzle sites: "embed" ones play inside the page; the rest refuse to be framed and open in a new tab
2526
+ const TRIVIA_SITES = [
2527
+ { id: "globle", name: "Globle", icon: "🌐", url: "https://globle-game.com/", desc: "Find the mystery country on the globe", embed: true },
2528
+ { id: "grid-football", name: "Immaculate Grid: Football", icon: "🏈", url: "https://www.sports-reference.com/immaculate-grid/football/", desc: "Name players who fit the row and column" },
2529
+ { id: "grid-baseball", name: "Immaculate Grid: Baseball", icon: "⚾", url: "https://www.sports-reference.com/immaculate-grid/", desc: "The baseball version" },
2530
+ { id: "krillion", name: "Krillion", icon: "🦐", url: "https://krillion.io/", desc: "Daily puzzle" },
2531
+ { id: "wordle", name: "Wordle", icon: "🟨", url: "https://www.nytimes.com/games/wordle/index.html", desc: "The daily five-letter word" },
2532
+ { id: "connections", name: "Connections (NYT)", icon: "🟪", url: "https://www.nytimes.com/games/connections", desc: "Sort 16 words into 4 groups" },
2533
+ ];
2534
+ const trivia = { topic: 0, level: "", kind: "all", team: "", qs: [], i: 0, score: 0, right: 0, streak: 0, best: 0, timer: 0, ends: 0, locked: true, token: null, started: false };
2535
+
2536
+ const triviaBestKey = () => (TRIVIA_LEAGUES[trivia.topic] && trivia.team ? `${trivia.topic}-team-${trivia.team}-${trivia.level}`
2537
+ : `${trivia.topic}-${trivia.level}` + (TRIVIA_LEAGUES[trivia.topic] ? `-${trivia.kind}` : ""));
2538
+ function renderTriviaChoices() {
2539
+ const tab = (label, val, on, kind) => `<button class="trivia-opt" role="tab" type="button" data-${kind}="${val}" aria-selected="${on}">${escapeHtml(label)}</button>`;
2540
+ $("trivia-cats").innerHTML = TRIVIA_TOPICS.map(([l, v]) => tab(l, v, v === trivia.topic, "topic")).join("");
2541
+ $("trivia-diff").innerHTML = TRIVIA_LEVELS.map(([l, v]) => tab(l, v, v === trivia.level, "level")).join("");
2542
+ $("trivia-kind").innerHTML = TRIVIA_KINDS.map(([l, v]) => tab(l, v, v === trivia.kind, "kind")).join("");
2543
+ const league = TRIVIA_LEAGUES[trivia.topic] ? trivia.topic : null;
2544
+ $("trivia-team-row").hidden = !league;
2545
+ if (league && $("trivia-team").dataset.league !== league) {
2546
+ $("trivia-team").dataset.league = league;
2547
+ $("trivia-team").innerHTML = `<option value="">All teams</option>` + TEAM_FACTS[league].teams.map((t) => t[0]).sort()
2548
+ .map((n) => `<option value="${escapeHtml(n)}">${escapeHtml(n)}</option>`).join("");
2549
+ }
2550
+ if (league) $("trivia-team").value = trivia.team;
2551
+ $("trivia-kind-row").hidden = !league || !!trivia.team;
2552
+ const best = store.get(TRIVIA_BEST_KEY, {})[triviaBestKey()];
2553
+ $("trivia-best").textContent = best ? `Your best here: ${best.toLocaleString()} points` : "";
2554
+ }
2555
+ function renderTriviaSites() {
2556
+ // the ones that play here first
2557
+ $("trivia-sites").innerHTML = [...TRIVIA_SITES].sort((a, b) => !!b.embed - !!a.embed).map((s) => `<button class="trivia-site" type="button" data-site="${s.id}">` +
2558
+ `<span class="trivia-site-art"><img src="logos/trivia-${s.id}.webp" alt="" loading="lazy" decoding="async" onerror="this.remove()"></span>` +
2559
+ `<span class="trivia-site-text"><b>${escapeHtml(s.name)}</b><small>${escapeHtml(s.desc)}</small></span>` +
2560
+ `<span class="trivia-site-how">${s.embed ? "Play" : "New tab ↗"}</span></button>`).join("");
2561
+ }
2562
+ function openTriviaSite(site) {
2563
+ if (!site.embed) { window.open(site.url, "_blank", "noopener"); return; }
2564
+ stopTriviaTimer();
2565
+ $("trivia-home").hidden = true;
2566
+ $("trivia-viewer").hidden = false;
2567
+ $("trivia-site-name").textContent = site.name;
2568
+ $("trivia-frame").src = site.url;
2569
+ track(`Trivia site: ${site.name}`);
2570
+ }
2571
+ function closeTriviaSite() {
2572
+ if ($("trivia-viewer").hidden) return;
2573
+ $("trivia-frame").src = "about:blank";
2574
+ $("trivia-viewer").hidden = true;
2575
+ $("trivia-home").hidden = false;
2576
+ }
2577
+
2578
+ const decode = (s) => { try { return decodeURIComponent(s); } catch { return s; } };
2579
+ const shuffle = (a) => { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; };
2580
+ const fromSet = (set, topic) => shuffle(set.slice()).slice(0, TRIVIA_COUNT).map(([q, right, ...wrong]) =>
2581
+ ({ q, right, topic, answers: shuffle([right, ...wrong]) }));
2582
+ async function triviaQuestions() {
2583
+ if (TRIVIA_LEAGUES[trivia.topic] && trivia.team) return teamQuestions(trivia.topic, trivia.team, trivia.level);
2584
+ if (TRIVIA_LEAGUES[trivia.topic]) {
2585
+ const lv = trivia.level ? trivia.level[0] : "", kind = { players: "p", teams: "t" }[trivia.kind];
2586
+ const pool = TRIVIA_LEAGUES[trivia.topic].filter(([l, k]) => (!lv || l === lv) && (!kind || k === kind)).map((q) => q.slice(2));
2587
+ return fromSet(pool, trivia.topic.toUpperCase() + (kind === "p" ? " players" : ""));
2588
+ }
2589
+ const get = async (url) => (await fetch(url, { signal: AbortSignal.timeout(8000) })).json();
1909
2590
  try {
1910
- const screen = useScreen ? await navigator.mediaDevices.getDisplayMedia({ video: { frameRate: 30 }, audio: true }) : null;
1911
- const cam = useCam || useMic ? await navigator.mediaDevices.getUserMedia({ video: useCam ? { width: 640, height: 360 } : false, audio: useMic }) : null;
1912
- // one sound track: the screen's sound and the mic mixed together
1913
- live.audioCtx = new AudioContext();
1914
- const mix = live.audioCtx.createMediaStreamDestination();
1915
- for (const src of [screen, cam]) if (src?.getAudioTracks().length) live.audioCtx.createMediaStreamSource(new MediaStream(src.getAudioTracks())).connect(mix);
1916
- const mainVideo = screen ? screen.getVideoTracks() : cam ? cam.getVideoTracks() : [];
1917
- const screenOut = new MediaStream([...mainVideo, ...mix.stream.getAudioTracks()]);
1918
- const camOut = screen && cam?.getVideoTracks().length ? new MediaStream(cam.getVideoTracks()) : null;
1919
- live.streams = { screenOut, camOut, raw: [screen, cam].filter(Boolean) };
1920
- // preview what you're sending (muted, so no echo)
1921
- $("live-screen").srcObject = screenOut;
1922
- $("live-cam").srcObject = camOut;
1923
- $("live-cam").hidden = !camOut;
1924
- screen?.getVideoTracks()[0]?.addEventListener("ended", endLive); // "Stop sharing" in the browser bar
1925
- const db = (await getFirebase()).database();
1926
- await db.ref("live/viewers").remove();
1927
- db.ref("live/state").onDisconnect().remove();
1928
- db.ref("live/viewers").onDisconnect().remove();
1929
- await db.ref("live/state").set({ on: true, main: screenOut.id, cam: camOut ? camOut.id : null, ts: window.firebase.database.ServerValue.TIMESTAMP });
1930
- db.ref("live/viewers").on("child_added", (s) => connectViewer(db, s.key));
1931
- db.ref("live/viewers").on("child_removed", (s) => { live.peers.get(s.key)?.close(); live.peers.delete(s.key); updateViewerCount(); });
1932
- renderLive();
2591
+ if (!trivia.token) trivia.token = (await get("https://opentdb.com/api_token.php?command=request")).token;
2592
+ const url = () => `https://opentdb.com/api.php?amount=${TRIVIA_COUNT}&encode=url3986&token=${trivia.token}` +
2593
+ (trivia.topic ? `&category=${trivia.topic}` : "") + (trivia.level ? `&difficulty=${trivia.level}` : "");
2594
+ let d = await get(url());
2595
+ if (d.response_code === 4) { await get(`https://opentdb.com/api_token.php?command=reset&token=${trivia.token}`); d = await get(url()); } // seen them all: start over
2596
+ if (d.response_code === 5) { await new Promise((r) => setTimeout(r, 5200)); d = await get(url()); } // one request per 5s
2597
+ if (d.response_code !== 0 || !d.results?.length) throw new Error(`code ${d.response_code}`);
2598
+ return d.results.map((q) => ({
2599
+ q: decode(q.question), right: decode(q.correct_answer), topic: decode(q.category),
2600
+ answers: q.type === "boolean" ? ["True", "False"] : shuffle([q.correct_answer, ...q.incorrect_answers].map(decode)),
2601
+ }));
1933
2602
  } catch (err) {
1934
- console.warn(err);
1935
- live.streams?.raw.forEach((m) => m.getTracks().forEach((t) => t.stop()));
1936
- live.streams = null;
1937
- toast("Couldn't start the stream (screen, camera or mic was blocked).");
2603
+ console.warn("Trivia questions unavailable, using the built-in set:", err.message);
2604
+ return fromSet(TRIVIA_BACKUP, "Mixed");
1938
2605
  }
1939
2606
  }
1940
- function updateViewerCount() { $("live-viewers").textContent = live.streams ? `${live.peers.size} watching` : ""; }
1941
- async function connectViewer(db, id) {
1942
- if (!live.streams || live.peers.has(id)) return;
1943
- const pc = new RTCPeerConnection(ICE);
1944
- live.peers.set(id, pc);
1945
- updateViewerCount();
1946
- const { screenOut, camOut } = live.streams;
1947
- screenOut.getTracks().forEach((t) => pc.addTrack(t, screenOut));
1948
- camOut?.getTracks().forEach((t) => pc.addTrack(t, camOut));
1949
- const ref = db.ref(`live/viewers/${id}`);
1950
- pc.onicecandidate = (e) => { if (e.candidate) ref.child("oice").push(JSON.stringify(e.candidate)); };
1951
- pc.onconnectionstatechange = () => { if (["failed", "closed"].includes(pc.connectionState)) { live.peers.delete(id); updateViewerCount(); } };
1952
- const offer = await pc.createOffer();
1953
- await pc.setLocalDescription(offer);
1954
- await ref.child("offer").set({ type: offer.type, sdp: offer.sdp });
1955
- ref.child("answer").on("value", async (s) => { const a = s.val(); if (a && !pc.currentRemoteDescription) await pc.setRemoteDescription(a).catch(() => {}); });
1956
- ref.child("vice").on("child_added", (s) => { pc.addIceCandidate(JSON.parse(s.val())).catch(() => {}); });
1957
- }
1958
- async function endLive() {
1959
- const db = (await getFirebase())?.database();
1960
- if (db) { db.ref("live/viewers").off(); await db.ref("live/state").remove().catch(() => {}); await db.ref("live/viewers").remove().catch(() => {}); await db.ref("live/gifts").remove().catch(() => {}); }
1961
- live.peers.forEach((pc) => pc.close());
1962
- live.peers.clear();
1963
- live.streams?.raw.forEach((m) => m.getTracks().forEach((t) => t.stop()));
1964
- live.streams = null;
1965
- live.audioCtx?.close().catch(() => {});
1966
- live.audioCtx = null;
1967
- $("live-screen").srcObject = null; $("live-cam").srcObject = null; $("live-cam").hidden = true;
1968
- renderLive();
1969
- }
1970
-
1971
- // -- viewer side --
1972
- async function watchLive() {
1973
- if (!live.state || live.viewer) return;
1974
- const app = await getFirebase();
1975
- const user = chat.uid ? { uid: chat.uid } : await ensureUser(app);
1976
- const ref = app.database().ref(`live/viewers/${user.uid}`);
1977
- const pc = new RTCPeerConnection(ICE);
1978
- live.viewer = { pc, ref };
1979
- pc.ontrack = (e) => {
1980
- const stream = e.streams[0];
1981
- if (!stream) return;
1982
- const isCam = !!live.state?.cam && stream.id === live.state.cam;
1983
- const el = isCam ? $("live-cam") : $("live-screen");
1984
- if (el.srcObject !== stream) el.srcObject = stream;
1985
- if (isCam) { $("live-cam").hidden = false; return; }
1986
- // sound needs a tap first on some browsers: try with sound, else start muted and offer the button
1987
- el.muted = false;
1988
- el.play().catch(() => { el.muted = true; el.play().catch(() => {}); $("live-unmute").hidden = false; });
1989
- };
1990
- pc.onicecandidate = (e) => { if (e.candidate) ref.child("vice").push(JSON.stringify(e.candidate)); };
1991
- pc.onconnectionstatechange = () => {
1992
- if (pc.connectionState === "failed") { toast("Couldn't connect to the stream (your network may block it)."); stopWatching(); renderLive(); }
1993
- };
1994
- await ref.remove().catch(() => {});
1995
- ref.onDisconnect().remove();
1996
- await ref.set({ join: window.firebase.database.ServerValue.TIMESTAMP });
1997
- ref.child("offer").on("value", async (s) => {
1998
- const o = s.val();
1999
- if (!o || pc.currentRemoteDescription) return;
2000
- await pc.setRemoteDescription(o);
2001
- const ans = await pc.createAnswer();
2002
- await pc.setLocalDescription(ans);
2003
- await ref.child("answer").set({ type: ans.type, sdp: ans.sdp });
2607
+ function triviaScreen(which) {
2608
+ for (const id of ["setup", "play", "done"]) $(`trivia-${id}`).hidden = id !== which;
2609
+ }
2610
+ async function startTrivia() {
2611
+ trivia.daily = false;
2612
+ triviaScreen("play");
2613
+ Object.assign(trivia, { qs: [], i: 0, score: 0, right: 0, streak: 0, best: 0, locked: true });
2614
+ $("trivia-q").textContent = "Getting questions…";
2615
+ $("trivia-answers").innerHTML = "";
2616
+ $("trivia-note").textContent = "";
2617
+ $("trivia-count").textContent = $("trivia-topic").textContent = $("trivia-score").textContent = "";
2618
+ $("trivia-time").style.width = "100%";
2619
+ trivia.qs = await triviaQuestions();
2620
+ if ($("view-trivia").hidden) return; // left the page while loading
2621
+ showTriviaQuestion();
2622
+ }
2623
+ function showTriviaQuestion() {
2624
+ const q = trivia.qs[trivia.i];
2625
+ trivia.locked = false;
2626
+ $("trivia-count").textContent = `Question ${trivia.i + 1} of ${trivia.qs.length}`;
2627
+ $("trivia-topic").textContent = q.topic;
2628
+ $("trivia-score").textContent = `${trivia.score.toLocaleString()} pts${trivia.streak >= 2 ? ` · ${trivia.streak} in a row` : ""}`;
2629
+ $("trivia-q").textContent = q.q;
2630
+ $("trivia-answers").innerHTML = q.answers.map((a, i) =>
2631
+ `<button class="trivia-answer" type="button" data-i="${i}"><kbd>${i + 1}</kbd>${escapeHtml(a)}</button>`).join("");
2632
+ $("trivia-note").textContent = "";
2633
+ trivia.ends = Date.now() + TRIVIA_SECONDS * 1000;
2634
+ stopTriviaTimer();
2635
+ trivia.timer = setInterval(() => {
2636
+ const left = Math.max(0, trivia.ends - Date.now());
2637
+ $("trivia-time").style.width = `${(left / (TRIVIA_SECONDS * 1000)) * 100}%`;
2638
+ if (!left) answerTrivia(-1);
2639
+ }, 100);
2640
+ }
2641
+ function stopTriviaTimer() { clearInterval(trivia.timer); trivia.timer = 0; }
2642
+ function answerTrivia(i) {
2643
+ if (trivia.locked) return;
2644
+ trivia.locked = true;
2645
+ stopTriviaTimer();
2646
+ const q = trivia.qs[trivia.i], picked = q.answers[i], ok = picked === q.right;
2647
+ const left = Math.max(0, trivia.ends - Date.now()) / 1000;
2648
+ $("trivia-answers").querySelectorAll(".trivia-answer").forEach((b, j) => {
2649
+ b.disabled = true;
2650
+ if (q.answers[j] === q.right) b.classList.add("right");
2651
+ else if (j === i) b.classList.add("wrong");
2004
2652
  });
2005
- ref.child("oice").on("child_added", (s) => { pc.addIceCandidate(JSON.parse(s.val())).catch(() => {}); });
2006
- renderLive();
2007
- }
2008
- function stopWatching() {
2009
- if (!live.viewer) return;
2010
- const { pc, ref } = live.viewer;
2011
- ref.child("offer").off();
2012
- ref.child("oice").off();
2013
- ref.remove().catch(() => {});
2014
- pc.close();
2015
- live.viewer = null;
2016
- if (!live.streams) { $("live-screen").srcObject = null; $("live-cam").srcObject = null; $("live-cam").hidden = true; }
2017
- $("live-unmute").hidden = true;
2018
- }
2019
- function bindLive() {
2020
- $("live-go").addEventListener("click", goLive);
2021
- $("live-watch").addEventListener("click", watchLive);
2022
- $("live-unmute").addEventListener("click", () => { const v = $("live-screen"); v.muted = false; v.play().catch(() => {}); $("live-unmute").hidden = true; });
2023
- window.addEventListener("pagehide", () => { if (live.streams) endLive(); });
2024
- }
2025
-
2026
- // ---------- Live gifts (fake, free) ----------
2027
- // Viewers tap a gift; it pops up over the stream for everyone ("Bob sent a 🚀 Rocket!").
2028
- // One gift per person per minute (the database checks too), and pop-ups play one at a time.
2029
- const GIFTS = [
2030
- { id: "heart", emoji: "❤️", name: "Heart" }, { id: "rose", emoji: "🌹", name: "Rose" },
2031
- { id: "pizza", emoji: "🍕", name: "Pizza" }, { id: "diamond", emoji: "💎", name: "Diamond" },
2032
- { id: "rocket", emoji: "🚀", name: "Rocket" }, { id: "crown", emoji: "👑", name: "Crown" },
2033
- ];
2034
- const GIFT_GAP = 60000;
2035
- const gifts = { sentAt: store.get("rug-gift-sent", 0), queue: [], playing: false, ref: null, timer: null };
2036
- function renderGiftButtons() {
2037
- $("gift-btns").innerHTML = GIFTS.map((g) => `<button class="gift-btn" type="button" data-gift="${g.id}" title="Send a ${g.name}"><span>${g.emoji}</span>${g.name}</button>`).join("");
2038
- }
2039
- function updateGiftWait() {
2040
- const left = GIFT_GAP - (Date.now() - gifts.sentAt);
2041
- const waiting = left > 0;
2042
- $("gift-btns").querySelectorAll("button").forEach((b) => { b.disabled = waiting; });
2043
- $("gift-wait").textContent = waiting ? `Next gift in ${Math.ceil(left / 1000)}s` : "";
2044
- }
2045
- async function sendGift(id) {
2046
- const g = GIFTS.find((x) => x.id === id);
2047
- if (!g || Date.now() - gifts.sentAt < GIFT_GAP || !live.state) return;
2048
- if (chat.banned) { toast("You can't send gifts right now."); return; }
2049
- const n = chat.admin ? { name: ADMIN_NAME } : cleanName($("chat-name").value);
2050
- if (n.error) { toast("Type a nickname in the chat box first, so everyone knows who sent it."); $("chat-name").focus(); return; }
2653
+ if (ok) {
2654
+ trivia.streak++;
2655
+ trivia.right++;
2656
+ const pts = 100 + Math.round((left / TRIVIA_SECONDS) * 100) + Math.min(50, (trivia.streak - 1) * 10); // speed + streak bonus
2657
+ trivia.score += pts;
2658
+ trivia.best = Math.max(trivia.best, trivia.streak);
2659
+ $("trivia-note").textContent = `Right! +${pts}`;
2660
+ } else {
2661
+ trivia.streak = 0;
2662
+ $("trivia-note").textContent = i < 0 ? `Time's up! It was ${q.right}.` : `Not quite. It was ${q.right}.`;
2663
+ }
2664
+ $("trivia-score").textContent = `${trivia.score.toLocaleString()} pts`;
2665
+ setTimeout(() => {
2666
+ if ($("view-trivia").hidden) return;
2667
+ trivia.i++;
2668
+ if (trivia.i < trivia.qs.length) showTriviaQuestion(); else finishTrivia();
2669
+ }, ok ? 1100 : 1900);
2670
+ }
2671
+ function finishTrivia() {
2672
+ triviaScreen("done");
2673
+ if (trivia.daily) {
2674
+ trivia.daily = false;
2675
+ submitDaily();
2676
+ $("trivia-final").textContent = `${trivia.score.toLocaleString()} points`;
2677
+ $("trivia-summary").textContent = `${trivia.right} of 10 right in today's challenge. Check the leaderboard above.`;
2678
+ $("trivia-daily").hidden = false;
2679
+ $("trivia-again").textContent = "Play a quick quiz";
2680
+ renderDaily();
2681
+ return;
2682
+ }
2683
+ $("trivia-again").textContent = "Play again";
2684
+ const key = triviaBestKey(), bests = store.get(TRIVIA_BEST_KEY, {});
2685
+ const record = trivia.score > (bests[key] || 0);
2686
+ if (record) { bests[key] = trivia.score; store.set(TRIVIA_BEST_KEY, bests); }
2687
+ $("trivia-final").textContent = `${trivia.score.toLocaleString()} points`;
2688
+ $("trivia-summary").textContent = `${trivia.right} of ${trivia.qs.length} right` +
2689
+ (trivia.best >= 3 ? `, best streak ${trivia.best}` : "") + (record && trivia.score ? ". New personal best!" : ".");
2690
+ }
2691
+ function bindTrivia() {
2692
+ $("daily-start").addEventListener("click", startDaily);
2693
+ $("daily-name").addEventListener("keydown", (e) => { if (e.key === "Enter") startDaily(); });
2694
+ renderDaily();
2695
+ watchDailyBoard();
2696
+ renderTriviaChoices();
2697
+ renderTriviaSites();
2698
+ $("trivia-cats").addEventListener("click", (e) => { const b = e.target.closest("[data-topic]"); if (b) { const v = b.dataset.topic; trivia.topic = /^\d+$/.test(v) ? Number(v) : v; trivia.team = ""; renderTriviaChoices(); } });
2699
+ $("trivia-diff").addEventListener("click", (e) => { const b = e.target.closest("[data-level]"); if (b) { trivia.level = b.dataset.level; renderTriviaChoices(); } });
2700
+ $("trivia-team").addEventListener("change", (e) => { trivia.team = e.target.value; renderTriviaChoices(); });
2701
+ $("trivia-kind").addEventListener("click", (e) => { const b = e.target.closest("[data-kind]"); if (b) { trivia.kind = b.dataset.kind; renderTriviaChoices(); } });
2702
+ $("trivia-start").addEventListener("click", startTrivia);
2703
+ $("trivia-again").addEventListener("click", startTrivia);
2704
+ $("trivia-change").addEventListener("click", () => { renderTriviaChoices(); triviaScreen("setup"); });
2705
+ $("trivia-answers").addEventListener("click", (e) => { const b = e.target.closest("[data-i]"); if (b) answerTrivia(Number(b.dataset.i)); });
2706
+ $("trivia-sites").addEventListener("click", (e) => { const b = e.target.closest("[data-site]"); if (b) openTriviaSite(TRIVIA_SITES.find((s) => s.id === b.dataset.site)); });
2707
+ $("trivia-back").addEventListener("click", closeTriviaSite);
2708
+ $("trivia-full").addEventListener("click", () => { const f = $("trivia-frame"); (f.requestFullscreen || f.webkitRequestFullscreen)?.call(f); });
2709
+ // number keys 1-4 answer while a question is up
2710
+ document.addEventListener("keydown", (e) => {
2711
+ if ($("view-trivia").hidden || $("trivia-play").hidden || trivia.locked || e.ctrlKey || e.metaKey || e.altKey) return;
2712
+ if (/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName || "")) return;
2713
+ const n = Number(e.key);
2714
+ if (n >= 1 && n <= trivia.qs[trivia.i].answers.length) { e.preventDefault(); answerTrivia(n - 1); }
2715
+ });
2716
+ }
2717
+
2718
+ // ---------- Daily trivia challenge: the same 10 questions for everyone today, one try, a leaderboard ----------
2719
+ // Questions come from the built-in sets, picked and ordered by today's date, so every visitor gets the same quiz.
2720
+ // Scores go to daily/<date>/<player id> (one per person per day, checked by the database).
2721
+ const DAILY_KEY = "rug-daily";
2722
+ const dailyDate = (d = new Date()) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
2723
+ function seededRandom(text) { // the same text always gives the same sequence of numbers
2724
+ let h = 1779033703 ^ text.length;
2725
+ for (let i = 0; i < text.length; i++) { h = Math.imul(h ^ text.charCodeAt(i), 3432918353); h = (h << 13) | (h >>> 19); }
2726
+ return () => { h = Math.imul(h ^ (h >>> 16), 2246822507); h = Math.imul(h ^ (h >>> 13), 3266489909); h ^= h >>> 16; return (h >>> 0) / 4294967296; };
2727
+ }
2728
+ function dailyQuestions() {
2729
+ const rnd = seededRandom("richardwho daily " + dailyDate());
2730
+ const mix = (a) => { a = a.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; };
2731
+ // a spread: 3 NFL, 3 NBA, 2 MLB, 2 general knowledge, easy to hard
2732
+ const fromLeague = (lg, n) => mix(TRIVIA_LEAGUES[lg]).slice(0, n).map(([, , q, right, ...wrong]) => ({ q, right, wrong, topic: lg.toUpperCase() }));
2733
+ const general = mix(TRIVIA_BACKUP).slice(0, 2).map(([q, right, ...wrong]) => ({ q, right, wrong, topic: "General" }));
2734
+ return mix([...fromLeague("nfl", 3), ...fromLeague("nba", 3), ...fromLeague("mlb", 2), ...general])
2735
+ .map(({ q, right, wrong, topic }) => ({ q, right, topic: `Daily · ${topic}`, answers: mix([right, ...wrong]) }));
2736
+ }
2737
+ const daily = { board: [], ref: null };
2738
+ function dailyMine() { const d = store.get(DAILY_KEY, null); return d && d.date === dailyDate() ? d : null; }
2739
+ async function startDaily() {
2740
+ if (dailyMine()) return renderDaily();
2741
+ const name = ($("daily-name").value || "").replace(/\s+/g, " ").trim();
2742
+ if (!name) { $("daily-note").textContent = "Pick a name for the leaderboard first."; $("daily-name").focus(); return; }
2743
+ if ([...name].length > 16) { $("daily-note").textContent = "Names can be up to 16 characters."; return; }
2744
+ if (/^ *richard *$/i.test(name)) { $("daily-note").textContent = "That name is taken."; return; }
2745
+ store.set("rug-chat-name", store.get("rug-chat-name", "") || name); // same name as chat, if chat doesn't have one yet
2746
+ store.set(DAILY_KEY, { date: dailyDate(), name: maskSlurs(name), started: true }); // one try: starting counts
2747
+ trivia.daily = true;
2748
+ $("trivia-daily").hidden = true;
2749
+ triviaScreen("play");
2750
+ Object.assign(trivia, { qs: dailyQuestions(), i: 0, score: 0, right: 0, streak: 0, best: 0, locked: true });
2751
+ showTriviaQuestion();
2752
+ }
2753
+ async function submitDaily() {
2754
+ const mine = { ...store.get(DAILY_KEY, {}), score: trivia.score, right: trivia.right, finished: true };
2755
+ store.set(DAILY_KEY, mine);
2051
2756
  const app = await getFirebase();
2052
- if (!app || !chat.uid) return;
2053
- const db = app.database(), TS = window.firebase.database.ServerValue.TIMESTAMP;
2757
+ if (!app) return;
2054
2758
  try {
2055
- await db.ref().update({
2056
- [`live/gifts/${db.ref("live/gifts").push().key}`]: { name: n.name, gift: g.id, uid: chat.uid, ts: TS },
2057
- [`live/giftLast/${chat.uid}`]: TS,
2759
+ const user = await signedInUser(app);
2760
+ await app.database().ref(`daily/${mine.date}/${user.uid}`).set({
2761
+ name: mine.name, score: mine.score, right: mine.right, ts: window.firebase.database.ServerValue.TIMESTAMP,
2058
2762
  });
2059
- gifts.sentAt = Date.now();
2060
- store.set("rug-gift-sent", gifts.sentAt);
2061
- updateGiftWait();
2763
+ } catch { /* already played today from this browser, or offline: the local score still shows */ }
2764
+ }
2765
+ async function watchDailyBoard() {
2766
+ const app = await getFirebase();
2767
+ if (!app) return;
2768
+ if (daily.ref) daily.ref.off();
2769
+ daily.ref = app.database().ref(`daily/${dailyDate()}`).orderByChild("score").limitToLast(10);
2770
+ daily.ref.on("value", (s) => {
2771
+ const rows = [];
2772
+ s.forEach((c) => { const v = c.val(); if (v && typeof v.name === "string") rows.push({ ...v, uid: c.key }); });
2773
+ daily.board = rows.sort((a, b) => b.score - a.score || a.ts - b.ts); // ties: whoever finished first
2774
+ daily.me = app.auth().currentUser?.uid;
2775
+ renderDaily();
2776
+ }, () => {});
2777
+ }
2778
+ function renderDaily() {
2779
+ const mine = dailyMine();
2780
+ $("daily-date").textContent = new Date().toLocaleDateString([], { weekday: "long", month: "long", day: "numeric" });
2781
+ $("daily-name-row").hidden = !!mine;
2782
+ $("daily-start").hidden = !!mine;
2783
+ if (!$("daily-name").value) $("daily-name").value = store.get("rug-chat-name", "");
2784
+ $("daily-status").textContent = !mine ? "10 questions, same for everyone, one try. Come back tomorrow for a new one."
2785
+ : mine.finished ? `You scored ${mine.score.toLocaleString()} (${mine.right}/10). New challenge tomorrow.`
2786
+ : "You started today's challenge but didn't finish it. New challenge tomorrow.";
2787
+ $("daily-board").innerHTML = daily.board.length
2788
+ ? daily.board.map((r, i) => `<li class="${r.uid === daily.me ? "me" : ""}"><span class="daily-rank">${i + 1}</span>` +
2789
+ `<span class="daily-who">${escapeHtml(maskSlurs(r.name))}</span><span class="daily-pts">${Number(r.score).toLocaleString()}</span></li>`).join("")
2790
+ : `<li class="daily-empty">No scores yet today. Be the first!</li>`;
2791
+ }
2792
+
2793
+ // ---------- First-visit tour: a few steps pointing at the side bar, shown once to new visitors ----------
2794
+ const TOUR_KEY = "rug-tour-done";
2795
+ const TOUR_STEPS = [
2796
+ [null, "Welcome to richardwho", "Hundreds of free games, nothing to install. Here's a quick tour (about 20 seconds)."],
2797
+ ["#home-search", "Search", "Start typing to find any game. Press / from anywhere to jump here."],
2798
+ [".rail-btn[data-nav=games]", "Games", "Every game, by category. There's a Game of the day and the most played games at the top."],
2799
+ [".rail-btn[data-nav=trivia]", "Trivia", "Quick quizzes, NFL, NBA and MLB team trivia, and a daily challenge with a leaderboard."],
2800
+ ["#soundboard-btn", "Soundboard", "Meme sounds and effects, one click away."],
2801
+ [".rail-btn[data-nav=ai]", "AI chat", "Ask anything: homework help, game ideas, or just questions."],
2802
+ [".rail-btn[data-nav=chat]", "Chat", "Talk with everyone on the site. Be nice, and you can post polls too."],
2803
+ ["#panic-btn", "Panic button", "Jumps straight to Google Classroom. The ` and ] keys do it too."],
2804
+ [".rail-btn[data-nav=settings]", "Settings", "Themes, the tab disguise, the panic page and more. You can replay this tour there."],
2805
+ ];
2806
+ const tour = { i: 0 };
2807
+ function showTour() {
2808
+ tour.i = 0;
2809
+ document.documentElement.classList.add("rail-peek");
2810
+ $("tour").hidden = false;
2811
+ tourStep();
2812
+ }
2813
+ function endTour() {
2814
+ $("tour").hidden = true;
2815
+ document.documentElement.classList.remove("rail-peek");
2816
+ store.set(TOUR_KEY, true);
2817
+ }
2818
+ function tourStep() {
2819
+ const [sel, title, text] = TOUR_STEPS[tour.i];
2820
+ const target = sel && document.querySelector(sel);
2821
+ const r = target && target.offsetParent !== null ? target.getBoundingClientRect() : null;
2822
+ const spot = $("tour-spot"), card = $("tour-card");
2823
+ spot.hidden = !r;
2824
+ if (r) Object.assign(spot.style, { left: `${r.left - 6}px`, top: `${r.top - 6}px`, width: `${r.width + 12}px`, height: `${r.height + 12}px` });
2825
+ $("tour-step").textContent = `${tour.i + 1} of ${TOUR_STEPS.length}`;
2826
+ $("tour-title").textContent = title;
2827
+ $("tour-text").textContent = text;
2828
+ $("tour-back").hidden = tour.i === 0;
2829
+ $("tour-next").textContent = tour.i === TOUR_STEPS.length - 1 ? "Done" : "Next";
2830
+ // put the card beside the highlighted thing (to its right, or above it on phones), or in the middle
2831
+ const w = card.offsetWidth || 320, h = card.offsetHeight || 170;
2832
+ let x = innerWidth / 2 - w / 2, y = innerHeight / 2 - h / 2;
2833
+ if (r) {
2834
+ if (r.right + 20 + w < innerWidth) { x = r.right + 20; y = r.top + r.height / 2 - h / 2; }
2835
+ else { x = r.left + r.width / 2 - w / 2; y = r.top - h - 20 > 0 ? r.top - h - 20 : r.bottom + 20; }
2836
+ }
2837
+ card.style.left = `${Math.max(12, Math.min(innerWidth - w - 12, x))}px`;
2838
+ card.style.top = `${Math.max(12, Math.min(innerHeight - h - 12, y))}px`;
2839
+ $("tour-next").focus();
2840
+ }
2841
+ function bindTour() {
2842
+ $("tour-next").addEventListener("click", () => { if (++tour.i >= TOUR_STEPS.length) endTour(); else tourStep(); });
2843
+ $("tour-back").addEventListener("click", () => { tour.i = Math.max(0, tour.i - 1); tourStep(); });
2844
+ $("tour-skip").addEventListener("click", endTour);
2845
+ $("set-tour").addEventListener("click", () => { go("home"); setTimeout(showTour, 400); });
2846
+ document.addEventListener("keydown", (e) => { if (!$("tour").hidden && e.key === "Escape") endTour(); });
2847
+ addEventListener("resize", () => { if (!$("tour").hidden) tourStep(); });
2848
+ }
2849
+
2850
+ // ---------- AI chat ----------
2851
+ // One chatbot backed by several free AI services. It tries them in order (Gemini, Groq, OpenRouter,
2852
+ // Mistral); when one is out of free messages, down or missing a key, it moves to the next.
2853
+ // Keys go in config.js (ai: { gemini, groq, openrouter, mistral }). Models are picked from each service's
2854
+ // own current list, so renamed models don't break it. The conversation is kept in this browser only.
2855
+ const AI_KEY = "rug-ai-chat";
2856
+ const AI_SYSTEM = "You are the helpful AI on richardwho, a games site used by students. Be friendly, clear and fairly short. " +
2857
+ "Help with homework by explaining how to solve things, not just giving answers. Keep everything appropriate for school: " +
2858
+ "no sexual content, no graphic violence, nothing hateful, nothing dangerous or illegal. Use Markdown for lists and code. " +
2859
+ "Never use LaTeX; write math in plain text (like CO2, x^2, 6CO2 + 6H2O -> C6H12O6 + 6O2).";
2860
+ const ai = { busy: false, models: {}, chats: [], currentId: null, pendingImg: null };
2861
+ const aiKeys = () => CFG.ai || {};
2862
+ const AI_SERVICES = [
2863
+ { id: "gemini", name: "Gemini",
2864
+ async pickModel(key) {
2865
+ const r = await fetch("https://generativelanguage.googleapis.com/v1beta/models?pageSize=200", { headers: { "x-goog-api-key": key } });
2866
+ const list = (await r.json()).models || [];
2867
+ const ok = list.filter((m) => (m.supportedGenerationMethods || []).includes("generateContent") && /gemini/.test(m.name) && !/(image|tts|audio|embedding|live|preview-tts|robotics)/.test(m.name));
2868
+ // newest first, full flash before lite; the newest often has no free messages, so ask() walks down the list
2869
+ const rank = (m) => (/flash/.test(m.name) ? 0 : 2) + (/lite/.test(m.name) ? 1 : 0);
2870
+ const names = ok.filter((m) => !/preview|latest|omni/.test(m.name))
2871
+ .sort((a, b) => rank(a) - rank(b) || b.name.localeCompare(a.name, undefined, { numeric: true })).map((m) => m.name);
2872
+ // the model that worked last time goes first, so only the very first visit has to search
2873
+ let good = null;
2874
+ try { good = localStorage.getItem("rug-ai-gemini"); } catch {}
2875
+ // the model set in config.js first, then the one that worked last time, then the rest
2876
+ for (const want of [good, aiKeys().geminiModel && "models/" + aiKeys().geminiModel]) {
2877
+ if (want && names.includes(want)) names.unshift(...names.splice(names.indexOf(want), 1));
2878
+ }
2879
+ return names.length ? names : null;
2880
+ },
2881
+ async ask(key, models, msgs) {
2882
+ let good = null;
2883
+ try { good = localStorage.getItem("rug-ai-gemini"); } catch {}
2884
+ for (const model of [...models]) {
2885
+ // an untested model gets 8s (overloaded ones just hang); a known-good one gets time for long answers
2886
+ const r = await fetch(`https://generativelanguage.googleapis.com/v1beta/${model}:generateContent`, {
2887
+ method: "POST", headers: { "Content-Type": "application/json", "x-goog-api-key": key }, signal: AbortSignal.timeout(model === good ? 45000 : 8000),
2888
+ body: JSON.stringify({ systemInstruction: { parts: [{ text: AI_SYSTEM }] },
2889
+ contents: msgs.map((m) => ({ role: m.role === "assistant" ? "model" : "user", parts: [{ text: m.text },
2890
+ ...(m.img ? [{ inline_data: { mime_type: m.img.slice(5, m.img.indexOf(";")), data: m.img.slice(m.img.indexOf(",") + 1) } }] : [])] })) }),
2891
+ }).catch(() => ({ ok: false, status: "timeout" }));
2892
+ if (!r.ok) { models.splice(models.indexOf(model), 1); continue; } // out of free messages for this model: next one
2893
+ try { localStorage.setItem("rug-ai-gemini", model); } catch {}
2894
+ const d = await r.json();
2895
+ return (d.candidates?.[0]?.content?.parts || []).map((p) => p.text || "").join("").trim();
2896
+ }
2897
+ throw new Error("gemini: no model with free messages left");
2898
+ } },
2899
+ { id: "groq", name: "Groq", base: "https://api.groq.com/openai/v1",
2900
+ prefer: [/llama.*70b/, /llama/, /qwen/, /gpt-oss/], avoid: /(whisper|guard|tts|vision|embed)/ },
2901
+ { id: "openrouter", name: "OpenRouter", base: "https://openrouter.ai/api/v1",
2902
+ prefer: [/llama/, /gemma/, /qwen/, /mistral/, /nemotron.*super/, /./], avoid: /(content-safety|code|coder|guard|vision|vl|embed)/, freeOnly: true },
2903
+ { id: "mistral", name: "Mistral", base: "https://api.mistral.ai/v1",
2904
+ prefer: [/mistral-small-latest/, /mistral-medium-latest/, /mistral-large-latest/, /mistral/], avoid: /(embed|ocr|moderation|codestral|pixtral)/ },
2905
+ ];
2906
+ // Groq, OpenRouter and Mistral all speak the same (OpenAI-style) format
2907
+ const openAiStyle = {
2908
+ async pickModel(key, svc) {
2909
+ const r = await fetch(`${svc.base}/models`, { headers: { Authorization: `Bearer ${key}` } });
2910
+ let ids = ((await r.json()).data || []).map((m) => m.id).filter((id) => !svc.avoid.test(id));
2911
+ if (svc.freeOnly) ids = ids.filter((id) => id.endsWith(":free"));
2912
+ for (const re of svc.prefer) { const hit = ids.find((id) => re.test(id)); if (hit) return hit; }
2913
+ return ids[0];
2914
+ },
2915
+ async ask(key, model, msgs, svc) {
2916
+ const r = await fetch(`${svc.base}/chat/completions`, {
2917
+ method: "POST",
2918
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}`, ...(svc.id === "openrouter" ? { "X-Title": "richardwho" } : {}) },
2919
+ body: JSON.stringify({ model, messages: [{ role: "system", content: AI_SYSTEM }, ...msgs.map((m) => ({ role: m.role, content: m.img ? m.text + "\n\n(The user attached a picture, but you can't see pictures. Say so if it matters.)" : m.text }))], max_tokens: 1200 }),
2920
+ });
2921
+ if (!r.ok) throw new Error(`${svc.id} ${r.status}`);
2922
+ const d = await r.json();
2923
+ return (d.choices?.[0]?.message?.content || "").trim();
2924
+ },
2925
+ };
2926
+ function aiReady() { return AI_SERVICES.some((s) => aiKeys()[s.id]); }
2927
+ async function askAi(msgs) {
2928
+ const order = msgs.some((m) => m.img) ? [...AI_SERVICES].sort((x) => (x.id === "gemini" ? -1 : 0)) : AI_SERVICES;
2929
+ for (const svc of order) {
2930
+ const key = aiKeys()[svc.id];
2931
+ if (!key) continue;
2932
+ const impl = svc.ask ? svc : openAiStyle;
2933
+ try {
2934
+ ai.models[svc.id] ||= (aiKeys().models || {})[svc.id] || await impl.pickModel(key, svc);
2935
+ if (!ai.models[svc.id]) throw new Error("no model");
2936
+ const text = await impl.ask(key, ai.models[svc.id], msgs, svc);
2937
+ if (text) return { text, by: svc.name };
2938
+ } catch (err) {
2939
+ console.warn("AI service skipped:", svc.name, err.message); // out of free messages, down, or bad key: try the next
2940
+ }
2941
+ }
2942
+ throw new Error("all busy");
2943
+ }
2944
+ // Light Markdown: code blocks, inline code, bold, italics, lists, links (everything escaped first)
2945
+ function aiFormat(text) {
2946
+ const blocks = [];
2947
+ let h = escapeHtml(text).replace(/```[a-z0-9+-]*\n?([\s\S]*?)```/gi, (m, code) => { blocks.push(code.replace(/\n$/, "")); return `\u0000${blocks.length - 1}\u0000`; });
2948
+ h = h.replace(/`([^`\n]+)`/g, "<code>$1</code>")
2949
+ .replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>")
2950
+ .replace(/(^|[\s(])\*([^*\n]+)\*(?=[\s).,!?:;]|$)/g, "$1<em>$2</em>")
2951
+ .replace(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
2952
+ // line by line; runs of "- item" become a bullet list, runs of "1. item" a numbered list
2953
+ const out = [];
2954
+ let list = null;
2955
+ for (const line of h.split("\n")) {
2956
+ const bullet = line.match(/^\s*[-*•] (.*)/), num = line.match(/^\s*\d+[.)] (.*)/);
2957
+ const kind = bullet ? "ul" : num ? "ol" : null;
2958
+ if (list && list !== kind) { out.push(`</${list}>`); list = null; }
2959
+ if (kind) { if (!list) { out.push(`<${kind}>`); list = kind; } out.push(`<li>${(bullet || num)[1]}</li>`); continue; }
2960
+ if (/^\s*([-*_])\1{2,}\s*$/.test(line)) out.push("<hr>");
2961
+ else if (/^#{1,6} /.test(line)) out.push(`<p class="ai-h">${line.replace(/^#+ /, "")}</p>`);
2962
+ else if (line.trim()) out.push(`<p>${line}</p>`);
2963
+ }
2964
+ if (list) out.push(`</${list}>`);
2965
+ return out.join("").replace(/\u0000(\d+)\u0000/g, (m, i) => `<pre><code>${blocks[i]}</code></pre>`);
2966
+ }
2967
+ // -- AI page: several saved chats (this browser only), search, suggestions, pictures, daily usage --
2968
+ const AI_CHATS_KEY = "rug-ai-chats", AI_USAGE_KEY = "rug-ai-usage", AI_DAILY = 100;
2969
+ const AI_SUGGESTIONS = [
2970
+ ["🍝", "What should I make for dinner?"], ["😂", "Tell me a joke"],
2971
+ ["🎬", "Recommend a movie to watch"], ["💡", "Give me a fun fact"],
2972
+ ];
2973
+ function aiLoadChats() {
2974
+ const old = store.get(AI_KEY, null); // the first version kept one chat; bring it over
2975
+ let chats = store.get(AI_CHATS_KEY, []);
2976
+ if (Array.isArray(old) && old.length && !chats.length) chats = [{ id: Date.now().toString(36), title: aiTitle(old[0].text), ts: Date.now(), messages: old }];
2977
+ store.set(AI_KEY, null);
2978
+ return Array.isArray(chats) ? chats : [];
2979
+ }
2980
+ function aiTitle(text) { const t = String(text || "").replace(/\s+/g, " ").trim(); return t.length > 40 ? t.slice(0, 40) + "…" : t || "New chat"; }
2981
+ function aiSave() {
2982
+ // pictures are kept for this visit only (they'd fill the browser's storage)
2983
+ const slim = ai.chats.slice(0, 50).map((c) => ({ ...c, messages: c.messages.slice(-60).map(({ img, ...m }) => (img ? { ...m, hadImg: true } : m)) }));
2984
+ store.set(AI_CHATS_KEY, slim);
2985
+ }
2986
+ const aiCurrent = () => ai.chats.find((c) => c.id === ai.currentId) || null;
2987
+ // Usage: AI_DAILY messages a day on this device, starting fresh at midnight
2988
+ function aiUsage() {
2989
+ const today = new Date().toDateString(), u = store.get(AI_USAGE_KEY, {});
2990
+ return u.day === today ? u : { day: today, used: 0 };
2991
+ }
2992
+ function renderAiUsage() {
2993
+ const u = aiUsage(), left = Math.max(0, AI_DAILY - u.used);
2994
+ $("ai-usage-used").textContent = `${u.used}/${AI_DAILY}`;
2995
+ $("ai-usage-left").textContent = `${left} left`;
2996
+ $("ai-usage-fill").style.width = `${Math.min(100, (u.used / AI_DAILY) * 100)}%`;
2997
+ $("ai-foot").textContent = `${u.used}/${AI_DAILY} today · ${left} remaining · resets at midnight`;
2998
+ }
2999
+ function aiGroup(ts) {
3000
+ const d = new Date(ts), now = new Date(), day = 86400000;
3001
+ const start = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
3002
+ return ts >= start ? "Today" : ts >= start - day ? "Yesterday" : ts >= start - 7 * day ? "Last 7 days" : "Older";
3003
+ }
3004
+ function renderAiChats() {
3005
+ const q = $("ai-search").value.trim().toLowerCase();
3006
+ const list = ai.chats.filter((c) => !q || c.title.toLowerCase().includes(q) || c.messages.some((m) => m.text.toLowerCase().includes(q)));
3007
+ let html = "", last = "";
3008
+ for (const c of list) {
3009
+ const g = aiGroup(c.ts);
3010
+ if (g !== last) { html += `<p class="ai-group">${g}</p>`; last = g; }
3011
+ html += `<button class="ai-chat-item${c.id === ai.currentId ? " on" : ""}" type="button" data-chat="${escapeHtml(c.id)}">💬 <span>${escapeHtml(c.title)}</span></button>`;
3012
+ }
3013
+ $("ai-chats").innerHTML = html || `<p class="ai-group">${q ? "No chats match." : "No chats yet."}</p>`;
3014
+ }
3015
+ function renderAi() {
3016
+ const ready = aiReady(), c = aiCurrent(), msgs = c?.messages || [];
3017
+ $("ai-off").hidden = ready;
3018
+ $("ai-form").hidden = !ready;
3019
+ $("ai-title").textContent = c ? c.title : "New chat";
3020
+ $("ai-delete").hidden = !c;
3021
+ const log = $("ai-log");
3022
+ if (!msgs.length) {
3023
+ log.innerHTML = ready ? `<div class="ai-welcome"><h2>What can I help you with today?</h2><div class="ai-suggest">` +
3024
+ AI_SUGGESTIONS.map(([icon, text]) => `<button type="button" data-suggest="${escapeHtml(text)}"><span aria-hidden="true">${icon}</span>${escapeHtml(text)}</button>`).join("") + `</div></div>` : "";
3025
+ } else {
3026
+ log.innerHTML = msgs.map((m) => m.role === "assistant"
3027
+ ? `<div class="ai-msg assistant">${aiFormat(m.text)}${m.by ? `<span class="ai-by">${escapeHtml(m.by)}</span>` : ""}</div>`
3028
+ : `<div class="ai-msg user">${m.img ? `<img class="ai-msg-img" src="${m.img}" alt="Picture you sent">` : m.hadImg ? `<p class="ai-img-note">📷 picture</p>` : ""}<p>${escapeHtml(m.text)}</p></div>`).join("");
3029
+ if (ai.busy) log.insertAdjacentHTML("beforeend", `<div class="ai-msg assistant thinking"><span></span><span></span><span></span></div>`);
3030
+ }
3031
+ log.scrollTop = log.scrollHeight;
3032
+ renderAiChats();
3033
+ renderAiUsage();
3034
+ }
3035
+ async function sendAi(e, preset) {
3036
+ e?.preventDefault();
3037
+ const box = $("ai-input"), text = (preset ?? box.value).trim();
3038
+ if ((!text && !ai.pendingImg) || ai.busy) return;
3039
+ const u = aiUsage();
3040
+ if (u.used >= AI_DAILY) { toast(`You've used all ${AI_DAILY} AI messages today. They reset at midnight.`); return; }
3041
+ let c = aiCurrent();
3042
+ if (!c) { c = { id: Date.now().toString(36), title: aiTitle(text || "Picture"), ts: Date.now(), messages: [] }; ai.chats.unshift(c); ai.currentId = c.id; }
3043
+ c.messages.push({ role: "user", text: text.slice(0, 4000) || "What's in this picture?", ...(ai.pendingImg ? { img: ai.pendingImg } : {}) });
3044
+ c.ts = Date.now();
3045
+ ai.chats = [c, ...ai.chats.filter((x) => x !== c)]; // most recent chat on top
3046
+ box.value = "";
3047
+ clearAiPicture();
3048
+ store.set(AI_USAGE_KEY, { day: u.day, used: u.used + 1 });
3049
+ ai.busy = true;
3050
+ renderAi();
3051
+ try {
3052
+ const reply = await askAi(c.messages.slice(-16)); // the last few turns, so it remembers the conversation
3053
+ c.messages.push({ role: "assistant", text: reply.text, by: reply.by });
2062
3054
  } catch {
2063
- toast("That gift didn't send. You can send one gift a minute.");
3055
+ c.messages.push({ role: "assistant", text: "The AI is busy right now (the free limits ran out). Try again in a bit." });
2064
3056
  }
3057
+ ai.busy = false;
3058
+ aiSave();
3059
+ renderAi();
3060
+ box.focus();
2065
3061
  }
2066
- // Everyone watching the Live page sees new gifts pop up (not old ones)
2067
- async function watchGifts() {
2068
- const app = await getFirebase();
2069
- if (!app || gifts.ref) return;
2070
- gifts.ref = app.database().ref("live/gifts").orderByChild("ts").startAt(Date.now() - 5000);
2071
- gifts.ref.on("child_added", (s) => {
2072
- const v = s.val(), g = v && GIFTS.find((x) => x.id === v.gift);
2073
- if (!g || typeof v.name !== "string") return;
2074
- gifts.queue.push({ g, name: maskText(v.name).slice(0, 16) });
2075
- if (gifts.queue.length > 20) gifts.queue.shift(); // a burst never builds an endless line
2076
- playGifts();
2077
- }, () => { gifts.ref = null; });
2078
- }
2079
- function playGifts() {
2080
- if (gifts.playing || !gifts.queue.length) return;
2081
- gifts.playing = true;
2082
- const { g, name } = gifts.queue.shift();
2083
- const pop = $("gift-pop");
2084
- pop.innerHTML = `<span class="gift-emoji">${g.emoji}</span><span class="gift-text"><b>${escapeHtml(name)}</b> sent a ${g.name}!</span>`;
2085
- pop.hidden = false;
2086
- pop.classList.remove("show"); void pop.offsetWidth; pop.classList.add("show");
2087
- setTimeout(() => { pop.hidden = true; pop.classList.remove("show"); gifts.playing = false; setTimeout(playGifts, 400); }, 4000);
2088
- }
2089
- function renderGifts() {
2090
- // the gift row shows for viewers while someone is live (not for the streamer)
2091
- $("live-gifts").hidden = !live.state || !!live.streams;
2092
- if (!$("gift-btns").children.length) renderGiftButtons();
2093
- updateGiftWait();
2094
- clearInterval(gifts.timer);
2095
- if (!$("live-gifts").hidden) gifts.timer = setInterval(updateGiftWait, 1000);
2096
- }
2097
- function bindGifts() {
2098
- $("gift-btns").addEventListener("click", (e) => { const b = e.target.closest("[data-gift]"); if (b) sendGift(b.dataset.gift); });
3062
+ async function pickAiPicture(file) {
3063
+ if (!file || !/^image\//.test(file.type)) return;
3064
+ try {
3065
+ ai.pendingImg = await shrinkPhoto(await createImageBitmap(file));
3066
+ $("ai-attach-img").src = ai.pendingImg;
3067
+ $("ai-attach").hidden = false;
3068
+ $("ai-input").focus();
3069
+ } catch { toast("Couldn't read that picture."); }
3070
+ }
3071
+ function clearAiPicture() { ai.pendingImg = null; $("ai-attach").hidden = true; $("ai-attach-img").removeAttribute("src"); $("ai-pic-input").value = ""; }
3072
+ function bindAi() {
3073
+ ai.chats = aiLoadChats();
3074
+ ai.currentId = null;
3075
+ $("ai-form").addEventListener("submit", (e) => sendAi(e));
3076
+ $("ai-input").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); $("ai-form").requestSubmit(); } });
3077
+ $("ai-input").addEventListener("input", () => { const t = $("ai-input"); t.style.height = "auto"; t.style.height = Math.min(t.scrollHeight, 180) + "px"; });
3078
+ $("ai-input").addEventListener("paste", (e) => { const f = [...(e.clipboardData?.files || [])].find((x) => x.type.startsWith("image/")); if (f) { e.preventDefault(); pickAiPicture(f); } });
3079
+ $("ai-new").addEventListener("click", () => { ai.currentId = null; renderAi(); $("ai-input").focus(); });
3080
+ $("ai-chats").addEventListener("click", (e) => { const b = e.target.closest("[data-chat]"); if (b) { ai.currentId = b.dataset.chat; renderAi(); } });
3081
+ $("ai-search").addEventListener("input", renderAiChats);
3082
+ $("ai-delete").addEventListener("click", () => {
3083
+ const c = aiCurrent();
3084
+ if (!c || !confirm(`Delete “${c.title}”?`)) return;
3085
+ ai.chats = ai.chats.filter((x) => x !== c); ai.currentId = null; aiSave(); renderAi();
3086
+ });
3087
+ $("ai-log").addEventListener("click", (e) => { const b = e.target.closest("[data-suggest]"); if (b) sendAi(null, b.dataset.suggest); });
3088
+ $("ai-pic").addEventListener("click", () => $("ai-pic-input").click());
3089
+ $("ai-pic-input").addEventListener("change", () => pickAiPicture($("ai-pic-input").files[0]));
3090
+ $("ai-attach-x").addEventListener("click", clearAiPicture);
3091
+ const phone = () => innerWidth <= 800; // on phones the list slides over the chat, so it starts closed
3092
+ const side = (open) => { $("ai-app").classList.toggle("side-closed", !open); if (!phone()) store.set("rug-ai-side", open); };
3093
+ $("ai-collapse").addEventListener("click", () => side(false));
3094
+ $("ai-expand").addEventListener("click", () => side(true));
3095
+ for (const id of ["ai-new", "ai-chats"]) $(id).addEventListener("click", (e) => { if (phone() && e.target.closest("button")) side(false); });
3096
+ side(!phone() && store.get("rug-ai-side", true));
2099
3097
  }
2100
3098
 
2101
3099
  // ---------- Emoji picker and stickers ----------
@@ -2287,15 +3285,13 @@
2287
3285
  // There's one chat box: it sits on the Chat page, or in the player's side dock while that's open.
2288
3286
  const CHAT_SEEN_KEY = "rug-chat-seen", CHAT_DOCK_KEY = "rug-chat-dock";
2289
3287
  function dockOpen() { return !els.player.hidden && store.get(CHAT_DOCK_KEY, false); }
2290
- function liveShowing() { return els.player.hidden && !$("view-live").hidden; }
2291
- function chatShowing() { return dockOpen() || (els.player.hidden && !$("view-chat").hidden) || liveShowing(); }
3288
+ function chatShowing() { return dockOpen() || (els.player.hidden && !$("view-chat").hidden); }
2292
3289
  function placeChatBox() {
2293
3290
  const docked = dockOpen();
2294
3291
  $("chat-dock").hidden = !docked;
2295
3292
  $("dock-btn").setAttribute("aria-pressed", docked);
2296
- // the one chat box sits beside a game, beside the live stream, or on the Chat page
2297
- const home = docked ? $("chat-dock") : liveShowing() ? $("live-chat") : $("view-chat");
2298
- switchRoom(liveShowing() && !docked ? "live" : "main");
3293
+ // the one chat box sits beside a game or on the Chat page
3294
+ const home = docked ? $("chat-dock") : $("view-chat");
2299
3295
  if ($("chat-box").parentNode !== home) home.appendChild($("chat-box"));
2300
3296
  if (!chatShowing() && $("chat-box").classList.contains("full")) setChatFull(false);
2301
3297
  if (chatShowing()) markChatSeen();
@@ -2539,8 +3535,8 @@
2539
3535
  if (!deleting) {
2540
3536
  shown++;
2541
3537
  input.placeholder = text.slice(0, shown) + "▍";
2542
- if (shown >= text.length) { deleting = true; input.placeholder = text; timer = setTimeout(tick, 1800); return; }
2543
- timer = setTimeout(tick, 45 + Math.random() * 60); // uneven, like a real person typing
3538
+ if (shown >= text.length) { deleting = true; input.placeholder = text; timer = setTimeout(tick, 4000); return; }
3539
+ timer = setTimeout(tick, 90 + Math.random() * 90); // uneven, like a real person typing
2544
3540
  } else {
2545
3541
  shown--;
2546
3542
  input.placeholder = text.slice(0, shown) + "▍";
@@ -2548,59 +3544,29 @@
2548
3544
  deleting = false;
2549
3545
  line = (line + 1) % fixed.length;
2550
3546
  text = fixed[line]();
2551
- timer = setTimeout(tick, 350);
3547
+ timer = setTimeout(tick, 900);
2552
3548
  return;
2553
3549
  }
2554
- timer = setTimeout(tick, 22);
3550
+ timer = setTimeout(tick, 40);
2555
3551
  }
2556
3552
  }
2557
3553
  tick();
2558
3554
  }
2559
3555
 
2560
3556
  // ---------- Boot screen + auto-update ----------
2561
- const BOOT_LINES = [
2562
- "Loading… about 3 hours left", "Downloading more RAM…", "Calculating time left: 7 years…",
2563
- "Loading 99%… still 99%…", "Estimated time: yes", "Skill issue detected, loading anyway…",
2564
- "Installing 47 browser toolbars…", "Running on 3 megabytes and a dream…", "Buffering… (it's not the wifi, it's you)",
2565
- "Spawning in…", "Respawning in 3… 2… 9…", "Rendering grass you'll never touch…",
2566
- "Loading the loading screen…", "Downloading lag…", "Speedrunning the loading bar…",
2567
- "Turning it off and on again…", "Searching for the any key…", "Patching bugs, adding new ones…",
2568
- ];
2569
- // Football jokes are mixed in, but never two in a row
2570
- const TEAM_LINES = [
2571
- "The Cowboys suck. Loading anyway…", "Loading… unlike the Cowboys in January",
2572
- "This bar has more wins than the Cowboys…", "Giants are good. Loading respectfully…",
2573
- "Loading at Giants speed (fast, obviously)…", "Buffering like a Browns offense…",
2574
- "Searching for a Browns quarterback… still searching…", "Eagles fans booing the loading bar…",
2575
- "Loading… quieter than Philly after a loss", "Steelers: 8-9 and somehow still loading…",
2576
- "Loading with a Steelers-level 'we'll get 'em next year'…", "Ravens up big… loading the 4th-quarter collapse…",
2577
- "Loading faster than a Ravens playoff exit…",
2578
- ];
2579
3557
  const boot = { el: $("boot"), fill: $("boot-fill"), msg: $("boot-msg"), ver: $("boot-ver"), timer: 0, pct: 0 };
2580
3558
  function startBoot() {
2581
- const used = new Set();
2582
- let lastWasTeam = false;
2583
- const next = () => {
2584
- // ~1 in 3 lines is a team joke, but never right after another one
2585
- const team = !lastWasTeam && Math.random() < 0.35;
2586
- const pool = (team ? TEAM_LINES : BOOT_LINES).filter((l) => !used.has(l));
2587
- const line = pool[Math.floor(Math.random() * pool.length)] || BOOT_LINES[0];
2588
- used.add(line);
2589
- lastWasTeam = team;
2590
- return line;
2591
- };
2592
- boot.msg.textContent = next();
3559
+ boot.msg.textContent = "Loading…";
2593
3560
  boot.timer = setInterval(() => {
2594
- boot.msg.textContent = next();
2595
3561
  boot.pct = Math.min(90, boot.pct + 8 + Math.random() * 14); // creeps up, saves the last bit for "done"
2596
3562
  boot.fill.style.width = `${boot.pct}%`;
2597
- }, 420);
3563
+ }, 120);
2598
3564
  }
2599
3565
  function finishBoot(text) {
2600
3566
  clearInterval(boot.timer);
2601
3567
  boot.fill.style.width = "100%";
2602
3568
  if (text) boot.msg.textContent = text;
2603
- setTimeout(() => boot.el.classList.add("done"), 250);
3569
+ setTimeout(() => boot.el.classList.add("done"), 120);
2604
3570
  }
2605
3571
 
2606
3572
  // When opened from a versioned unpkg link (e.g. an old bookmark), jump to the newest version.
@@ -2625,10 +3591,22 @@
2625
3591
  }
2626
3592
 
2627
3593
  async function init() {
3594
+ let firstVisit = false;
3595
+ try { firstVisit = !Object.keys(localStorage).some((k) => k.startsWith("rug-")); } catch {}
2628
3596
  loadSettings();
2629
- if (settings.boot !== false) startBoot();
2630
- else boot.el.classList.add("done"); // loading screen turned off in Settings
3597
+ startBoot();
2631
3598
  initTheme();
3599
+ // the side bar can be tucked away (remembered); a small tab on the left edge brings it back
3600
+ const railHidden = (h) => { document.documentElement.classList.toggle("rail-hidden", h); store.set("rug-rail-hidden", h); };
3601
+ document.documentElement.classList.toggle("rail-hidden", store.get("rug-rail-hidden", false));
3602
+ const peek = (on) => document.documentElement.classList.toggle("rail-peek", on);
3603
+ $("rail-hide").addEventListener("click", () => { peek(false); railHidden(true); });
3604
+ $("rail-show").addEventListener("click", () => { peek(false); railHidden(false); });
3605
+ // While hidden, pointing at the left edge slides it back out over the page; moving away tucks it in again
3606
+ $("rail-zone").addEventListener("mouseenter", () => peek(true));
3607
+ document.querySelector(".rail").addEventListener("mouseleave", () => peek(false));
3608
+ $("soundboard-btn").addEventListener("click", () => play("gn-179")); // the soundboard: in the side bar, not the game list
3609
+ for (const id of ["home-apps", "gotd"]) $(id).addEventListener("click", (e) => { const b = e.target.closest("[data-id]"); if (b) play(b.dataset.id); });
2632
3610
  startClock();
2633
3611
  startGamepad();
2634
3612
  setPerRow(store.get(PER_ROW_KEY, 6));
@@ -2644,24 +3622,26 @@
2644
3622
  bindAdmin();
2645
3623
  bindChatTools();
2646
3624
  bindChatExtras();
3625
+ bindPolls();
2647
3626
  bindQuotes();
2648
- bindLive();
2649
- bindGifts();
3627
+ bindAi();
3628
+ bindTrivia();
2650
3629
  bindReports();
2651
3630
  startAnalytics();
2652
3631
  startPresence();
2653
3632
  // Listen to chat from the start so the chat buttons can show a dot for new messages.
2654
3633
  // First visit: only messages from now on count as new.
2655
3634
  if (store.get(CHAT_SEEN_KEY, null) === null) store.set(CHAT_SEEN_KEY, Date.now());
2656
- if (CFG.firebase) { openChat(); startQuotes(); startLiveWatch(); }
2657
- // long enough to read a joke or two (skipped when the loading screen is off)
2658
- const minShow = new Promise((r) => setTimeout(r, settings.boot !== false ? 1500 : 0));
3635
+ if (CFG.firebase) { openChat(); startQuotes(); }
3636
+ // just long enough that the loading screen doesn't flash
3637
+ const minShow = new Promise((r) => setTimeout(r, 300));
2659
3638
  const update = newerVersionUrl(2500);
2660
3639
  try {
2661
3640
  const res = await fetch("games.json", { cache: "no-cache" });
2662
3641
  const data = await res.json();
2663
- games = data.games.slice().sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
2664
- byId = new Map(games.map((g) => [g.id, g]));
3642
+ // "hidden" entries (the soundboard) can be opened by id but aren't listed with the games
3643
+ games = data.games.filter((g) => !g.hidden).sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
3644
+ byId = new Map(data.games.map((g) => [g.id, g]));
2665
3645
  cdnPins = data.cdnPins || {};
2666
3646
  } catch (err) {
2667
3647
  console.error(err);
@@ -2680,13 +3660,17 @@
2680
3660
  await minShow;
2681
3661
  startTypingPlaceholder();
2682
3662
  els.homeSub.innerHTML = `${games.length} games · press <kbd>/</kbd> to search`;
2683
- els.footerCount.textContent = `${games.length} games`;
2684
3663
  renderChips();
2685
3664
  renderRecent();
2686
3665
  renderGrid();
2687
3666
  startMarquee();
3667
+ renderHomeApps();
3668
+ renderGameOfDay();
3669
+ startCommunity();
2688
3670
  route();
2689
3671
  finishBoot("Done");
3672
+ bindTour();
3673
+ if (firstVisit && !store.get(TOUR_KEY, false) && !location.hash) setTimeout(showTour, 700);
2690
3674
  }
2691
3675
 
2692
3676
  init();