Skip to content

Commit

Permalink
Merge pull request #96 from nittre/feature_socketConnection
Browse files Browse the repository at this point in the history
Feature socket connection
  • Loading branch information
yoon-jisung authored May 6, 2021
2 parents 8f71dc1 + a204c93 commit 501b337
Show file tree
Hide file tree
Showing 4 changed files with 213 additions and 50 deletions.
73 changes: 27 additions & 46 deletions src/GamePages/InGame.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useState, useEffect, useRef } from 'react';
import Canvas from './components/Canvas3';
import ListnerCanvas from './components/ListnerCanvas';
import Timer from './components/Timer';
import User from './components/User';
import BackBtn from './components/BackBtn';
Expand All @@ -11,8 +12,10 @@ import GameStartBtn from './components/GameStartBtn';
import Words from '../Words';
import GameOver from './components/IsInGameMsg';
import { useHistory } from 'react-router-dom';
import Board from './components/Canvas';
import Logo from './components/Logo';


const socket = io.connect('http://localhost:4000', {
transports: ['websocket', 'polling'],
path: '/socket.io',
Expand Down Expand Up @@ -82,14 +85,12 @@ export default function InGame({ accessToken, isLogIn, loginCheck, userInfo }) {
};

const handleGameStart = () => {
if (minutes === 0 && seconds === 0) {
startRound();
// setMinutes(1); // 시간 다시 설정
// setIsTrueTimer(true); // Timer 다시 돌아감
SetIsOpen(true);
// RandomItem();
// setIsInGame(false);
}
startRound();
// setMinutes(1); // 시간 다시 설정
// setIsTrueTimer(true); // Timer 다시 돌아감
SetIsOpen(true);
// RandomItem();
// setIsInGame(false);
};

const handleAnswer = (word) => {
Expand Down Expand Up @@ -119,16 +120,14 @@ export default function InGame({ accessToken, isLogIn, loginCheck, userInfo }) {
};

const startRound = () => {
// setIsPresenter(false);
// setPresenter({ nickname: '', id: '' });
setWinner([]);
setAnswer('');
setIsPresenter(false);
socket.emit('start round');
SetIsOpen(true);
RandomItem();
socket.on('set presenter', (presenter) => {
setPresenter(presenter);
if (presenter.nickname === state.name) {
setIsPresenter(true);
}
});
};

const SetAnswer = (answer) => {
Expand All @@ -141,33 +140,6 @@ export default function InGame({ accessToken, isLogIn, loginCheck, userInfo }) {

//! --------------------------method--------------------------

useEffect(() => {}, [minutes, seconds, isTrueTimer]);
// useEffect(() => {
// loginCheck(isLogIn);
// });

// useEffect(() => {
// if (isTrueTimer) {
// const countdown = setInterval(() => {
// if (parseInt(seconds) > 0) {
// setSeconds(parseInt(seconds) - 1);
// }
// if (parseInt(seconds) === 0) {
// if (parseInt(minutes) === 0) {
// clearInterval(countdown);
// handleResult();
// } else {
// setMinutes(parseInt(minutes) - 1);
// setSeconds(59);
// }
// }
// }, 1000);
// return () => {
// clearInterval(countdown);
// };
// }
// }, [minutes, seconds, isTrueTimer]);

useEffect(() => {
// * 메세지
socketRef.current = socket;
Expand All @@ -183,6 +155,12 @@ export default function InGame({ accessToken, isLogIn, loginCheck, userInfo }) {
}, [answer]);

useEffect(() => {
socket.on('set presenter', (presenter) => {
setPresenter(presenter);
if (presenter.id === userInfo.id) {
setIsPresenter(true);
}
});
// answer를 전달받는다
socket.on('get answer', (answer) => {
setAnswer(answer);
Expand Down Expand Up @@ -223,11 +201,13 @@ export default function InGame({ accessToken, isLogIn, loginCheck, userInfo }) {

useEffect(() => {
// * 결과창이 열리고 서버에 라운드가 종료메세지 보냄 , 일정 시간이 지나면 결과창 닫히고 다시 게임 시작
const closeResult = setTimeout(() => setResultPopup(false), 3000);
setChat([]);
if (presenter.nickname === state.name) {
startRound();
}
const closeResult = setTimeout(() => {
setResultPopup(false);
setChat([]);
if (presenter.id === userInfo.id) {
startRound();
}
}, 3000);
}, [resultPopup]);

return (
Expand All @@ -236,6 +216,7 @@ export default function InGame({ accessToken, isLogIn, loginCheck, userInfo }) {
<div className="GameWindow">
<div className="canvasBox">
<div className="result_box">
<Board />
<Logo />
<Canvas className="canvas" />
{isPresenter ? (
Expand Down
172 changes: 172 additions & 0 deletions src/GamePages/components/Canvas.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import React, { useRef, useEffect } from 'react';
import io from 'socket.io-client';
// import './styles/board.css';

const Board = () => {
const canvasRef = useRef(null);
const colorsRef = useRef(null);
const socketRef = useRef();

useEffect(() => {
// --------------- getContext() method returns a drawing context on the canvas-----

const canvas = canvasRef.current;
const test = colorsRef.current;
const context = canvas.getContext('2d');

// ----------------------- Colors --------------------------------------------------

const colors = document.getElementsByClassName('color');
console.log(colors, 'the colors');
console.log(test);
// set the current color
const current = {
color: 'black',
};

// helper that will update the current color
const onColorUpdate = (e) => {
current.color = e.target.className.split(' ')[1];
};

// loop through the color elements and add the click event listeners
for (let i = 0; i < colors.length; i++) {
colors[i].addEventListener('click', onColorUpdate, false);
}
let drawing = false;

// ------------------------------- create the drawing ----------------------------

const drawLine = (x0, y0, x1, y1, color, emit) => {
context.beginPath();
context.moveTo(x0, y0);
context.lineTo(x1, y1);
context.strokeStyle = color;
context.lineWidth = 2;
context.stroke();
context.closePath();

if (!emit) {
return;
}
const w = canvas.width;
const h = canvas.height;

socketRef.current.emit('drawing', {
x0: x0 / w,
y0: y0 / h,
x1: x1 / w,
y1: y1 / h,
color,
});
};

// ---------------- mouse movement --------------------------------------

const onMouseDown = (e) => {
drawing = true;
current.x = e.clientX || e.touches[0].clientX;
current.y = e.clientY || e.touches[0].clientY;
};

const onMouseMove = (e) => {
if (!drawing) {
return;
}
drawLine(
current.x,
current.y,
e.clientX || e.touches[0].clientX,
e.clientY || e.touches[0].clientY,
current.color,
true
);
current.x = e.clientX || e.touches[0].clientX;
current.y = e.clientY || e.touches[0].clientY;
};

const onMouseUp = (e) => {
if (!drawing) {
return;
}
drawing = false;
drawLine(
current.x,
current.y,
e.clientX || e.touches[0].clientX,
e.clientY || e.touches[0].clientY,
current.color,
true
);
};

// ----------- limit the number of events per second -----------------------

const throttle = (callback, delay) => {
let previousCall = new Date().getTime();
return function () {
const time = new Date().getTime();

if (time - previousCall >= delay) {
previousCall = time;
callback.apply(null, arguments);
}
};
};

// -----------------add event listeners to our canvas ----------------------

canvas.addEventListener('mousedown', onMouseDown, false);
canvas.addEventListener('mouseup', onMouseUp, false);
canvas.addEventListener('mouseout', onMouseUp, false);
canvas.addEventListener('mousemove', throttle(onMouseMove, 10), false);

// Touch support for mobile devices
canvas.addEventListener('touchstart', onMouseDown, false);
canvas.addEventListener('touchend', onMouseUp, false);
canvas.addEventListener('touchcancel', onMouseUp, false);
canvas.addEventListener('touchmove', throttle(onMouseMove, 10), false);

// -------------- make the canvas fill its parent component -----------------

const onResize = () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};

window.addEventListener('resize', onResize, false);
onResize();

// ----------------------- socket.io connection ----------------------------
const onDrawingEvent = (data) => {
console.log('onDrawingEvent');
const w = canvas.width;
const h = canvas.height;
drawLine(data.x0 * w, data.y0 * h, data.x1 * w, data.y1 * h, data.color);
};

socketRef.current = io.connect('http://localhost:4000', {
transports: ['websocket', 'polling'],
path: '/socket.io',
});
socketRef.current.on('drawing', onDrawingEvent);
}, []);

// ------------- The Canvas and color elements --------------------------

return (
<div>
<canvas ref={canvasRef} className="WhiteBoard" />

<div ref={colorsRef} className="colors">
<div className="color black" />
<div className="color red" />
<div className="color green" />
<div className="color blue" />
<div className="color yellow" />
</div>
</div>
);
};

export default Board;
16 changes: 14 additions & 2 deletions src/GamePages/components/Canvas3.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const socket = io.connect('http://localhost:4000', {
path: '/socket.io',
});

export default function Canvas3({ Round }) {
export default function Canvas3() {
const canvasRef = useRef(null);
const contextRef = useRef(null);
const [canvas, setCanvas] = useState(undefined);
Expand All @@ -40,36 +40,46 @@ export default function Canvas3({ Round }) {
}, []);

const startDrawing = ({ nativeEvent }) => {
console.log('start drawing');
const { offsetX, offsetY } = nativeEvent;
contextRef.current.beginPath();
contextRef.current.moveTo(offsetX, offsetY);
setIsDrawing(true);
socket.emit('start drawing', offsetX, offsetY);
};

const finishDrawing = () => {
console.log('finish drawing');
contextRef.current.closePath();
setIsDrawing(false);
ctx.lineWidth = 5;
// ctx.lineWidth = 5;
socket.emit('finish drawing');
};

const draw = ({ nativeEvent }) => {
console.log('draw');
if (!isDrawing) return;
const { offsetX, offsetY } = nativeEvent;
contextRef.current.lineTo(offsetX, offsetY);
// ! 소켓
contextRef.current.stroke();

socket.emit('draw', offsetX, offsetY);
};

const reset = () => {
if (ctx) {
ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
socket.emit('reset');
}
};

const eraserBtn = (e) => {
setCursor({ cursor: `url(${Eraser}), pointer` });
ctx.lineWidth = 20;
ctx.strokeStyle = 'white';

socket.emit('erase');
};

const handleColorClick = (e) => {
Expand Down Expand Up @@ -98,6 +108,8 @@ export default function Canvas3({ Round }) {
setCursor({ cursor: `url(${Crayon_Black}), pointer` });
break;
}

socket.on('color', e.target.textContent);
};

useEffect(() => {
Expand Down
2 changes: 0 additions & 2 deletions src/GamePages/components/Chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ export default function Chat({
state,
renderChat,
}) {
console.log(chat);

return (
<div className="card">
<div className="render-chat">
Expand Down

0 comments on commit 501b337

Please sign in to comment.