As a newcomer to Typescript, JavaScript, and front-end development, I am experimenting with creating a simulation of an AI opponent's "thinking" process when playing cards in a game. The idea is to visually represent the AI's decision-making by shifting each card slightly to the left and then back to the right before actually playing a card from its hand.
In my project, I have a collection of images that symbolize a hand of cards. Using Visual Studio Code for coding and Chrome for debugging, I've implemented a process where the API call triggers the AI logic, followed by a sequence that involves iterating through the cards, simulating the thinking process, and finally playing the chosen card. Despite having everything set up in synchronous callback functions, the visual effect only seems to work properly when a breakpoint is active during debugging.
// Function triggered on opponent's turn
opponentTurn(callback) {
this.boardService.opponentTurn()
.subscribe(
cardPlayed =>
{
let cardData = [];
cardData = JSON.parse(cardPlayed.toString());
// Simulate the AI thought process
this.selectCard(function(_thisagain) {
_thisagain.dragService.simulateDragDrop(cardData);
});
callback(this);
}
);
}
// Method to simulate selection of cards for AI's "thinking"
selectCard(callback) {
for (var i = 0; i < this.players[1].cardHand.length; i++)
{
let imgObj = document.getElementById(this.players[1].name + i);
if (imgObj != null)
{
this.moveCard(imgObj, '400px', function(_thisagain) {
_thisagain.moveCard(imgObj, '350px', function() {
});
});
}
}
callback(this);
}
moveCard(imgObj, position, callback) {
this.wait(250, function() {
imgObj.style.right = position;
});
callback(this);
}
wait(ms, callback) {
var start = new Date().getTime();
var end = start;
while(end < start + ms)
{
end = new Date().getTime();
}
callback(this);
}
The issue arises when the code runs without breakpoints: the card animations don't occur smoothly. My assumption is that the lack of redraws causes this problem. However, as a novice, I'm uncertain about how to address it effectively. Any guidance or insights would be greatly appreciated.