gpt4 book ai didi

javascript - 如何在js中实现嵌套事件监听器

转载 作者:行者123 更新时间:2023-12-02 22:09:45 25 4
gpt4 key购买 nike

我正在构建一个文本冒险游戏,它接受用户输入并引导玩家沿着树状结构向下走。我的思考过程是让一个主要事件监听器监听将启动游戏的提交操作。然后,我根据初始响应继续添加另一个事件监听器,但没有任何反应。

嵌套事件监听器是处理这种情况的正确方法吗?

//prompts
const bed = 'Your lack of desire has lead you towards a life of bordeom and dread. [[GAME OVER]]'.split('');
const explore = 'As your eyes adjust to the early monning sun, you glance around the room. To your left, you notice a small, but sturdy bed side table. In front of you, a TV is broadcasting re-runs of the show "Friends". You also consider walking and exploring more of this strange room.What is your next inclination?'.split('')
const walkAroundRoom = 'Walking around the room seems like a good idea. After all, you tell yourself, "I should at least aquainte and introduce myself to this bewildering experience. After a bit of pondering and wandering, you look straight ahead and notice a bathroom. To your right, a window.'.split('')

submit.addEventListener('submit', () => {
if (response('bed')) {
go(bed)
} else if (response('ex')) {
go(explore)

submit.addEventListener('submit',()=>{
if(response('tv')){
go(watchTV)
} else if(response('walk')){
go(walkAroundRoom)
}
})
}
})

最佳答案

我将使用一个对象,其键唯一标识一组文本,值包含要显示的文本以及每个可能的响应将指向的提示键。这样,您只需添加一个监听器:

const prompts = {
wake: {
text: 'You wake, enter "walk" or "explore"',
responses: { walk: 'wake_walk', explore: 'wake_explore' }
},
wake_explore: {
text: 'You explore after waking. Enter "walk" to walk',
responses: { walk: 'wake_walk' }
},
wake_walk: {
text: 'You walk. Enter "walk" to continue walking, or "sleep" to go back to sleep',
responses: { walk: 'wake_walk', sleep: 'sleep' }
},
sleep: {
text: 'You sleep.',
responses: {}
}
};

const [div, input, button, errors] = document.querySelectorAll('div, input, button');
let lastResponses;
const displayPrompt = ({ text, responses }) => {
div.textContent = text;
lastResponses = responses;
};
displayPrompt(prompts.wake);

button.addEventListener('click', () => {
const nextPrompt = prompts[lastResponses[input.value]];
if (nextPrompt) {
displayPrompt(nextPrompt);
errors.textContent = '';
} else {
errors.textContent = 'Action not possible now';
}
input.value = '';
});
<div></div>
<input>
<button>submit</button>
<div></div>

半永久的lastResponses用于保存最后一个响应对象,以便可以在不同的情况下输入相同的操作,同时指向不同的提示键。 (例如,您可以在起床后行走,也可以在街上行走,并且这些 Action 不会发生碰撞)

关于javascript - 如何在js中实现嵌套事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59596949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com