Skip to content

Commit

Permalink
fixed fleet movements
Browse files Browse the repository at this point in the history
  • Loading branch information
ametel01 committed Feb 16, 2024
1 parent 8fd53cd commit 094c842
Show file tree
Hide file tree
Showing 10 changed files with 154 additions and 53 deletions.
9 changes: 6 additions & 3 deletions client/src/components/auth/AuthController.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import AuthScreen from '../../views/LoginOrGenerate';
import Dashboard from '../../views/DashBoard';
import Header from '../ui/Header';
import { useDojo } from '../../dojo/useDojo';
import { DestinationProvider } from '../../context/DestinationContext';

const AuthController = () => {
const {
Expand All @@ -20,7 +21,7 @@ const AuthController = () => {

const planetId = useComponentValue(GameOwnerPlanet, entityId);

const hasGeneratedPlanets = planetId?.planet_id > 0;
const hasGeneratedPlanets = (planetId?.planet_id || 0) > 0;
// const isOverallLoading = isTokenOfLoading || walletConnectLoading;

const shouldRenderAuthScreen =
Expand All @@ -33,8 +34,10 @@ const AuthController = () => {
/>
) : (
<>
<Header />
<Dashboard planetId={planetId?.planet_id} />
<DestinationProvider>
<Header planetId={planetId?.planet_id || 0} />
<Dashboard planetId={planetId?.planet_id || 0} />
</DestinationProvider>
</>
);
};
Expand Down
1 change: 0 additions & 1 deletion client/src/components/buttons/ButtonAttackPlanet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,6 @@ function ButtonAttackPlanet({
const [speed, setSpeed] = useState(100);

const missions = useActiveMissions(planetId);
console.log('missions', missions);
const isMissionLimitReached =
missions && techs && missions.length === Number(techs.digital) + 1;

Expand Down
22 changes: 6 additions & 16 deletions client/src/components/ui/FleetMovements.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import React, {
useState,
useEffect,
useCallback,
useReducer,
useMemo,
} from 'react';

import { useGetActiveMissions } from '../../hooks/FleetHooks';
import React, { useState, useEffect, useCallback, useReducer } from 'react';

import { Box } from '@mui/system';
import Modal from '@mui/material/Modal';
import styled from 'styled-components';
import { calculateFleetLoss } from '../../shared/utils/Formulas';
import { HeaderButton } from '../../shared/styled/Button';
import { MissionRow } from './MissionRow';
import { useActiveMissions } from '../../hooks/useActiveMissions';

export const StyledBox = styled(Box)({
fontWeight: 400,
Expand Down Expand Up @@ -110,14 +104,10 @@ interface Props {
}

export const FleetMovements = ({ planetId }: Props) => {
const rawMissions = useGetActiveMissions(planetId);
const missions = useMemo(() => {
if (!rawMissions) return [];
console.log(planetId);
const missions = useActiveMissions(planetId);

return [...rawMissions].sort((a, b) => {
return Number(a.time_arrival) - Number(b.time_arrival);
});
}, [rawMissions]);
console.log(missions);

const [isOpen, setIsOpen] = useState(false);
const [state, dispatch] = useReducer(fleetReducer, {
Expand Down
12 changes: 6 additions & 6 deletions client/src/components/ui/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import { HeaderButton } from '../../shared/styled/Button';
import { styled } from '@mui/material/styles';
// import { FleetMovements } from './FleetMovements';
import { FleetMovements } from './FleetMovements';
import { Link } from 'react-router-dom';
import LogoutIcon from '@mui/icons-material/Logout';
import IconButton from '@mui/material/IconButton';
Expand Down Expand Up @@ -32,11 +32,11 @@ const Spacer = styled('div')({
flex: '1',
});

// interface Props {
// planetId: number;
// }
interface Props {
planetId: number;
}

const Header = () => {
const Header = ({ planetId }: Props) => {
const { account } = useDojo();

const handleLogoutClick = () => {
Expand Down Expand Up @@ -66,6 +66,7 @@ const Header = () => {
</Link>
</HeaderButton>
<ConnectWallet />
<FleetMovements planetId={planetId || 0} />

{/* <HeaderButton>
<Link
Expand All @@ -75,7 +76,6 @@ const Header = () => {
Pioneer NFT
</Link>
</HeaderButton>
<FleetMovements planetId={planetId || 0} />
<HeaderButton variant="text">
<Link
to="/battlereports"
Expand Down
45 changes: 25 additions & 20 deletions client/src/components/ui/MissionRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,11 @@ import React, { memo } from 'react';
import styled from 'styled-components';
import Tooltip from '@mui/material/Tooltip';
import { MissionCategory, type Mission } from '../../shared/types';
import {
useAttackPlanet,
useRecallFleet,
useCollectDebris,
useDockFleet,
} from '../../hooks/FleetHooks';
import { usePlanetPosition } from '../../hooks/usePlanetPosition';
import fleetIcon from '../../assets/uiIcons/Fleet.svg';
import { StyledButton } from '../../shared/styled/Button';
import { useDestination } from '../../context/DestinationContext';
import { useDojo } from '../../dojo/useDojo';

const FleetTooltipContent = styled('div')({
display: 'flex',
Expand Down Expand Up @@ -60,20 +55,30 @@ interface MissionRowProps {

export const MissionRow = memo(
({ mission, index, countdown, decayPercentage }: MissionRowProps) => {
const {
setup: {
systemCalls: { attackPlanet, collectDebris, dockFleet, recallFleet },
},
account,
} = useDojo();

const position = usePlanetPosition(Number(mission.destination));

const destination = position
? `${Number(position.system)} / ${Number(position.orbit)}`
: 'Unknown';
const { writeAsync: recallFleet } = useRecallFleet(mission.id);
const { writeAsync: attackPlanet } = useAttackPlanet(mission.id);
const { writeAsync: collectDebris } = useCollectDebris(mission.id);
const { writeAsync: dockFleet } = useDockFleet(mission.id);

const onRecallClick = React.useCallback(() => {
recallFleet().then(() => {
// Handle post-recall actions here, if needed
});
}, [recallFleet]);
const attackCallBack = () => attackPlanet(account.account, mission.id);
const recallFleetCallBack = () => recallFleet(account.account, mission.id);
const collectDebrisCallBack = () =>
collectDebris(account.account, mission.id);
const dockFleetCallBack = () => dockFleet(account.account, mission.id);

// const onRecallClick = React.useCallback(() => {
// recallFleet().then(() => {
// // Handle post-recall actions here, if needed
// });
// }, [recallFleet]);

const { handleDestinationClick } = useDestination();

Expand Down Expand Up @@ -129,7 +134,7 @@ export const MissionRow = memo(
size="small"
sx={{ background: '#C47E33' }}
fullWidth
onClick={onRecallClick}
onClick={recallFleetCallBack}
>
Recall
</StyledButton>
Expand All @@ -139,10 +144,10 @@ export const MissionRow = memo(
onClick={() => {
{
mission.category == MissionCategory['Debris']
? collectDebris()
? collectDebrisCallBack()
: mission.category == MissionCategory['Attack']
? attackPlanet()
: dockFleet();
? attackCallBack()
: dockFleetCallBack();
}
}}
size="small"
Expand All @@ -159,7 +164,7 @@ export const MissionRow = memo(
size="small"
sx={{ background: '#C47E33' }}
fullWidth
onClick={onRecallClick}
onClick={recallFleetCallBack}
>
Recall
</StyledButton>
Expand Down
36 changes: 36 additions & 0 deletions client/src/context/DestinationContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import React, { createContext, useContext, useState, ReactNode } from 'react';

// Create a context
type DestinationContextType = {
selectedDestination: number | null;
handleDestinationClick: (destinationId: number) => void;
};

// Create a context with a default value
const DestinationContext = createContext<DestinationContextType>({
selectedDestination: null,
handleDestinationClick: () => {},
});

// Create a provider component
export const DestinationProvider = ({ children }: { children: ReactNode }) => {
const [selectedDestination, setSelectedDestination] = useState<number | null>(
null
);

const handleDestinationClick = (destinationId: number) => {
setSelectedDestination(destinationId);
};

return (
<DestinationContext.Provider
value={{ selectedDestination, handleDestinationClick }}
>
{children}
</DestinationContext.Provider>
);
};

// Hook for easy access to the context
// eslint-disable-next-line react-refresh/only-export-components
export const useDestination = () => useContext(DestinationContext);
69 changes: 69 additions & 0 deletions client/src/dojo/createSystemCalls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,72 @@ export function createSystemCalls(
}
};

const collectDebris = async (account: Account, missionId: number) => {
try {
const { transaction_hash } = await provider.execute(
account,
'fleetactions',
'collect_debris',
[missionId]
);

setComponentsFromEvents(
contractComponents,
getEvents(
await account.waitForTransaction(transaction_hash, {
retryInterval: 100,
})
)
);
} catch (e) {
console.log(e);
}
};

const recallFleet = async (account: Account, missionId: number) => {
try {
const { transaction_hash } = await provider.execute(
account,
'fleetactions',
'recall_fleet',
[missionId]
);

setComponentsFromEvents(
contractComponents,
getEvents(
await account.waitForTransaction(transaction_hash, {
retryInterval: 100,
})
)
);
} catch (e) {
console.log(e);
}
};

const dockFleet = async (account: Account, missionId: number) => {
try {
const { transaction_hash } = await provider.execute(
account,
'fleetactions',
'dock_fleet',
[missionId]
);

setComponentsFromEvents(
contractComponents,
getEvents(
await account.waitForTransaction(transaction_hash, {
retryInterval: 100,
})
)
);
} catch (e) {
console.log(e);
}
};

interface PlanetResourcesResponse {
steel: bigint;
quartz: bigint;
Expand Down Expand Up @@ -275,6 +341,9 @@ export function createSystemCalls(
buildDefence,
sendFleet,
attackPlanet,
collectDebris,
recallFleet,
dockFleet,
getPlanetResources,
getColonyResources,
};
Expand Down
11 changes: 6 additions & 5 deletions client/src/hooks/useActiveMissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ type EdgeType = {
};
};

export function useActiveMissions(planetId: number): Array<[Mission]> {
const [missions, setMissions] = useState<Array<[Mission]>>([]);
export function useActiveMissions(planetId: number): Array<Mission> {
const [missions, setMissions] = useState<Array<Mission>>([]);

const {
setup: { graphSdk },
Expand All @@ -45,7 +45,7 @@ export function useActiveMissions(planetId: number): Array<[Mission]> {
const edges = countResponse.data.activeMissionLenModels.edges;
if (edges && edges.length > 0) {
const count = edges[0].node.entity.models[0].lenght;
const activeMissions: Array<[Mission]> = [];
const activeMissions: Array<Mission> = [];

for (let i = 0; i < count; i++) {
const missionId = i + 1; // Adjust based on how colony IDs are determined
Expand All @@ -56,7 +56,9 @@ export function useActiveMissions(planetId: number): Array<[Mission]> {
const mission = extractMission(missionResponse);

if (mission) {
activeMissions.push([mission]);
if (mission.origin !== 0) {
activeMissions.push(mission);
}
}
}

Expand All @@ -76,7 +78,6 @@ function extractMission(response: any): Mission | undefined {
)?.node.entity.models[0];

if (missionModel) {
console.log('missionModel', missionModel);
return {
id: missionModel.mission.id,
time_start: missionModel.mission.time_start,
Expand Down
1 change: 0 additions & 1 deletion client/src/hooks/usePlanetShips.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ export function usePlanetShips(planetId: number): Fleet {
(model) => model?.__typename === 'PlanetShips'
);
if (planetShip && 'count' in planetShip) {
console.log('planetShip', planetShip.count);
setter(planetShip.count as number);
}
}
Expand Down
1 change: 0 additions & 1 deletion client/src/panels/UniverseViewTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,6 @@ export const UniverseViewTabPanel = ({
const [pageError, setPageError] = useState(false);
const itemsPerPage = 6;
const pageCount = Math.ceil(planetsData.length / itemsPerPage);
console.log('planetsData', planetsData);
// Fetch planets using the custom hook
const fetchedPlanets = useGeneratedPlanets();

Expand Down

0 comments on commit 094c842

Please sign in to comment.