我想創建一個有一些玩家的桌子,如果我加入這個桌子,我的用戶名應該在屏幕下方,就像在另一個游戲中一樣。其他玩家也一樣!
為此我該怎么辦。
export const GameStart = (props) => {
const params = useParams();
const gameID = params.gameID;
const { isConnected, client, occupants } = useGameValue();
const ourTeam = occupants?.findIndex((p) => p.nickname == client.nickname);
console.log(ourTeam);
const startGame = () => {
client.start(gameID);
};
const playerIndex = occupants
.filter((o) => !o.inactive)
.findIndex((o) => o.nickname === client.nickname);
const getPlayerStyle = (index) => {
console.log("condition player index ", playerIndex, index);
if (index === playerIndex) {
const rotate = `rotate(0deg) translate(197px)`;
console.log("if condition", rotate);
return {
transform: `${rotate}`,
};
} else {
const angle = 360 / occupants.length;
const rotate = occupants.length - index;
const rotation = `rotate(${angle * rotate}deg) translate(197px) `;
return {
transform: `${rotation}`,
};
}
};
const playerCount = (players) => {
return players === 1
? "count-1"
: players === 2
? "count-2"
: players === 3
? "count-3"
: players === 4
? "count-4"
: players === 5
? "count-5"
: players === 6
? "count-6"
: "";
};
useEffect(() => {
if (!client.nickname && isConnected) {
client.nickname = prompt("enter nickname");
client.join(gameID, null, client.nickname);
}
}, [isConnected]);
useEffect(() => {
console.log(occupants, "occupants");
}, [occupants]);
return (
<div className="gameStart">
<h2>Game</h2>
{occupants && (
<div className="table">
<div
className={`players ${playerCount(occupants.length)}`}
style={{ "--rotation-xtra-turns": `${playerIndex}` }}
>
{occupants.map((data, index) => {
return (
<div
className={`player`}
style={getPlayerStyle(index)}
key={index}
>
{data.nickname}
</div>
);
})}
</div>
</div>
)}
<button onClick={startGame}>Start Game</button>
</div>
);
};
這是我嘗試過的,但它不起作用,不起作用的是,如果我加入一個新的球員在另一個設備上,我以前的用戶也在相同的底部空間,我的用戶的地方。
我想知道是怎么發生的,有人能修改給我嗎?
我用一個函數創建了一個簡單的例子,這個函數把一個有特定名字的玩家(& quot簡& quot在這種情況下)在列表的底部。在這個例子中,我用一個按鈕調用排序函數,但是你可以隨時調用它。你必須替換& quot簡& quot使用用戶的實際用戶名。
function Example() {
const [players, setPlayers] = useState(["wim", "henk", "jan", "piet"]);
const sortPlayer = () => {
const newPlayerList = [...players].sort((a,b) => {
return (a === "jan")
})
setPlayers(newPlayerList)
}
const playerElements = players.map(p => {
return <div key={p}>{p}</div>
}
);
return (
<div>
<button onClick={sortPlayer}>Sort JAN to bottom</button>
<div>
{playerElements}
</div>
</div>
);
}
上一篇tp vue 官網
下一篇ts vue全局方法