Skip to content

Commit

Permalink
Merge pull request #10 from IRLL/key_input
Browse files Browse the repository at this point in the history
Fix the keyboard input
  • Loading branch information
NickNissen authored Jan 21, 2021
2 parents 1d0ffe0 + 4c2f5fc commit b44a7f3
Showing 1 changed file with 18 additions and 22 deletions.
40 changes: 18 additions & 22 deletions src/components/Game/game.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@ class Game extends React.Component{
isVisible : false,
UIlist : [],
progress : 0,
allData : null,
inputBudget : 0,
usedInputBudget : 0,
receiveData : null,
isPause : false,
displayData : null,
inMessage : [],
outMessage : []
outMessage : [],
holdKey : null
}

componentDidMount() {
Expand All @@ -49,22 +49,6 @@ class Game extends React.Component{
},1000)
}

//Running a check every 1/100 second(10 millisecond)
//If allData is not null then send the message
//otherwise just wait until next checking
this.sendData = setInterval(() => {
if(this.state.allData && this.state.isConnection){
this.websocket.send(JSON.stringify(this.state.allData));
//record every message send to the server
if(DEBUG){
this.setState(prevState => ({
outMessage : [prevState.allData,...prevState.outMessage],
}))
}
this.setState(({allData : null}));
}
}, 10);

//To update the progress of loading game content
//Since we always need to wait 30 seconds before the game
//content get loaded, we update the progress (100/30) per second
Expand Down Expand Up @@ -164,13 +148,27 @@ class Game extends React.Component{
}

if(this.state.UIlist.includes(dataToSend.action)){
if(this.state.holdKey !== dataToSend.actionType){
this.setState(({holdKey : dataToSend.actionType}));
this.sendMessage(dataToSend);
}
}
})

document.addEventListener('keyup', (event) => {
//Used to prevent arrow keys and space key from scrolling the page
let dataToSend = getKeyInput(event.code);
if(this.state.UIlist.includes(dataToSend.action)){
dataToSend.action = 'noop';
if(this.state.holdKey === dataToSend.actionType){
this.setState({holdKey : null});
}
this.sendMessage(dataToSend);
}
})
}

componentWillUnmount() {
clearInterval(this.sendData);
if(this.setInMessage) clearInterval(this.setInMessage);
}

Expand Down Expand Up @@ -199,9 +197,7 @@ class Game extends React.Component{
frameCount : this.state.frameCount,
frameId : this.state.frameId
}
this.setState(({
allData : allData
}))
this.websocket.send(JSON.stringify(allData));
}
}

Expand Down

0 comments on commit b44a7f3

Please sign in to comment.