refactor stats

This commit is contained in:
Hannah Park 2022-01-20 21:19:33 -05:00
parent 4aa84f25e1
commit e57e1cc391
12 changed files with 152 additions and 148 deletions

4
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,4 @@
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
}

6
package-lock.json generated
View file

@ -18,7 +18,6 @@
"@types/react": "^17.0.38", "@types/react": "^17.0.38",
"@types/react-dom": "^17.0.11", "@types/react-dom": "^17.0.11",
"classnames": "^2.3.1", "classnames": "^2.3.1",
"prettier": "^2.5.1",
"react": "^17.0.2", "react": "^17.0.2",
"react-dom": "^17.0.2", "react-dom": "^17.0.2",
"react-scripts": "5.0.0", "react-scripts": "5.0.0",
@ -28,6 +27,7 @@
"devDependencies": { "devDependencies": {
"autoprefixer": "^10.4.2", "autoprefixer": "^10.4.2",
"postcss": "^8.4.5", "postcss": "^8.4.5",
"prettier": "^2.5.1",
"tailwindcss": "^3.0.12" "tailwindcss": "^3.0.12"
} }
}, },
@ -12633,6 +12633,7 @@
"version": "2.5.1", "version": "2.5.1",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.1.tgz", "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.1.tgz",
"integrity": "sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==", "integrity": "sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==",
"dev": true,
"bin": { "bin": {
"prettier": "bin-prettier.js" "prettier": "bin-prettier.js"
}, },
@ -24864,7 +24865,8 @@
"prettier": { "prettier": {
"version": "2.5.1", "version": "2.5.1",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.1.tgz", "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.1.tgz",
"integrity": "sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==" "integrity": "sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==",
"dev": true
}, },
"pretty-bytes": { "pretty-bytes": {
"version": "5.6.0", "version": "5.6.0",

View file

@ -9,7 +9,7 @@ import { InfoModal } from './components/modals/InfoModal'
import { WinModal } from './components/modals/WinModal' import { WinModal } from './components/modals/WinModal'
import { StatsModal } from './components/modals/StatsModal' import { StatsModal } from './components/modals/StatsModal'
import { isWordInWordList, isWinningWord, solution } from './lib/words' import { isWordInWordList, isWinningWord, solution } from './lib/words'
import { addEvent, loadStats } from './lib/stats' import { addStatsForCompletedGame, loadStats } from './lib/stats'
import { import {
loadGameStateFromLocalStorage, loadGameStateFromLocalStorage,
saveGameStateToLocalStorage, saveGameStateToLocalStorage,
@ -37,15 +37,12 @@ function App() {
return loaded.guesses return loaded.guesses
}) })
const [stats, setStats] = useState<number[]>(() => { const [stats, setStats] = useState(() => loadStats())
const loaded = loadStats()
return loaded
})
useEffect(() => { useEffect(() => {
saveGameStateToLocalStorage({ guesses, solution }) saveGameStateToLocalStorage({ guesses, solution })
}, [guesses]) }, [guesses])
useEffect(() => { useEffect(() => {
if (isGameWon) { if (isGameWon) {
setIsWinModalOpen(true) setIsWinModalOpen(true)
@ -69,7 +66,7 @@ function App() {
setIsNotEnoughLetters(false) setIsNotEnoughLetters(false)
}, 2000) }, 2000)
} }
if (!isWordInWordList(currentGuess)) { if (!isWordInWordList(currentGuess)) {
setIsWordNotFoundAlertOpen(true) setIsWordNotFoundAlertOpen(true)
return setTimeout(() => { return setTimeout(() => {
@ -84,12 +81,12 @@ function App() {
setCurrentGuess('') setCurrentGuess('')
if (winningWord) { if (winningWord) {
setStats(addEvent(stats, guesses.length)) setStats(addStatsForCompletedGame(stats, guesses.length))
return setIsGameWon(true) return setIsGameWon(true)
} }
if (guesses.length === 5) { if (guesses.length === 5) {
setStats(addEvent(stats, guesses.length + 1)) setStats(addStatsForCompletedGame(stats, guesses.length + 1))
setIsGameLost(true) setIsGameLost(true)
return setTimeout(() => { return setTimeout(() => {
setIsGameLost(false) setIsGameLost(false)
@ -148,7 +145,7 @@ function App() {
<StatsModal <StatsModal
isOpen={isStatsModalOpen} isOpen={isStatsModalOpen}
handleClose={() => setIsStatsModalOpen(false)} handleClose={() => setIsStatsModalOpen(false)}
stats={stats} gameStats={stats}
/> />
<AboutModal <AboutModal
isOpen={isAboutModalOpen} isOpen={isAboutModalOpen}

View file

@ -1,19 +0,0 @@
import {Progress} from './progress'
type Props = {
data: number[]
}
export const Histogram = ({ data }: Props) => {
const min = 10
const max = Math.ceil(Math.max.apply(null, data)*1.2)
return(
<div className="columns-1 justify-left m-2 text-sm">
{ data.map(( value, i ) => (
<Progress key={i} index={i} size={min+100*value/max}
label={String(value)} />
))
}
</div>
)
}

View file

@ -1,23 +0,0 @@
type Props = {
index: number,
size: number,
label: string
}
export const Progress = ( {index, size, label}: Props ) => {
return(
<div className="flex justify-left m-1">
<div className="items-center justify-center w-10%">{index+1}</div>
<div className="bg-gray-200 rounded-full w-full ml-2">
<div
style={{ width: `${size}%`}}
className="bg-blue-600 text-xs font-medium text-blue-100 text-center p-0.5
rounded-l-full">{label}
</div>
</div>
</div>
)
}

View file

@ -1,21 +1,17 @@
import { Fragment } from 'react' import { Fragment } from 'react'
import { Dialog, Transition } from '@headlessui/react' import { Dialog, Transition } from '@headlessui/react'
import { XCircleIcon } from '@heroicons/react/outline' import { XCircleIcon } from '@heroicons/react/outline'
import { trys, successRate, currentStreak, bestStreak } from '../../lib/stats' import { StatBar } from '../stats/StatBar'
import { Histogram } from '../histogram/histogram' import { Histogram } from '../stats/Histogram'
import { StatLine } from '../statline/statline' import { GameStats } from '../../lib/localStorage'
type Props = { type Props = {
isOpen: boolean isOpen: boolean
handleClose: () => void handleClose: () => void
stats: number[] gameStats: GameStats
} }
export const StatsModal = ({ isOpen, handleClose, stats }: Props) => { export const StatsModal = ({ isOpen, handleClose, gameStats }: Props) => {
const labels = ["Total trys", "Success rate",
"Current streak", "Best streak"]
const values = [String(trys(stats)), String(successRate(stats))+'%',
String(currentStreak(stats)), String(bestStreak(stats))]
return ( return (
<Transition.Root show={isOpen} as={Fragment}> <Transition.Root show={isOpen} as={Fragment}>
<Dialog <Dialog
@ -52,13 +48,15 @@ export const StatsModal = ({ isOpen, handleClose, stats }: Props) => {
leaveFrom="opacity-100 translate-y-0 sm:scale-100" leaveFrom="opacity-100 translate-y-0 sm:scale-100"
leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
> >
<div className="inline-block align-bottom bg-white rounded-lg px-4 <div
className="inline-block align-bottom bg-white rounded-lg px-4
pt-5 pb-4 text-left overflow-hidden shadow-xl transform pt-5 pb-4 text-left overflow-hidden shadow-xl transform
transition-all sm:my-8 sm:align-middle sm:max-w-sm sm:w-full sm:p-6"> transition-all sm:my-8 sm:align-middle sm:max-w-sm sm:w-full sm:p-6"
>
<div className="absolute right-4 top-4"> <div className="absolute right-4 top-4">
<XCircleIcon <XCircleIcon
className="h-6 w-6 cursor-pointer" className="h-6 w-6 cursor-pointer"
onClick={() => handleClose()} onClick={handleClose}
/> />
</div> </div>
<div> <div>
@ -69,14 +67,11 @@ export const StatsModal = ({ isOpen, handleClose, stats }: Props) => {
> >
Statistics Statistics
</Dialog.Title> </Dialog.Title>
<StatLine labels={labels} values={values} /> <StatBar gameStats={gameStats} />
<Dialog.Title <h4 className="text-lg leading-6 font-medium text-gray-900">
as="h3" Guess Distribution
className="text-lg leading-6 font-medium text-gray-900" </h4>
> <Histogram gameStats={gameStats} />
Guess Distribution
</Dialog.Title>
<Histogram data={stats.slice(0,6)} />
</div> </div>
</div> </div>
</div> </div>

View file

@ -1,19 +0,0 @@
type Props = {
labels: string[]
values: string[]
}
export const StatLine = ({labels, values}: Props) => {
return (
<div className="flex justify-center m-1">
{values.map((value,i ) => (
<div key={i} className="items-center justify-center m-1 w-1/4">
<div className="text-3xl font-bold">{value} </div>
<div className="text-sm">{labels[i]}</div>
</div>
))}
</div>
)
}

View file

@ -0,0 +1,23 @@
import { GameStats } from '../../lib/localStorage'
import { Progress } from './Progress'
type Props = {
gameStats: GameStats
}
export const Histogram = ({ gameStats }: Props) => {
const { totalGames, winDistribution } = gameStats
return (
<div className="columns-1 justify-left m-2 text-sm">
{winDistribution.map((value, i) => (
<Progress
key={i}
index={i}
size={95 * (value / totalGames)}
label={String(value)}
/>
))}
</div>
)
}

View file

@ -0,0 +1,21 @@
type Props = {
index: number
size: number
label: string
}
export const Progress = ({ index, size, label }: Props) => {
return (
<div className="flex justify-left m-1">
<div className="items-center justify-center w-2">{index + 1}</div>
<div className="rounded-full w-full ml-2">
<div
style={{ width: `${5 + size}%` }}
className="bg-blue-600 text-xs font-medium text-blue-100 text-center p-0.5 rounded-l-full"
>
{label}
</div>
</div>
</div>
)
}

View file

@ -0,0 +1,31 @@
import { GameStats } from '../../lib/localStorage'
type Props = {
gameStats: GameStats
}
const StatItem = ({
label,
value,
}: {
label: string
value: string | number
}) => {
return (
<div className="items-center justify-center m-1 w-1/4">
<div className="text-3xl font-bold">{value}</div>
<div className="text-xs">{label}</div>
</div>
)
}
export const StatBar = ({ gameStats }: Props) => {
return (
<div className="flex justify-center my-2">
<StatItem label="Total tries" value={gameStats.totalGames} />
<StatItem label="Success rate" value={`${gameStats.successRate}%`} />
<StatItem label="Current streak" value={gameStats.currentStreak} />
<StatItem label="Best streak" value={gameStats.bestStreak} />
</div>
)
}

View file

@ -16,17 +16,20 @@ export const loadGameStateFromLocalStorage = () => {
const gameStatKey = 'gameStats' const gameStatKey = 'gameStats'
type StoredGameStats = { export type GameStats = {
distribution: number[] winDistribution: number[]
current: number gamesFailed: number
best: number currentStreak: number
bestStreak: number
totalGames: number
successRate: number
} }
export const saveStatsToLocalStorage = ( gameStats: StoredGameStats) => { export const saveStatsToLocalStorage = (gameStats: GameStats) => {
localStorage.setItem(gameStatKey, JSON.stringify(gameStats)) localStorage.setItem(gameStatKey, JSON.stringify(gameStats))
} }
export const loadStatsFromLocalStorage = () => { export const loadStatsFromLocalStorage = () => {
const stats = localStorage.getItem(gameStatKey) const stats = localStorage.getItem(gameStatKey)
return stats ? (JSON.parse(stats) as StoredGameStats) : null return stats ? (JSON.parse(stats) as GameStats) : null
} }

View file

@ -1,67 +1,56 @@
/**
** An attempt at a statistics object and its interface
**/
import { import {
GameStats,
loadStatsFromLocalStorage, loadStatsFromLocalStorage,
saveStatsToLocalStorage saveStatsToLocalStorage,
} from './localStorage' } from './localStorage'
// In stats array elements 0-5 are successes in 1-6 trys // In stats array elements 0-5 are successes in 1-6 trys
// stats[6] is the number of failures
// stats[7] is the currentStreak
// stats[8] is the bestStreak
export const failures = (stats: number[] ) => { return stats[6] } export const addStatsForCompletedGame = (
export const currentStreak = (stats: number[] ) => { return stats[7] } gameStats: GameStats,
export const bestStreak = (stats: number[] ) => { return stats[8] } count: number
) => {
// Count is number of incorrect guesses before end.
const stats = { ...gameStats }
export const addEvent = (stats: number[], count: number) => { stats.totalGames += 1
// Count is number of incorrect guesses before end.
if(count < 0) { count = 0 } // Should not really need this if (count > 5) {
if( count > 5 ){ // A fail situation // A fail situation
stats[7] = 0 // End current streak stats.currentStreak = 0
stats[6] += 1 // Increase number of fails stats.gamesFailed += 1
} else { } else {
stats[count] += 1 // Increase counters stats.winDistribution[count] += 1
stats[7] += 1 stats.currentStreak += 1
if( bestStreak(stats) < currentStreak(stats) ){
stats[8] = currentStreak(stats) if (stats.bestStreak < stats.currentStreak) {
stats.bestStreak = stats.currentStreak
} }
} }
saveStats(stats)
stats.successRate = getSuccessRate(stats)
saveStatsToLocalStorage(stats)
return stats return stats
} }
export const resetStats = () => { const defaultStats: GameStats = {
return [0,0,0,0,0,0,0,0,0] winDistribution: [0, 0, 0, 0, 0, 0],
} gamesFailed: 0,
currentStreak: 0,
export const saveStats = (stats: number[]) => { bestStreak: 0,
const distribution = stats.slice(0,7) totalGames: 0,
const current = currentStreak(stats) successRate: 0,
const best = bestStreak(stats)
saveStatsToLocalStorage({ distribution , current, best })
} }
export const loadStats = () => { export const loadStats = () => {
const loaded = loadStatsFromLocalStorage() return loadStatsFromLocalStorage() || defaultStats
var stats = resetStats()
if( loaded ){
stats = loaded.distribution
stats[7] = loaded.current
stats[8] = loaded.best
}
return ( stats )
} }
export const trys = (stats: number[] ) => { const getSuccessRate = (gameStats: GameStats) => {
return(stats.slice(0,7).reduce((a,b) => a+b , 0 )) const { totalGames, gamesFailed } = gameStats
return Math.round(
(100 * (totalGames - gamesFailed)) / Math.max(totalGames, 1)
)
} }
export const successRate = (stats: number[] ) => {
return(Math.round((100*(trys(stats) - failures(stats)))/Math.max(trys(stats),1)))
}