暂停处理
游戏业务逻辑是与React组件联系比较紧的。
暂停处理的React组件如下所示:
import React from 'react';
import './Pause.scss';
import * as MiniGame from '../../miniGame';
//only div
const s={
toast:'pauseToast',
toastOrigin:'toast',
pause:'pause',
pauseButton:'pauseButton'
}
let stylePause={
borderLeft:'10px solid white',
borderRight:'10px solid white',
display:'inline',
position:'absolute',
left:'6%',
top:'12%',
width:'auto',
height:'auto',
color:'transparent',
cursor:'pointer',
zIndex:'1000'
}
class Pause extends React.Component{
constructor(props){
super(props);
this.state={
value:'',
display:'none'
};
this.handleClick=this.handleClick.bind(this);
}
componentWillMount(){
}
componentDidMount(){
//window.onblur=MiniGame.windowOnBlur(this);
//window.onfocus=MiniGame.windowOnFocus(this);
console.log('work');
//document.addEventListener('blur', ()=>{MiniGame.windowOnBlur(this)} );
window.onblur=()=>{
//console.log(this); if you don't use arrow function ,then this -> window
//now this -> Pause object -- a React Component
MiniGame.windowOnBlur(this);
}
window.onfocus=()=>{
MiniGame.windowOnFocus(this);
}
}
handleClick(){
MiniGame.pauseToastClickHandler(this);
}
render(){
const display=this.state.display;
return(
<div>
<div className={s.toast+' '+s.toastOrigin}
onClick={
this.handleClick}
style={
{display:display}}>
<p className={s.pause}>{
this.props.pause.info}</p>
<p>{
this.props.pause.start}</p>
</div>
<span style={stylePause}
onClick={
this.handleClick}>|</span>
</div>
);
}
}
export default Pause;
可以看到主要是使用内联样式来显示这个组件,在componentDidMount即组件渲染完成后绑定了
window.onblur 和window.onfocus两个事件,
事件处理函数windowOnBlur和windowOnFocus在游戏逻辑中定义,所以其实我们尽量让View的逻辑轻。
同时也有一个暂停按钮用于恢复或暂停游戏。
处理函数:
pauseToastClickHandler=function(that){
togglePaused(that);
}
// 离开浏览器 失去焦点时触发
function windowOnBlur(that){
// console.log(loading,gameOver,game.paused);
if(!loading && !gameOver&& !game.paused){
togglePaused(that);
let displayx=game.paused?'inline':'none';
that.setState({
display:displayx
});
}
//console.log('sss');
}
function windowOnFocus(that){
if(game.paused&&!gameOver){
togglePaused(that);