Implemented rotating counter

This commit is contained in:
mic0 2024-10-23 11:14:39 +02:00
parent 294052070a
commit 56e4b5ce26
Signed by: mico
GPG Key ID: A3F8023524CF1C8D
2 changed files with 41 additions and 7 deletions

View File

@ -0,0 +1,34 @@
import { useEffect, useReducer, useRef } from "react";
import { usePlayer } from "../providers/PlayerProvider"
import styles from "../styles/Header.module.css"
const calculateBalance = (balance: bigint, perSecond: bigint, lastRaidedAt: bigint) => {
// convert to milliseconds trick so we get a more smooth counter
const millisecondsSinceLastRaid =
(new Date()).getTime() - parseInt(lastRaidedAt.toString()) * 1000;
return (balance + (BigInt(millisecondsSinceLastRaid) * perSecond / BigInt(1000)))
}
const formatToGeld = (balance: bigint) => balance / BigInt(10000);
const Counter = () => {
const { balance, army, player } = usePlayer();
const [, render] = useReducer(p => !p, false);
const balanceCount = useRef(balance ?? BigInt(0))
useEffect(() => {
const tickInterval = setInterval(() => {
balanceCount.current = formatToGeld(calculateBalance(
balance,
army?.profit_per_second ?? BigInt(0),
player?.last_raided_at ?? BigInt(0)
));
render();
}, 20);
return () => clearInterval(tickInterval)
}, [balance, army?.profit_per_second, player?.last_raided_at])
return <p className={styles.counter}>{balanceCount.current.toString()} GELD</p>
}
export default Counter

View File

@ -1,15 +1,15 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import React, { useCallback, useEffect, useMemo, useState } from "react"
import styles from "../styles/Header.module.css"
import { usePlayer } from "../providers/PlayerProvider";
import { useAccount } from 'wagmi';
import dynamic from "next/dynamic";
import { formatUnits } from "viem";
import Counter from "./Counter";
const Header = () => {
const { isConnected } = useAccount();
const { isRegistered, register, balance } = usePlayer();
const { isRegistered, register, balance, army } = usePlayer();
const [count, setCount] = useState("0")
const [perSecond, setPerSecond] = useState("0")
useEffect(() => {
if (balance != null) {
@ -25,17 +25,17 @@ const Header = () => {
const subtitle = useMemo(() => {
if (isRegistered) {
return <p className={styles.counter}>{count} GELD</p>
return <Counter />
} else {
return <p className={styles.counter}>SLAY THE MOLOCH</p>
}
}, [isRegistered, count])
}, [isRegistered])
const perSecondParagraph = useMemo(() => {
return (isRegistered) ?
<p className={styles.counter_per_seconds}>per second: {perSecond}</p>
<p className={styles.counter_per_seconds}>per second: {army?.profit_per_second.toString()}</p>
: null
}, [isRegistered, perSecond])
}, [isRegistered, army?.profit_per_second])
const onRegister = useCallback(() => {
if (isRegistered) return