Commit dfc0f826 authored by 18손재민's avatar 18손재민

Merge branch 'wordspace' into release

parents 22c3f8fa 9c3f21f8
var GameServer = GameServer || {};
GameServer.serverNumber = -1;
GameServer.Phase = {READY: 0, COUNT: -1, START: 1, MAIN: 2, MUSIC: 3};
GameServer.connectCount = 0;
GameServer.disconnectCount = 0;
GameServer.currentPlayer = [];
GameServer.playingRoom = [];
......@@ -70,14 +74,13 @@ GameServer.getRoomNumber = function()
} while (true)
}
class GameRoom
{
constructor()
{
this.roomId = GameServer.getRoomNumber();
this.roomIndex = -1;
this.startCount = 2;
this.startCount = 5;
this.maxPlayer = 100;
this.nextRank = 100;
......@@ -133,7 +136,7 @@ class GameRoom
{
if (this.currentPhase === GameServer.Phase.READY)
{
this.endTime = Date.now() + 5000; // 테스트용 10초
this.endTime = Date.now() + 1000; // 테스트용 10초
this.announceToRoom('setRoomCount',
{
isEnable: true, endTime: this.endTime, playerCount: this.currentPlayer.length,
......@@ -201,7 +204,6 @@ class GameRoom
this.announceToRoom('syncRoomData', toSync);
console.log('[ROOM#'+this.roomId+'] Game Start with ' + this.currentPlayer.length + ' players');
this.announceToRoom('changePhase', GameServer.Phase.START);
this.announceToRoom('startGame');
this.startTime = Date.now();
}
......@@ -210,9 +212,10 @@ class GameRoom
{
if (this.currentPhase === GameServer.Phase.START)
{
if (this.phaseChanger < 0 && checkTime - this.startTime > 60000)
if (this.phaseChanger < 0 && checkTime - this.startTime > 6000)
{
this.currentPhase = GameServer.Phase.MAIN;
this.rateArrangePoint = 150;
this.announceToRoom('changePhase', GameServer.Phase.MAIN);
}
else if (this.phaseChanger < 0)
......@@ -220,6 +223,7 @@ class GameRoom
this.phaseChanger = setTimeout(function(room)
{
room.currentPhase = GameServer.Phase.MAIN;
room.rateArrangePoint = 150;
room.announceToRoom('changePhase', GameServer.Phase.MAIN);
room.phaseChanger = -1;
}, 60000 - (checkTime - this.startTime), this);
......@@ -227,10 +231,11 @@ class GameRoom
}
else if (this.currentPhase === GameServer.Phase.MAIN)
{
let playerLimit = Math.max(this.currentPlayer.length / 10, 3);
let playerLimit = Math.min(Math.round(this.currentPlayer.length / 5), 3);
if (this.aliveCount <= playerLimit)
{
this.currentPhase = GameServer.Phase.MUSIC;
this.rateArrangePoint = 50;
this.announceToRoom('changePhase', GameServer.Phase.MUSIC);
}
}
......@@ -287,12 +292,14 @@ class Player
this.gameRoomId = gameRoom.roomId;
this.index = gameRoom.currentPlayer.length;
this.nickname = playerData.nickname;
this.playerImage = null;
this.position = null;
this.isAlive = true;
this.rank = -1;
this.playerTyping = 0;
this.lastAttacks = []; // { attackerId, word, wordGrade, time }
this.lastAttacks = []; // { attackerId, attacker, wrongCount, word, wordGrade, time }
this.lastAttack = null;
}
......@@ -312,18 +319,22 @@ class Player
if (this.lastAttacks.length > 0)
{
this.lastAttack = this.lastAttacks[this.lastAttacks.length - 1];
if (Date.now() - this.lastAttack.time > 40000) this.lastAttack = null;
if (Date.now() - this.lastAttack.time > 20000) this.lastAttack = null;
else
{
this.lastAttacks.forEach(function(element)
{
if (Date.now() - element.time < 40000 && element.wordGrade > player.lastAttack.wordGrade) player.lastAttack = element;
if (Date.now() - element.time < 20000)
{
if (element.wrongCount > player.lastAttack.wrongCount) player.lastAttack = element;
else if (element.wrongCount === player.lastAttack.wrongCount && element.wordGrade > player.lastAttack.wordGrade) player.lastAttack = element;
}
});
}
}
room.announceToRoom('defeat', this);
console.log('[' + this.id + '] defeated, rank: ' + this.rank + ', ' + room.currentPlayer.length + 'player left');
console.log('[' + this.id + '] defeated, rank: ' + this.rank + ', ' + room.aliveCount + ' player left');
if (socket.playerData.currentRoom.aliveCount === 1)
{
......
No preview for this file type
......@@ -15,9 +15,47 @@
<script src="js/SelectWord.js"></script>
<script src="js/BGMsound.js"></script>
<script src="js/Enums.js"></script>
<script src="js/ResourceLoader.js"></script>
<script src="js/UIObject.js"></script>
<style>
img { position: relative; width: 100%; height: 100%; z-index: 0;}
#dvLogin { position: absolute; left: 65%; top: 35%; width: 30%; height: 30%; padding: 10px; background: black; z-index: 1;}
</style>
</head>
<body>
<div id="mainTitle">
<img id="titleImg" src="assets/image/background/title.png" alt="title">
<div id="dvLogin">
<input id="userEmail" type="email" placeholder="email" style="width: 100%; height: 10%;"></br>
<input id="userPassword" type="password" placeholder="password" maxlength="17" style="width: 100%; height: 10%;"></br>
<button id="joinBtn" style="width: 100%; height: 10%;">이메일로 가입하기</button></br>
<button id="emailBtn" style="width: 100%; height: 10%;">이메일로 로그인</button></br>
<button id="googleBtn" style="width: 10%; height: 10%;"><img src="assets/title/googleBtn.png" style="object-fit: contain"></button></br>
</div>
</div>
<script src="https://www.gstatic.com/firebasejs/6.3.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.10.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.10.1/firebase-database.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyCJIQjnJyQg54MRAmIzKVanYyiLNq628rI",
authDomain: "sejongio.firebaseapp.com",
databaseURL: "https://sejongio.firebaseio.com",
projectId: "sejongio",
storageBucket: "sejongio.appspot.com",
messagingSenderId: "57247216553",
appId: "1:57247216553:web:faa4183e9b0a2614"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
<script src="js/Client.js"></script>
<script src="js/Main.js"></script>
<script src="js/FirebaseClient.js"></script>
</body>
</html>
\ No newline at end of file
......@@ -5,6 +5,8 @@ Audio.loadSound = function(scene)
{
scene.load.audio('login', 'assets/sound/login.ogg');
scene.load.audio('startGame', 'assets/sound/startGame.ogg');
scene.load.audio('attack', 'assets/sound/attackShort.ogg');
scene.load.audio('inRoom', 'assets/sound/roomBGM.ogg');
}
Audio.playSound = function(scene, title) // 한 번만 재생할 때 사용
......
var BackGround = BackGround || {}
BackGround.brainGroup = null;
BackGround.myCharacter = null;
BackGround.characterPos = [
new Phaser.Math.Vector2(100, 99), new Phaser.Math.Vector2(248, 198), new Phaser.Math.Vector2(412, 144), new Phaser.Math.Vector2(124, 393),
new Phaser.Math.Vector2(368, 336), new Phaser.Math.Vector2(272, 453), new Phaser.Math.Vector2(100, 595), new Phaser.Math.Vector2(284, 678),
new Phaser.Math.Vector2(444, 639), new Phaser.Math.Vector2(116, 799), new Phaser.Math.Vector2(413, 789), new Phaser.Math.Vector2(280, 916),
new Phaser.Math.Vector2(1437, 157), new Phaser.Math.Vector2(1672, 95), new Phaser.Math.Vector2(1832, 166), new Phaser.Math.Vector2(1581, 239),
new Phaser.Math.Vector2(1779, 311), new Phaser.Math.Vector2(1595, 414), new Phaser.Math.Vector2(1774, 480), new Phaser.Math.Vector2(1501, 563),
new Phaser.Math.Vector2(1736, 655), new Phaser.Math.Vector2(1446, 770), new Phaser.Math.Vector2(1656, 894), new Phaser.Math.Vector2(1826, 819),
]
BackGround.otherCharacters = [];
BackGround.loadImage = function(scene)
BackGround.drawCharacter = function(scene)
{
scene.load.image('brainGround', 'assets/image/background/background_brain.png');
scene.load.image('menuBackground', 'assets/placeholder/menuBackground.png');
scene.load.image('roomBackground', 'assets/placeholder/roomBackground.png');
RoomData.myself.playerImage = scene.add.sprite(game.config.width / 2, game.config.height * 41 / 48, 'pyeongminWrite').setScale(0.45).setDepth(2);
RoomData.myself.position = new Phaser.Math.Vector2(RoomData.myself.playerImage.x, RoomData.myself.playerImage.y);
BackGround.characterPos = BackGround.characterPos.sort(function(){return 0.5-Math.random()});
RoomData.players.forEach(function(element){
if(element.id != RoomData.myself.id)
{
element.position = BackGround.characterPos.pop();
element.playerImage = scene.add.sprite(element.position.x, element.position.y, 'pyeongminWrite').setScale(0.315).setDepth(1);
element.playerImage.flipX = element.position.x < game.config.width / 2 ? true : false;
element.nicknameText = scene.add.text(element.position.x, element.position.y - 90, element.nickname)
.setOrigin(0.5,0.5).setColor('#000000').setPadding(0.5,0.5,0.5,0.5).setDepth(1);
6 }
});
}
BackGround.drawCharacter = function(scene)
BackGround.gameBackground = null;
BackGround.drawBrain = function(scene)
{
BackGround.myCharacter = scene.add.sprite(640, 615, 'pyeongminWrite').setScale(0.45).setDepth(2);
BackGround.gameBackground = scene.add.sprite(game.config.width / 2, game.config.height / 2, 'gameBackground').setDisplaySize(game.config.width, game.config.height).setDepth(1);
}
BackGround.drawBrain = function(scene)
BackGround.drawBackground = function(scene)
{
brains = scene.add.sprite(640, 360, 'brainGround').setDisplaySize(1282, 722).setDepth(1);
scene.add.sprite(game.config.width / 2, game.config.height / 2, 'baseBackground').setDisplaySize(game.config.width, game.config.height).setDepth(0);
}
BackGround.drawMenu = function(scene)
{
scene.add.sprite(640, 360, 'menuBackground').setDisplaySize(1282, 722).setDepth(1);
scene.add.sprite(game.config.width / 2, game.config.height / 2, 'menuBackground').setDisplaySize(game.config.width, game.config.height).setDepth(1);
}
BackGround.drawRoom = function(scene)
{
scene.add.sprite(640, 360, 'roomBackground').setDisplaySize(1282, 722).setDepth(1);
scene.add.sprite(game.config.width / 2, game.config.height / 2, 'roomBackground').setDisplaySize(game.config.width, game.config.height).setDepth(1);
}
\ No newline at end of file
var socket = io.connect();
var serverNumber = -1;
// init account
socket.emit('idRequest');
socket.on('syncServer', function(msg)
{
if (serverNumber < 0 || serverNumber === msg)
{
socket.emit('idRequest');
serverNumber = msg;
}
else location.reload();
});
socket.on('alert', function(msg) // string errorcode
{
//let toAlert = 'null alert';
if (msg === 'errNicknameOverlaped') alert('이미 사용중인 닉네임입니다.');
if (msg === 'gameWin')
else if (msg === 'errNicknameEmpty') alert('설정된 닉네임이 없습니다.');
else if (msg === 'gameWin')
{
//toAlert = '승리!';
ScenesData.gameScene.add.text(640, 360, '승리!!!!', {fontSize: '30pt'})
ScenesData.gameScene.add.text(game.config.width / 2, game.config.height / 2, '승리!!!!', {fontSize: '30pt'})
.setPadding(5,5,5,5).setOrigin(0.5, 0.5).setDepth(11)
.setColor('#000000').setBackgroundColor('#ffffff');
gameOver();
}
//alert(toAlert);
});
......@@ -22,12 +34,13 @@ socket.on('setId', function(msg) // {str, num playerNum}
console.log(msg.str);
PlayerData.id = msg.num;
});
// init game
socket.on('enterRoom', function()
{
fbClient.updateUserData('recentHopae', PlayerData.currentHopae);
Audio.killSound(ScenesData.menuScene, 'login');
game.scene.remove('menuScene');
game.scene.start('roomScene');
ScenesData.changeScene('roomScene');
});
socket.on('syncRoomScene', function(msg)
{
......@@ -55,7 +68,7 @@ socket.on('setRoomCount', function(msg)
ScenesData.roomScene.endTime = msg.endTime;
ScenesData.roomScene.peopleCount = msg.playerCount;
if (msg.isEnter) // generate charactor
if (msg.isEnter) // generate character
{
let randX = Math.random() * 1120 + 80;
let randY = Math.random() * 380 + 100;
......@@ -67,7 +80,7 @@ socket.on('setRoomCount', function(msg)
}
ScenesData.roomScene.players.push(playerSet);
}
else // remove charactor
else // remove character
{
let idx = ScenesData.roomScene.players.findIndex(function(element)
{
......@@ -82,8 +95,6 @@ socket.on('setRoomCount', function(msg)
}
}, 200);
});
// init game
socket.on('syncRoomData', function(msg) // {num roomNum, [] players}
{
//console.log(msg);
......@@ -101,8 +112,8 @@ socket.on('syncRoomData', function(msg) // {num roomNum, [] players}
});
socket.on('startGame', function()
{
game.scene.remove('roomScene');
game.scene.start('gameScene');
Audio.killSound(ScenesData.roomScene, 'inRoom');
ScenesData.changeScene('gameScene');
});
// in game
......@@ -110,52 +121,143 @@ socket.on('changePhase', function(msg) // number Phase
{
console.log('phase changed from ' + WordSpace.CurrentPhase + ' to ' + msg);
WordSpace.CurrentPhase = msg;
WordSpace.pauseCycle(true);
// 여기서 종이 드르륵 열면됨
let phaseChangeBgr = ScenesData.gameScene.add.sprite(game.config.width / 2, game.config.height / 2, 'phaseChangeBgr').setOrigin(0.5, 0.5).setDepth(10);
ScenesData.gameScene.scene.pause('gameScene');
setTimeout(function()
{
ScenesData.gameScene.scene.resume('gameScene');
// 여기서 종이 닫으면됨
phaseChangeBgr.destroy();
Audio.playSound(ScenesData.gameScene, 'startGame');
WordSpace.pauseCycle(false);
//console.log('start again');
}, 5000);
});
socket.on('setPlayerTypingRate', function(msg) // number playerTypingRate
{
WordSpace.PlayerTypingRate = msg;
//console.log('rate: ' + msg);
});
socket.on('writeWord', function(msg) // number playerId
{
console.log(msg + ' write word');
// msg의 id를 가진 사람이 writeWord한다.
});
socket.on('attackMode', function(msg) // number playerId
{
// if (msg's attackMode is false)
console.log(msg + ' is on attack Mode');
// msg의 id를 가진 사람이 attack Mode이다.
});
socket.on('someoneAttacked', function(msg) // {Id attackerId, Id victimId}
{
// 이때 위의 attack Mode인 사람(msg.attackerId)을 해제해주자.
console.log(msg.attackerId + ' attacked ' + msg.victimId);
let attackerPos = RoomData.findPlayer(msg.attackerId).position;
let victimPos = RoomData.findPlayer(msg.victimId).position;
WordSpace.makeAttackPaper(ScenesData.gameScene, attackerPos, victimPos, msg.multiple);
});
socket.on('attacked', function(msg) // object attackData
{
//console.log('attacked by ' + msg.attacker.nickname);
var timeout = setTimeout(function()
let attackedEvent = new Cycle(function()
{
WordSpace.generateWord.Attack(ScenesData.gameScene, msg.text, msg.grade, msg.attacker, msg.isStrong, msg.isCountable);
}, 4000);
console.log(timeout);
if(!WordSpace.isInvincible)
for (let i = 0; i < msg.multiple; i++) WordSpace.generateWord.Attack(ScenesData.gameScene, msg.text, msg.grade, RoomData.findPlayer(msg.attackerId), msg.attackOption);
attackedEvent.currentCycle.destroy();
WordSpace.attackedEvents.splice(WordSpace.attackedEvents.findIndex(function(element) {
return element.cert === (msg.text + msg.attackerId);
}), 1);
});
attackedEvent.cert = msg.text + msg.attackerId;
attackedEvent.resetCycle(ScenesData.gameScene, 4000, 0, false);
WordSpace.attackedEvents.push(attackedEvent);
//console.log(timeout);
});
socket.on('defeat', function(msg) // object player
{
let playerImage = RoomData.findPlayer(msg.id).playerImage;
let position = RoomData.findPlayer(msg.id).position;
let nicknameText = RoomData.findPlayer(msg.id).nicknameText;
RoomData.players[msg.index] = msg;
RoomData.players[msg.index].playerImage = playerImage;
RoomData.players[msg.index].position = position;
RoomData.players[msg.index].nicknameText = nicknameText;
RoomData.aliveCount--;
console.log(msg.id);
console.log(RoomData.findPlayer(msg.id));
RoomData.findPlayer(msg.id).playerImage.play(WordSpace.pyeongminAnims[Enums.characterAnim.gameOver]);
if (msg.lastAttack != null)
{
console.log(RoomData.players[msg.index].nickname + ' defeated by ' + msg.lastAttack.attacker + ', with ' + msg.lastAttack.word);
WordSpace.killLogForTest += ('\n' + msg.lastAttack.attacker + ' --' + msg.lastAttack.word + '-> ' + RoomData.players[msg.index].nickname);
let lastAttacker = RoomData.findPlayer(msg.lastAttack.attackerId).nickname;
console.log(RoomData.findPlayer(msg.id).nickname + ' defeated by ' + lastAttacker + ', with ' + msg.lastAttack.word);
WordSpace.killLogForTest += ('\n' + lastAttacker + ' --' + msg.lastAttack.word + '-> ' + RoomData.findPlayer(msg.id).nickname);
if(msg.lastAttack.attackerId == RoomData.myself.id)
{
var keys = Object.keys(Enums.item);
WordSpace.generateWord.Item(ScenesData.gameScene, Enums.item[keys[keys.length * Math.random() << 0]]);
let itemBag = ScenesData.gameScene.add.sprite(RoomData.myself.position.x, RoomData.myself.position.y, 'itemBag').setScale(0).setDepth(5);
ScenesData.gameScene.tweens.add({
targets: itemBag,
scaleX: 1,
scaleY: 1,
ease: 'Linear', // 'Cubic', 'Elastic', 'Bounce', 'Back'
duration: 500,
repeat: 0, // -1: infinity
yoyo: false,
onComplete: function () {
setTimeout(function() {
ScenesData.gameScene.tweens.add({
targets: itemBag,
scaleX: 0,
scaleY: 0,
ease: 'Linear', // 'Cubic', 'Elastic', 'Bounce', 'Back'
duration: 500,
repeat: 0, // -1: infinity
yoyo: false });
}, 1500);
},
onCompleteScope: ScenesData.gameScene
});
setTimeout(function() {
itemBag.destroy();
}, 3000);
}
}
else
{
console.log(RoomData.players[msg.index].nickname + ' defeated');
WordSpace.killLogForTest += ('\n--Suicide->' + RoomData.players[msg.index].nickname);
console.log(RoomData.findPlayer(msg.id).nickname + ' defeated');
WordSpace.killLogForTest += ('\n--Suicide->' + RoomData.findPlayer(msg.id).nickname);
}
});
socket.on('gameEnd', function(msg) // object player
{
console.log(msg.nickname + ' Win!!!!!!');
});
socket.on('attackSucceed', function(msg)
{
console.log('client');
let tempWord = WordSpace.generateWord.Name(ScenesData.gameScene, true, msg.victim);
//console.log('client');
let tempWord = WordSpace.generateWord.Name(ScenesData.gameScene, true, RoomData.findPlayer(msg.victimId));
let victimPos = RoomData.findPlayer(msg.victimId).position;
tempWord.physicsObj.setPosition(victimPos.x, victimPos.y);
tempWord.wordObj.setPosition(tempWord.physicsObj.x, tempWord.physicsObj.y);
tempWord.destroy();
});
// out game
socket.on('userDisconnect', function(msg) // {num index , num id, str nickname}
{
console.log(msg.index + ' / ' + msg.id + ' / ' + msg.nickname + ' disconnected');
//console.log(msg.index + ' / ' + msg.id + ' / ' + msg.nickname + ' disconnected');
RoomData.players[msg.index] = msg;
RoomData.aliveCount--;
});
\ No newline at end of file
var Enums = Enums || {};
Enums.characterAnim = { write: 0, attackWrite: 1, throw: 2, hit: 3 }
\ No newline at end of file
Enums.characterAnim = { sit: 0, write: 1, notBurning: 2, smallBurning: 3, bigBurning: 4, throw: 5, hit: 6, gameOver: 7 }
Enums.item = {invincible: "무적", nameList: "명단", charge: "충전", clean: "청소", heavy: "중량", dark: "암흑"}
\ No newline at end of file
function FirebaseClient()
{
this.init();
this.initEvent();
}
FirebaseClient.prototype.init = function()
{
this.auth = firebase.auth();
this.googleBtn = document.getElementById('googleBtn');
this.emailBtn = document.getElementById('emailBtn');
this.joinBtn = document.getElementById('joinBtn');
}
FirebaseClient.prototype.initEvent = function()
{
this.auth.onAuthStateChanged(this.onAuthChange.bind(this));
this.googleBtn.addEventListener('click', this.onGoogleBtnClick.bind(this));
this.emailBtn.addEventListener('click', this.onEmailBtnClick.bind(this));
this.joinBtn.addEventListener('click', this.createEmailUser.bind(this));
}
FirebaseClient.prototype.logOut = function()
{
if (confirm('Logout?'))
{
if (this.database)
{
this.database.goOffline();
}
this.auth.signOut();
}
}
FirebaseClient.prototype.onAuthChange = function(user)
{
if (user)
{
console.log('user로그인');
this.setLogin();
}
else
{
console.log('로그아웃');
this.setLogOut();
}
}
FirebaseClient.prototype.setLogin = function()
{
this.database = firebase.database();
this.database.goOnline();
var userDataRef = this.database.ref('/user-data/' + this.auth.currentUser.uid);
userDataRef.once('value').then(function(snapshot)
{
if (snapshot.exists())
{
PlayerData.userData = snapshot.val();
}
else
{
let newUserData = new UserData();
PlayerData.userData = newUserData;
userDataRef.set(newUserData);
}
})
.then(function()
{
game = new Phaser.Game(config);
});
document.getElementById('mainTitle').style.display = 'none';
document.getElementById('titleImg').style.display = 'none';
}
FirebaseClient.prototype.setLogOut = function()
{
}
FirebaseClient.prototype.onEmailBtnClick = function()
{
var email = document.getElementById('userEmail').value.trim();
var password = document.getElementById('userPassword').value.trim();
if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email) && password.length > 0)
{ // 유효성 체크
var cbSignInEmail = function()
{
return this.auth.signInWithEmailAndPassword(email, password)
.then(function()
{
console.log('이메일 로그인 성공');
})
.catch(function(error)
{
console.error('이메일 로그인 과정 에러', error);
switch(error.code)
{
case "auth/invalid-email":
alert('유효하지 않은 메일입니다');
break;
case "auth/user-disabled":
alert('사용이 정지된 유저 입니다.')
break;
case "auth/user-not-found":
alert('사용자를 찾을 수 없습니다.')
break;
case "auth/wrong-password":
alert("잘못된 패스워드 입니다.");
break;
}
});
}
this.auth.setPersistence(firebase.auth.Auth.Persistence.SESSION)
.then(cbSignInEmail.bind(this));
}
}
FirebaseClient.prototype.createEmailUser = function()
{
var email = document.getElementById('userEmail').value.trim();
var password = document.getElementById('userPassword').value.trim();
// 유효성 검증
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))
{
var cbCreateUserWithEmail = function(user){
console.log('이메일 가입 성공 : ', JSON.stringify(user));
//프로필 업데이트 - 이메일 가입시 유저이름 파라미터를 보내지 않으므로 가입 성공 후 처리
firebase.auth().currentUser.updateProfile({
displayName: email,
}).then(function() {
console.log('userName 업데이트 성공')
}).catch(function(error) {
console.error('userName 업데이트 실패 : ', error );
});
/*
//인증 메일 발송
this.auth.useDeviceLanguage(); // 이메일 기기언어로 세팅
user.sendEmailVerification().then(function() {
console.log('인증메일 발송 성공')
}).catch(function(error) {
console.error('인증메일 발송 에러', error);
});*/
}
var cbAfterPersistence = function(){
return this.auth.createUserWithEmailAndPassword(email, password)
.then(cbCreateUserWithEmail.bind(this))
.catch(function(error) {
console.error('이메일 가입시 에러 : ', error);
switch(error.code){
case "auth/email-already-in-use":
alert('이미 사용중인 이메일 입니다.');
break;
case "auth/invalid-email":
alert('유효하지 않은 메일입니다');
break;
case "auth/operation-not-allowed":
alert('이메일 가입이 중지되었습니다.');
break;
case "auth/weak-password":
alert("비밀번호를 6자리 이상 필요합니다");
break;
}
});
}
this.auth.setPersistence(firebase.auth.Auth.Persistence.SESSION)
.then(cbAfterPersistence.bind(this))
.catch(function(error) {
console.error('인증 상태 설정 중 에러 발생' , error);
});
}
}
FirebaseClient.prototype.onGoogleBtnClick = function()
{
var googleProvider = new firebase.auth.GoogleAuthProvider();
this.auth.setPersistence(firebase.auth.Auth.Persistence.SESSION)
.then(this.signInWithPopup.bind(this, googleProvider))
.catch(function(error)
{
console.error('인증 상태 설정 중 에러 발생', error);
});
}
FirebaseClient.prototype.signInWithPopup = function(provider)
{
return this.auth.signInWithPopup(provider).then(function(result)
{
console.log('로그인 성공')
}).catch(function(error)
{
alert('로그인에 실패하였습니다');
console.error('로그인 에러',error);
});
}
FirebaseClient.prototype.updateUserData = function(key, valueChanged, replace = false)
{
var beforeData = PlayerData.userData;
switch(key)
{
case 'exp':
beforeData.exp = replace ? (valueChanged) : (beforeData.exp + valueChanged);
break;
case 'rank':
beforeData.rank = replace ? (valueChanged) : (beforeData.rank + valueChanged);
break;
case 'hopae':
if (beforeData.hopae != null) beforeData.hopae.push(valueChanged);
else beforeData.hopae = [valueChanged];
break;
case 'recentHopae':
beforeData.recentHopae = valueChanged;
break;
case 'title':
if (beforeData.title != null) beforeData.title.push(valueChanged);
else beforeData.title = [valueChanged];
break;
case 'money':
beforeData.money = replace ? (valueChanged) : (beforeData.money + valueChanged);;
break;
case 'item':
if (beforeData.item != null) beforeData.item.push(valueChanged);
else beforeData.item = [valueChanged];
break;
default:
console.log('[ERROR] database has no key for ' + key);
break;
}
PlayerData.userData = beforeData;
return this.database.ref('/user-data/' + this.auth.currentUser.uid).update(beforeData);
}
document.addEventListener('DOMContentLoaded', function()
{
window.fbClient = new FirebaseClient();
console.log('done load');
});
class UserData
{
constructor()
{
this.userName = prompt("유저의 이름을 입력해주세요.");
this.exp = 0;
this.rank = -1;
this.hopae =
[
{name: prompt("첫번째 호패의 닉네임을 입력해주세요.\n(반드시 한글만 사용해주세요 띄어쓰기도 금지)"), type: 'wood'}
];
this.recentHopae = null;
this.title = [];
this.money = 0;
this.item = [];
}
}
\ No newline at end of file
......@@ -3,10 +3,7 @@ WordSpace.startCycle = function(scene)
WordSpace.wordCycle.resetCycle(scene, 3000, 0, true);
WordSpace.nameCycle.resetCycle(scene, 3000, 0, true);
WordSpace.varAdjustCycle.resetCycle(scene, 100, 0, true);
WordSpace.playerTypingCycle = setInterval(function()
{
socket.emit('setPlayerTyping', WordSpace.playerTyping);
}, 500);
WordSpace.playerTypingCycle.resetCycle(scene, 500, 500, true);
}
WordSpace.pauseCycle = function(isPause)
......@@ -15,11 +12,8 @@ WordSpace.pauseCycle = function(isPause)
WordSpace.nameCycle.currentCycle.paused = isPause;
WordSpace.varAdjustCycle.currentCycle.paused = isPause;
WordSpace.attackGauge.pauseCycle(isPause);
if (isPause) clearInterval(WordSpace.playerTypingCycle);
else WordSpace.playerTypingCycle = setInterval(function()
{
socket.emit('setPlayerTyping', WordSpace.playerTyping);
}, 500);
WordSpace.playerTypingCycle.currentCycle.paused = isPause;
WordSpace.attackedEvents.forEach(function(element) {element.currentCycle.paused = isPause});
}
class Cycle //앞으로 cycle은 이 클래스를 사용해서 구현할 것
......@@ -65,4 +59,12 @@ WordSpace.varAdjustCycle = new Cycle(function()
//WordSpace.GetPhase();
//WordSpace.GetPlayerTypingRate();
WordSpace.AdjustVarByPhase(WordSpace.playerTypingRate, WordSpace.CurrentPhase);
});
\ No newline at end of file
});
// playerTypingRate 갱신용 사이클
WordSpace.playerTypingCycle = new Cycle(function()
{
socket.emit('setPlayerTyping', {playerTyping: WordSpace.playerTyping, isWord: WordSpace.setPlayerTyping.writeWord, isAttackMode: Input.attackMode} );
WordSpace.setPlayerTyping.writeWord = false;
});
// 공격받을때의 일회용 이벤트들
WordSpace.attackedEvents = [];
\ No newline at end of file
......@@ -12,7 +12,12 @@ Input.justPressed = '';
Input.maxInput = 6;
Input.attackMode = false;
Input.attackOption = null;
Input.attackOption = {
wordCount: 0,
wordGrade: 0,
isHeavy: false,
isDark: false
};
Input.gameSceneEnterReaction = function()
{
......@@ -29,7 +34,6 @@ Input.menuSceneEnterReaction = function()
Input.finalInput = Input.removeConVow(Input.finalInput);
if (Input.finalInput.length > 1)
{
socket.emit('setNickname', Input.finalInput);
PlayerData.nickname = Input.finalInput;
Input.reset();
}
......@@ -314,12 +318,17 @@ Input.removeConVow = function(_wordText)
Input.inputField =
{
generate: function(scene, enterCallback)
generate: function(scene, enterCallback, text, isHopaeScene = false)
{
this.background = scene.add.sprite(640, 500, 'inputfield').setDepth(10);
this.text = scene.add.text(640, 500, "", {font: '25pt 궁서'}).setOrigin(0.5, 0.5).setColor('#000000').setDepth(10);
this.text = text;
scene.input.keyboard.on('keyup', function() {Input.pressCount--; Input.justPressed = ''})
scene.input.keyboard.on('keyup', function() {Input.pressCount--; Input.justPressed = '';
if(isHopaeScene)
{
ScenesData.hopaeScene.checkBtn.setEnable(Input.checkProperInput(Input.inputField.text.text) ? true : false);
if(Input.finalInput.length > 4) ScenesData.hopaeScene.warningText.setVisible(true);
else ScenesData.hopaeScene.warningText.setVisible(false);
}})
scene.input.keyboard.on('keydown-SHIFT', function() {Input.isShifted = true});
scene.input.keyboard.on('keyup-SHIFT', function() {Input.isShifted = false});
scene.input.keyboard.on('keydown-DELETE', function() {Input.reset()});
......@@ -370,10 +379,6 @@ Input.inputField =
scene.input.keyboard.on('keydown-B', function() {Input.pushInput('')});
scene.input.keyboard.on('keydown-N', function() {Input.pushInput('')});
scene.input.keyboard.on('keydown-M', function() {Input.pushInput('')});
},
loadImage: function(scene)
{
scene.load.image('inputfield', 'assets/placeholder/inputfield.png');
}
}
......
var ResourceLoader = ResourceLoader || {};
ResourceLoader.loadBackGround = function(scene)
{
scene.load.image('brain', 'assets/image/background/brain.png');
scene.load.image('baseBackground', 'assets/image/background/yellowBack.png');
scene.load.image('gameBackground', 'assets/image/background/background_brain.png');
scene.load.image('menuBackground', 'assets/placeholder/menuBackground.png');
scene.load.image('roomBackground', 'assets/placeholder/roomBackground.png');
}
ResourceLoader.loadImage = function(scene)
{
scene.load.image('inputfield', 'assets/image/etc/wordspace.png');
for (let i = 0; i < 4; i++)
{
for (let j = 2; j < 7; j++)
{
scene.load.image(('wordBgr' + i + '_' + j), ('assets/image/word/'+i + '_' + j + '.png'));
}
}
for (let i = 0; i < 4; i++)
{
scene.load.image('attackAlert' + i, 'assets/placeholder/attackalert' + (i+1) + '.png');
}
for (let i = 0; i < 6; i++)
{
scene.load.image('item' + i, 'assets/placeholder/item' + i + '.png');
}
for (let i = 2; i < 7; i++)
{
scene.load.image('nameBgr' + i, 'assets/image/word/name' + i + '.png');
scene.load.image('strongBgr' + i, 'assets/image/word/strong' + i + '.png');
}
scene.load.spritesheet('pyeongminSit', 'assets/image/character/pyeongmin/pyeong_sit.png', { frameWidth: 521, frameHeight: 610 });
scene.load.spritesheet('pyeongminWrite', 'assets/image/character/pyeongmin/write/pyeong_write.png', { frameWidth: 521, frameHeight: 610 });
scene.load.spritesheet('pyeongminThrow', 'assets/image/character/pyeongmin/throw/pyeong_throw.png', { frameWidth: 521, frameHeight: 610 });
scene.load.spritesheet('pyeongminBurningSmall', 'assets/image/character/pyeongmin/burning/pyeong_burning_small.png', { frameWidth: 521, frameHeight: 610 });
scene.load.spritesheet('pyeongminBurningBig', 'assets/image/character/pyeongmin/burning/pyeong_burning_big.png', { frameWidth: 521, frameHeight: 610 });
scene.load.spritesheet('pyeongminGameOver', 'assets/image/character/pyeongmin/balladang/pyeong_balladang.png', { frameWidth: 720, frameHeight: 700 });
scene.load.image('pyeongminStand', 'assets/image/character/pyeongmin/pyeong_stand.png');
scene.load.spritesheet('wordBreak', 'assets/image/word/wordbreak.png', { frameWidth: 180, frameHeight: 180 });
scene.load.image('phaseChangeBgr', 'assets/placeholder/phaseChange.png');
scene.load.image('attackPaper', 'assets/image/etc/paper_crumbled.png');
scene.load.image('panel', 'assets/placeholder/panel.png');
scene.load.image('button', 'assets/placeholder/button.png');
scene.load.image('itemBag', 'assets/image/etc/itembag2.png');
}
ResourceLoader.loadAnimation = function(scene)
{
scene.anims.create({
key: 'wordBreakAnim',
frames: scene.anims.generateFrameNumbers('wordBreak'),
frameRate: 10,
repeat: 0,
hideOnComplete: false
});
WordSpace.pyeongminAnims[Enums.characterAnim.sit] = scene.anims.create({
key: 'pyeongminSitAnim',
frames: scene.anims.generateFrameNumbers('pyeongminSit'),
frameRate: 10,
repeat: 0,
hideOnComplete: false
});
WordSpace.pyeongminAnims[Enums.characterAnim.write] = scene.anims.create({
key: 'pyeongminWriteAnim',
frames: scene.anims.generateFrameNumbers('pyeongminWrite'),
frameRate: 10,
repeat: 0,
hideOnComplete: false
});
WordSpace.pyeongminAnims[Enums.characterAnim.notBurning] = scene.anims.create({
key: 'pyeongminnotBurningAnim',
frames: scene.anims.generateFrameNumbers('pyeongminWrite'),
frameRate: 10,
repeat: -1,
hideOnComplete: false
});
WordSpace.pyeongminAnims[Enums.characterAnim.smallBurning] = scene.anims.create({
key: 'pyeongminsmallBurningAnim',
frames: scene.anims.generateFrameNumbers('pyeongminBurningSmall'),
frameRate: 10,
repeat: -1,
hideOnComplete: false
});
WordSpace.pyeongminAnims[Enums.characterAnim.bigBurning] = scene.anims.create({
key: 'pyeongminbigBurningAnim',
frames: scene.anims.generateFrameNumbers('pyeongminBurningBig'),
frameRate: 10,
repeat: -1,
hideOnComplete: false
});
WordSpace.pyeongminAnims[Enums.characterAnim.throw] = scene.anims.create({
key: 'pyeongminThrowAnim',
frames: scene.anims.generateFrameNumbers('pyeongminThrow'),
frameRate: 10,
repeat: 0,
hideOnComplete: false
});
WordSpace.pyeongminAnims[Enums.characterAnim.gameOver] = scene.anims.create({
key: 'pyeongminGameOverAnim',
frames: scene.anims.generateFrameNumbers('pyeongminGameOver'),
frameRate: 10,
repeat: 0,
hideOnComplete: false
});
}
\ No newline at end of file
var ScenesData = ScenesData || {};
ScenesData.currentScene = null;
var menuScene = new Phaser.Class(
{
......@@ -14,17 +15,295 @@ var menuScene = new Phaser.Class(
preload: function()
{
ScenesData.menuScene = this;
Input.inputField.loadImage(this);
BackGround.loadImage(this);
ScenesData.currentScene = this;
ResourceLoader.loadBackGround(this);
ResourceLoader.loadImage(this);
CSVParsing.loadText(this);
Audio.loadSound(this);
this.load.scenePlugin({
key: 'rexuiplugin',
url: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/plugins/dist/rexuiplugin.min.js',
sceneKey: 'rexUI'
});
this.load.scenePlugin({
key: 'rexbuttonplugin',
url: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/plugins/dist/rexbuttonplugin.min.js',
sceneKey: 'button'
});
},
create: function()
{
BackGround.drawBackground(this);
Audio.loopSound(this, 'login');
Input.inputField.generate(this, Input.menuSceneEnterReaction);
BackGround.drawMenu(this);
PlayerData.currentHopae = (PlayerData.userData.recentHopae == null) ? PlayerData.userData.hopae[0] : PlayerData.userData.recentHopae;
PlayerData.nickname = PlayerData.currentHopae.name;
this.userName = this.add.text(100, 100, '내 이름 : ' + PlayerData.userData.userName).setOrigin(0, 0.5).setColor('#000000').setDepth(10).setPadding(5,5,5,5).setFontSize(40);
this.money = this.add.text(100, 200, '소지 엽전 : ' + PlayerData.userData.money).setOrigin(0, 0.5).setColor('#000000').setDepth(10).setPadding(5,5,5,5).setFontSize(40);
this.organizeHopae = function()
{
this.myHopae = [];
this.myHopae.push({
name: PlayerData.currentHopae.name,
type: PlayerData.currentHopae.type,
});
for(let i = 0; i < PlayerData.userData.hopae.length; i++)
if(PlayerData.userData.hopae[i].name != PlayerData.currentHopae.name)
this.myHopae.push({
name: PlayerData.userData.hopae[i].name,
type: PlayerData.userData.hopae[i].type,
});
}
this.createHopaeMenu = function()
{
this.hopaeMenuObject = [];
for(let i = 0; i < this.myHopae.length; i++)
{
let temp = UIObject.createButton(this, UIObject.createLabel(this, 100, 300, 10,
'nameBgr' + ScenesData.menuScene.myHopae[i].name.length, 1, 'left', ScenesData.menuScene.myHopae[i].name, 25, '#ffffff', 0.45, 0.5), 0, 0, 0,
function()
{
PlayerData.currentHopae = ScenesData.menuScene.myHopae[i];
PlayerData.nickname = ScenesData.menuScene.myHopae[i].name;
ScenesData.menuScene.organizeHopae();
ScenesData.menuScene.currentHopaeBtn.destroy();
ScenesData.menuScene.createCurrentHopae();
ScenesData.menuScene.hopaeMenuObject.forEach(function(element){
ScenesData.menuScene.tweens.add({
targets: element,
y: 0,
duration: 200,
ease: 'Linear',
loop: 0,
onComplete: function(){element.destroy();}
});
});
});
ScenesData.menuScene.tweens.add({
targets: temp,
y: 50 * i,
duration: 500,
ease: 'Bounce',
loop: 0
});
this.hopaeMenuObject.push(temp);
}
}
this.createCurrentHopae = function()
{
this.currentHopaeBtn = UIObject.createButton(this, UIObject.createLabel(this, 100, 300, 10,
'nameBgr' + PlayerData.nickname.length, 1, 'left', PlayerData.nickname, 25, '#ffffff', 0.45, 0.5), 0, 0, 0,
function()
{
ScenesData.menuScene.currentHopaeBtn.destroy();
ScenesData.menuScene.createHopaeMenu();
})
}
this.organizeHopae();
this.createCurrentHopae();
this.myCharacter = this.add.sprite(game.config.width / 2, game.config.height / 2 - 200, 'pyeongminStand').setOrigin(0.5, 0.5).setDepth(5).setScale(0.8);
this.roomEnterDialog = this.rexUI.add.dialog({
x: game.config.width / 2,
y: game.config.height / 2,
background: this.add.sprite(game.config.width / 2, game.config.height / 2, 'panel').setOrigin(0.5, 0.5),
content: this.add.text(0, 0, '대기실에 참가하시겠습니까?', {
font: '50pt 궁서'
}),
actions: [
UIObject.createLabel(this, 0, 0, 0, 'button', 1, 'center', '', 50),
UIObject.createLabel(this, 0, 0, 0, 'button', 1, 'center', '아니오', 50)
],
space: {
content: 25,
action: 100,
left: 20,
right: 20,
top: 20,
bottom: 20,
},
align: {
actions: 'center' // 'center'|'left'|'right'
},
expand: {
content: false, // Content is a pure text object
}
}).layout().setDepth(10).setVisible(false);
this.roomEnterDialog
.on('button.click', function (button, groupName, index) {
if(index == 0) socket.emit('enterRoom', PlayerData.nickname);
else
{
this.roomEnterDialog.setVisible(false);
this.gameStartBtn.setEnable(true);
}
}, this)
.on('button.over', function (button, groupName, index) {
//console.log('button over');
})
.on('button.out', function (button, groupName, index) {
//console.log('button out');
});
this.gameStartBtn = UIObject.createButton(this, UIObject.createLabel(this, game.config.width / 2, 900, 5, 'pyeongminWrite', 0.5, 'center'), 1, 0, 2,
function()
{
ScenesData.menuScene.gameStartBtn.setEnable(false);
ScenesData.menuScene.roomEnterDialog.setVisible(true);
ScenesData.menuScene.roomEnterDialog.popUp(200);
})
this.shopBtn = UIObject.createButton(this, UIObject.createLabel(this, game.config.width - 100, 900, 5, 'pyeongminThrow', 0.5, 'center'), 1, 0, 2,
function()
{
console.log('상점 입장');
})
this.hopaeBtn = UIObject.createButton(this, UIObject.createLabel(this, 100, 900, 5, 'pyeongminThrow', 0.5, 'center'), 1, 0, 2,
function()
{
ScenesData.changeScene('hopaeScene');
})
}
});
var hopaeScene = new Phaser.Class(
{
Extends: Phaser.Scene,
initialize:
function hopaeScene ()
{
Phaser.Scene.call(this, {key: 'hopaeScene'});
},
preload: function()
{
ScenesData.hopaeScene = this;
this.load.scenePlugin({
key: 'rexuiplugin',
url: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/plugins/dist/rexuiplugin.min.js',
sceneKey: 'rexUI'
});
this.load.scenePlugin({
key: 'rexbuttonplugin',
url: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/plugins/dist/rexbuttonplugin.min.js',
sceneKey: 'button'
});
},
create: function()
{
BackGround.drawBackground(this);
Input.inputField.generate(this, function(){},
UIObject.createLabel(this, game.config.width / 2, game.config.height / 2, 10, 'nameBgr6', 2, 'center', '', 50, '#ffffff').getElement('text').setOrigin(0.45,0.5), true);
this.checkDialog = this.rexUI.add.dialog({
x: game.config.width / 2,
y: game.config.height / 2,
background: this.add.sprite(game.config.width / 2, game.config.height / 2, 'panel').setOrigin(0.5, 0.5),
content: this.add.text(0, 0, '이 이름으로 하시겠습니까?\n변경에는 엽전이 소모됩니다.', {
font: '50pt 궁서',
color: '#000000'
}),
actions: [
UIObject.createLabel(this, 0, 0, 0, 'button', 1, 'center', '', 50),
UIObject.createLabel(this, 0, 0, 0, 'button', 1, 'center', '아니오', 50)
],
space: {
title: 25,
content: 25,
action: 100,
left: 20,
right: 20,
top: 20,
bottom: 20,
},
align: {
actions: 'center' // 'center'|'left'|'right'
},
expand: {
content: false, // Content is a pure text object
}
}).layout().setDepth(10).setVisible(false);
this.checkDialog
.on('button.click', function (button, groupName, index) {
if(index == 0)
{
if(PlayerData.userData.money > 0)
{
fbClient.updateUserData('hopae', {name: Input.inputField.text.text, type: 'wood'});
fbClient.updateUserData('money', -1);
ScenesData.changeScene('menuScene');
}
else
{
this.checkDialog.setVisible(false);
this.errorMsg = UIObject.createButton(this, UIObject.createLabel(this, game.config.width / 2, game.config.height / 2, 10, 'panel', 1, 'center',
'엽전이 부족합니다', 50, '#000000').layout().popUp(200), 0, 0, 0,
function()
{
ScenesData.hopaeScene.errorMsg.destroy();
ScenesData.hopaeScene.checkBtn.setEnable(true);
})
}
}
else
{
this.checkDialog.setVisible(false);
this.checkBtn.setEnable(true);
}
}, this)
.on('button.over', function (button, groupName, index) {
//console.log('button over');
})
.on('button.out', function (button, groupName, index) {
//console.log('button out');
});
this.warningText = UIObject.createLabel(this, game.config.width / 2, game.config.height / 2 - 100, 2, 'panel', 1, 'center',
'이름 타수가 많아 플레이에 패널티가 있을 수 있습니다', 40, '#000000').setVisible(false).layout();
this.checkBtn = UIObject.createButton(this, UIObject.createLabel(this, game.config.width / 2, 900, 5, 'pyeongminWrite', 0.5, 'center'), 1, 0, 2,
function()
{
if(Input.checkProperInput(Input.inputField.text.text))
{
ScenesData.hopaeScene.checkBtn.setEnable(false);
ScenesData.hopaeScene.checkDialog.setVisible(true).popUp(200);
}
})
this.backBtn = UIObject.createButton(this, UIObject.createLabel(this, 100, 900, 5, 'pyeongminWrite', 0.5, 'center'), 1, 0, 2,
function()
{
ScenesData.changeScene('menuScene');
});
}
});
......@@ -42,22 +321,23 @@ var roomScene = new Phaser.Class(
preload: function()
{
ScenesData.roomScene = this;
BackGround.loadImage(this);
//ResourceLoader.loadBackGround(this);
this.load.image('playerStand', 'assets/image/character/pyeongmin/pyeong_stand.png');
},
create: function()
{
BackGround.drawBackground(this);
BackGround.drawRoom(this);
Audio.loopSound(this, 'inRoom');
this.players = [];
this.isCounting = false;
this.isCountEnd = false;
this.endTime = 0;
this.peopleCount = 1;
this.countText = this.add.text(640, 360, '사람들을 위해 대기중입니다...').setOrigin(0.5, 0.5).setColor('#000000').setBackgroundColor('#ffffff').setDepth(10).setPadding(5,5,5,5);
this.peopleText = this.add.text(640, 80, '1 / 10').setOrigin(0.5, 0.5).setColor('#000000').setBackgroundColor('#ffffff').setDepth(10);
this.countText = this.add.text(game.config.width / 2, game.config.height / 2, '사람들을 위해 대기중입니다...').setOrigin(0.5, 0.5).setColor('#000000').setBackgroundColor('#ffffff').setDepth(10).setPadding(5,5,5,5);
this.peopleText = this.add.text(game.config.width / 2, game.config.height / 9, '1 / 10').setOrigin(0.5, 0.5).setColor('#000000').setBackgroundColor('#ffffff').setDepth(10);
},
update: function()
......@@ -72,20 +352,20 @@ var roomScene = new Phaser.Class(
//console.log('end Count');
setTimeout(() => {
socket.emit('endCount');
}, (Phaser.Math.Distance.Between(0, 0, 640, 800) * 3));
}, (Phaser.Math.Distance.Between(0, 0, game.config.width / 2, game.config.height * 10 / 9) * 10));
this.isCounting = false;
this.isCountEnd = true;
this.players.forEach(function(element){
element.follower = { t: 0, vec: new Phaser.Math.Vector2() };
element.path = new Phaser.Curves.Line([
element.sprite.x, element.sprite.y,
640, 800
game.config.width / 2, game.config.height * 10 / 9
]);
ScenesData.roomScene.tweens.add({
targets: element.follower,
t: 1,
ease: 'Linear',
duration: Phaser.Math.Distance.Between(element.sprite.x, element.sprite.y, 640, 800) * 3,
duration: Phaser.Math.Distance.Between(element.sprite.x, element.sprite.y, game.config.width / 2, game.config.height * 10 / 9) * 3,
repeat: 0
});
});
......@@ -96,7 +376,7 @@ var roomScene = new Phaser.Class(
this.players.forEach(function(element){
element.path.getPoint(element.follower.t, element.follower.vec);
element.sprite.setPosition(element.follower.vec.x, element.follower.vec.y);
element.nickname.setPosition(element.sprite.x - 10, element.sprite.y - 60);
element.nickname.setPosition(element.sprite.x - game.config.width / 128, element.sprite.y - game.config.height / 12);
});
this.countText.setText('잠시만 기다려주세요...');
}
......@@ -105,7 +385,7 @@ var roomScene = new Phaser.Class(
this.countText.setText('사람들을 위해 대기중입니다...');
}
}
})
});
var gameScene = new Phaser.Class(
{
......@@ -121,25 +401,35 @@ var gameScene = new Phaser.Class(
preload: function()
{
ScenesData.gameScene = this;
BackGround.loadImage(this);
WordSpace.loadImage(this);
Input.inputField.loadImage(this);
CSVParsing.loadText(this);
Audio.loadSound(this);
this.load.scenePlugin({
key: 'rexuiplugin',
url: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/plugins/dist/rexuiplugin.min.js',
sceneKey: 'rexUI'
});
this.load.scenePlugin({
key: 'rexbuttonplugin',
url: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/plugins/dist/rexbuttonplugin.min.js',
sceneKey: 'button'
});
WordSpace.weightTextObjForTest = this.add.text(game.config.width * 5 / 64, game.config.height * 5 / 48, '뇌의 무게: (현재) 0 / ' + this.brainCapacity + ' (전체)').setDepth(10).setColor('#000000');
WordSpace.killLogTextForTest = this.add.text(game.config.width * 25 / 32, game.config.height * 5 / 72, WordSpace.killLogForTest).setDepth(10).setColor('#000000').setAlign('right');
},
create: function()
{
WordSpace.gameTimer = new Phaser.Time.Clock(this);
WordSpace.gameTimer.start();
WordSpace.loadAnimation(this);
ResourceLoader.loadAnimation(this);
CSVParsing.CSVParse(this);
BackGround.drawBackground(this);
BackGround.drawBrain(this);
BackGround.drawCharacter(this);
Audio.playSound(this, 'startGame');
WordSpace.wordPhysicsGroup = this.physics.add.group();
Input.inputField.generate(this, Input.gameSceneEnterReaction);
Input.inputField.generate(this, Input.gameSceneEnterReaction,
UIObject.createLabel(ScenesData.gameScene, game.config.width / 2, game.config.height * 25 / 36, 10, 'inputfield', 1, 'center', '', 25, '#000000').getElement('text'));
WordSpace.attackGauge.generate(this);
WordSpace.spaceInitiate(this);
WordSpace.attackGauge.resetCycle(this);
......@@ -148,11 +438,10 @@ var gameScene = new Phaser.Class(
WordSpace.setPlayerTyping.initiate(this);
WordSpace.nameWordTextForTest = ScenesData.gameScene.add.text(50,400,'현재 가진 호패들 : 없음').setDepth(10).setColor('#000000');
WordSpace.nameWordTextForTest = this.add.text(50,400,'현재 가진 호패들 : 없음').setDepth(10).setColor('#000000');
WordSpace.nameQueue.initiate();
//WordSpace.attackGauge.add(11);
// for test
WordSpace.attackGauge.add(11);
},
update: function()
......@@ -166,6 +455,9 @@ var gameScene = new Phaser.Class(
{
element.attract();
})
WordSpace.attackPaperGroup.forEach(function(element){
element.moveObject(element);
});
let tempNames = '';
WordSpace.nameGroup.forEach(function(element)
{
......@@ -178,4 +470,14 @@ var gameScene = new Phaser.Class(
WordSpace.killLogTextForTest.setText(WordSpace.killLogForTest);
WordSpace.setPlayerTyping.add('');
}
});
\ No newline at end of file
});
ScenesData.changeScene = function(sceneKey)
{
ScenesData.currentScene.scene.start(sceneKey);
Input.input = [];
Input.converted = '';
Input.convInput = '';
Input.finalInput = '';
ScenesData.currentScene = game.scene.getScene(sceneKey);
}
\ No newline at end of file
var UIObject = UIObject || {};
UIObject.createLabel = function (scene, x, y, depth, image, size, align, text = '', textSize = 24, textColor = '#000000', textOriginX = 0.5, textOriginY = 0.5) {
var temp = scene.rexUI.add.label({
/*width: width,
height: height,*/
x: x,
y: y,
background: scene.add.sprite(x, y, image).setScale(size).setOrigin(0.5, 0.5).setDepth(depth),
text: scene.add.text(x, y, text, {
font: textSize + 'pt 궁서'
}).setDepth(depth).setOrigin(textOriginX, textOriginY).setColor(textColor),
space: {
left: 10,
right: 10,
top: 10,
bottom: 10
}
});
switch(align)
{
case 'left':
temp.x += temp.getElement('background').width / 2;
break;
case 'right':
temp.x -= temp.getElement('background').width / 2;
break;
case 'center':
break;
default:
break;
}
return temp;
}
UIObject.createButton = function(scene, buttonGameObject, overFrame, outFrame, downFrame, clickCallback) {
var temp = scene.rexUI.add.buttons({
x: 0,
y: 0,
width: undefined,
height: undefined,
orientation: 0,
buttons: [
buttonGameObject,
],
click: {
mode: 'pointerdown',
clickInterval: 100
}
});
buttonGameObject = buttonGameObject.getElement('background');
temp.enabled = true;
buttonGameObject.setFrame(outFrame).setInteractive()
.on('pointerover', () => {
if(temp.enabled)
{
buttonGameObject.setFrame(overFrame);
}
})
.on('pointerdown', () => {
if(temp.enabled)
{
buttonGameObject.setFrame(downFrame);
clickCallback();
}
})
.on('pointerup', () => {
buttonGameObject.setFrame(overFrame);
})
.on('pointerout', () => {
buttonGameObject.setFrame(outFrame);
})
temp.setEnable = function(isEnable)
{
temp.enabled = isEnable;
return temp;
}
return temp;
}
\ No newline at end of file
class WordObject
{
constructor(text, isNameWord = false)
{
this.generationCode = WordSpace.nextWordCode++;
......@@ -13,31 +12,15 @@ class WordObject
this.isNameWord = isNameWord;
}
instantiate(scene, lenRate)
instantiate(scene, spriteName, textColor, lenRate)
{
let p = [{x : 3, y : 0.7}, {x : 20, y : 1.2}];
let p = [{x : 3, y : 1.25}, {x : 20, y : 2.05}];
this.scale = ((p[1].y - p[0].y) / (p[1].x - p[0].x)) * (this.wordWeight - p[0].x) + p[0].y;
this.fontScale = 25;
var random = WordSpace.getSpawnPoint(lenRate);
if (!this.isNameWord)
{
this.physicsObj = scene.physics.add.sprite(random.x, random.y, 'wordBgr' + this.wordGrade + '_' + Math.min(Math.max(2, this.wordText.length), 6))
.setMass(this.wordWeight * 10)
.setScale(this.scale)
.setFrictionX(0)
.setFrictionY(0)
.setBounce(0.5);
}
else
{
this.physicsObj = scene.physics.add.sprite(random.x, random.y, (this.isStrong ? 'strongBgr' : 'nameBgr') + Math.min(Math.max(2, this.wordText.length), 6))
.setMass(this.wordWeight * 10)
.setScale(this.scale)
.setFrictionX(0)
.setFrictionY(0)
.setBounce(0.5);
}
this.physicsObj = scene.physics.add.sprite(random.x, random.y, spriteName).setMass(this.wordWeight * 10).setScale(this.scale)
.setFrictionX(0).setFrictionY(0).setBounce(0.5);
this.physicsObj.wordCollider = null;
let dist = Phaser.Math.Distance.Between(this.physicsObj.x, this.physicsObj.y, WordSpace.gravityPoint.x, WordSpace.gravityPoint.y);
let angle = Phaser.Math.Angle.Between(this.physicsObj.x, this.physicsObj.y, WordSpace.gravityPoint.x, WordSpace.gravityPoint.y);
......@@ -52,8 +35,7 @@ class WordObject
fontFamily: '"궁서", 궁서체, serif',
//fontStyle: (this.wordWeight > 5 ? 'bold' : '')
});
if (!this.isNameWord) this.wordObj.setColor('#000000').setOrigin(0.5,0.5);
else this.wordObj.setColor('#ffffff').setOrigin(0.45,0.5);
this.wordObj.setColor(textColor).setOrigin(0.5,0.5);
this.createdTime = WordSpace.gameTimer.now;
WordSpace.totalWeight += this.wordWeight;
WordSpace.totalWordNum += 1;
......@@ -76,12 +58,8 @@ class WordObject
setTimeout(function() {
breakAnim.destroy();
}, 200);
if(!this.isNameWord)
{
this.wordObj.destroy();
this.physicsObj.destroy();
}
BackGround.myCharacter.play(WordSpace.pyeongminAnims[Enums.characterAnim.write]);
RoomData.myself.playerImage.play(WordSpace.pyeongminAnims[Enums.characterAnim.write]);
RoomData.myself.playerImage.anims.chain(WordSpace.pyeongminAnims[Enums.characterAnim.sit]);
}
attract()
......@@ -122,51 +100,76 @@ class NormalWord extends WordObject
{
super(text);
}
destroy()
instantiate(scene, lenRate)
{
switch(this.wordGrade)
let spriteName = 'wordBgr' + this.wordGrade + '_' + Math.min(Math.max(2, this.wordText.length), 6);
let textColor = '#000000'
super.instantiate(scene, spriteName, textColor, lenRate);
}
destroy(isNormallyRemoved = true)
{
super.destroy();
if(isNormallyRemoved)
{
case 0: WordSpace.attackGauge.add(2.5); break;
case 1: WordSpace.attackGauge.add(1.5); break;
case 2: WordSpace.attackGauge.add(0.9); break;
case 3: WordSpace.attackGauge.add(0.5); break;
default: console.log('[ERR] wrong grade of word'); break;
switch(this.wordGrade)
{
case 0: WordSpace.attackGauge.add(2.5); break;
case 1: WordSpace.attackGauge.add(1.5); break;
case 2: WordSpace.attackGauge.add(0.9); break;
case 3: WordSpace.attackGauge.add(0.5); break;
default: console.log('[ERR] wrong grade of word'); break;
}
}
super.destroy();
this.wordObj.destroy();
this.physicsObj.destroy();
}
}
class AttackWord extends WordObject
{
constructor(text, _wordGrade, _playerData, _isStrong, _isCountable = true, lenRate)
constructor(text, _wordGrade, _playerData, _attackOption, lenRate)
{
super(text);
this.wordGrade = _wordGrade;
this.wordWeight = _isStrong ? WordReader.strongAttackWeight[3 - this.wordGrade] : WordReader.attackWeight[3 - this.wordGrade];
this.wordWeight = _attackOption.isStrong ? WordReader.strongAttackWeight[3 - this.wordGrade] : WordReader.attackWeight[3 - this.wordGrade];
if(WordReader.getWordTyping(_playerData.nickname) > 9)
this.wordWeight += this.wordWeight * 0.2 * (WordReader.getWordTyping(_playerData.nickname) - 9);
if(_attackOption.isHeavy) this.wordWeight *= 2;
this.attacker = _playerData;
if(!_isCountable) this.counterTime = 0;
if(!_attackOption.isCountable) this.counterTime = 0;
else this.counterTime = WordSpace.gameTimer.now + 1000 * (this.wordTyping <= (5 - _wordGrade) * 2.5 ? this.wordTyping / (Math.max(200, WordSpace.playerTyping) / 60) * 1.5 :
((5 - _wordGrade) * 3 + (this.wordTyping - (5 - _wordGrade) * 2.5) * 2.5) / (Math.max(200, WordSpace.playerTyping) / 60) * 1.5);
this.isDark = _attackOption.isDark;
console.log('Attack text : ' + text + ', Attacker : ' + this.attacker.nickname + ', Weight : ' + this.wordWeight);
console.log('Counter time : ' + this.counterTime);
}
instantiate(scene, lenRate)
{
super.instantiate(scene, lenRate);
let spriteName = 'wordBgr' + this.wordGrade + '_' + Math.min(Math.max(2, this.wordText.length), 6);
let textColor = '#000000'
super.instantiate(scene, spriteName, textColor, lenRate);
this.maskBackground = scene.physics.add.sprite(this.physicsObj.x, this.physicsObj.y, 'wordBgr' + this.wordGrade + '_' + Math.min(Math.max(2, this.wordText.length), 6))
.setTint(Phaser.Display.Color.GetColor(120, 120, 120)).setScale(this.scale);
this.maskBackground.alpha = 0.5;
this.maskBackground.alpha = this.isDark ? 1 : 0.5;
this.shape = scene.make.graphics();
var rect = new Phaser.Geom.Rectangle(0, 0, this.maskBackground.width * this.scale, this.maskBackground.height * this.scale);
this.shape.fillStyle(0xffffff).fillRectShape(rect);
this.mask = this.shape.createGeometryMask();
this.maskBackground.setMask(this.mask);
this.maskStart = this.physicsObj.x;
this.maskEnd = this.physicsObj.x - this.physicsObj.width * this.scale;
if(this.isDark)
{
setTimeout(() => {
if(this.maskBackground != null && this.mask != null)
{
this.maskBackground.setMask(this.mask);
this.maskBackground.alpha = 0.5;
}
}, 4000);
}
else this.maskBackground.setMask(this.mask);
}
attract()
......@@ -182,36 +185,45 @@ class AttackWord extends WordObject
else if(this.maskBackground != null) this.maskBackground.destroy();
}
destroy()
destroy(isNormallyRemoved = true)
{
switch(this.wordGrade)
{
case 0: WordSpace.attackGauge.add(2.5); break;
case 1: WordSpace.attackGauge.add(1.5); break;
case 2: WordSpace.attackGauge.add(0.9); break;
case 3: WordSpace.attackGauge.add(0.5); break;
default: console.log('[ERR] wrong grade of word'); break;
}
if(WordSpace.gameTimer.now < this.counterTime)
super.destroy();
if(isNormallyRemoved)
{
let tempWord = WordSpace.generateWord.Name(ScenesData.gameScene, true, this.attacker);
tempWord.physicsObj.setPosition(this.physicsObj.x, this.physicsObj.y);
tempWord.wordObj.setPosition(tempWord.physicsObj.x, tempWord.physicsObj.y);
tempWord.destroy();
let attackData =
switch(this.wordGrade)
{
case 0: WordSpace.attackGauge.add(2.5); break;
case 1: WordSpace.attackGauge.add(1.5); break;
case 2: WordSpace.attackGauge.add(0.9); break;
case 3: WordSpace.attackGauge.add(0.5); break;
default: console.log('[ERR] wrong grade of word'); break;
}
if(WordSpace.gameTimer.now < this.counterTime)
{
roomNum: RoomData.roomId,
attacker: RoomData.myself,
target: this.attacker.id,
text: this.wordText,
grade: Math.min(3, this.wordGrade + 1),
isStrong: false,
isCountable: false
let tempWord = WordSpace.generateWord.Name(ScenesData.gameScene, true, this.attacker);
tempWord.physicsObj.setPosition(this.physicsObj.x, this.physicsObj.y);
tempWord.wordObj.setPosition(tempWord.physicsObj.x, tempWord.physicsObj.y);
tempWord.destroy();
let attackData =
{
roomNum: RoomData.roomId,
attackerId: RoomData.myself.id,
victimId: this.attacker.id,
text: this.wordText,
grade: Math.min(3, this.wordGrade + 1),
attackOption: {
isStrong: false,
isCountable: false,
isHeavy: false,
isDark: false
},
}
socket.emit('attack', attackData);
}
socket.emit('attack', attackData);
}
if(this.maskBackground != null) this.maskBackground.destroy();
super.destroy();
this.wordObj.destroy();
this.physicsObj.destroy();
}
}
......@@ -226,6 +238,13 @@ class NameWord extends WordObject
this.isActive = true;
//console.log('Name : ' + player.nickname + ', Strong : ' + this.isStrong + ', Weight : ' + this.wordWeight);
}
instantiate(scene, lenRate)
{
let spriteName = (this.isStrong ? 'strongBgr' : 'nameBgr') + Math.min(Math.max(2, this.wordText.length), 6)
let textColor = '#ffffff'
super.instantiate(scene, spriteName, textColor, lenRate);
this.wordObj.setOrigin(0.45,0.5);
}
attract()
{
if(this.isActive) super.attract();
......@@ -234,7 +253,7 @@ class NameWord extends WordObject
this.path.getPoint(this.follower.t, this.follower.vec);
this.physicsObj.setPosition(this.follower.vec.x, this.follower.vec.y);
this.wordObj.setPosition(this.physicsObj.x, this.physicsObj.y);
this.physicsObj.angle = 90 * this.follower.t;
this.physicsObj.angle = (this.isStrong ? 450 : 90) * this.follower.t
this.wordObj.angle = this.physicsObj.angle;
if(this.isStrong)
{
......@@ -247,40 +266,145 @@ class NameWord extends WordObject
}
}
}
destroy()
destroy(isNormallyRemoved = true)
{
super.destroy();
ScenesData.gameScene.physics.world.removeCollider(this.physicsObj.wordCollider);
WordSpace.wordGroup.forEach(function(element)
if(isNormallyRemoved)
{
ScenesData.gameScene.physics.world.removeCollider(element.physicsObj.wordCollider);
element.physicsObj.wordCollider = ScenesData.gameScene.physics.add.collider(element.physicsObj, WordSpace.wordPhysicsGroup, function(object1)
ScenesData.gameScene.physics.world.removeCollider(this.physicsObj.wordCollider);
WordSpace.wordGroup.forEach(function(element)
{
object1.topObj.attract();
ScenesData.gameScene.physics.world.removeCollider(element.physicsObj.wordCollider);
element.physicsObj.wordCollider = ScenesData.gameScene.physics.add.collider(element.physicsObj, WordSpace.wordPhysicsGroup, function(object1)
{
object1.topObj.attract();
});
});
});
if(!this.isStrong) WordSpace.attackGauge.add(this.wordTyping * 0.1);
WordSpace.nameGroup.push(this);
this.isActive = false;
this.physicsObj.setVelocity(0, 0).setDepth(20);
this.wordObj.setPosition(this.physicsObj.x, this.physicsObj.y).setDepth(20);
this.follower = { t: 0, vec: new Phaser.Math.Vector2() };
this.path = new Phaser.Curves.Spline([
this.physicsObj.x, this.physicsObj.y,
(this.physicsObj.x + 500 + WordSpace.nameGroup.length * 15) / 2, this.physicsObj.y - 50,
500 + WordSpace.nameGroup.length * 15, 680 + this.wordText.length * 10 + (Math.random() * 20 - 10)
]);
ScenesData.gameScene.tweens.add({
targets: this.follower,
t: 1,
ease: 'Sine',
duration: 2000,
repeat: 0
});
//이동경로 디버그
/*var graphics = ScenesData.gameScene.add.graphics();
graphics.lineStyle(2, 0xffffff, 1);
this.path.draw(graphics);*/
if(!this.isStrong) WordSpace.attackGauge.add(this.wordTyping * 0.1);
WordSpace.nameGroup.push(this);
this.isActive = false;
this.physicsObj.setVelocity(0, 0).setDepth(20);
this.wordObj.setPosition(this.physicsObj.x, this.physicsObj.y).setDepth(20);
this.follower = { t: 0, vec: new Phaser.Math.Vector2() };
this.path = new Phaser.Curves.Spline([
this.physicsObj.x, this.physicsObj.y,
(this.physicsObj.x + game.config.width * (500 + WordSpace.nameGroup.length * 15) / 1280) / 2, this.physicsObj.y - game.config.height * 5 / 72,
game.config.width * (500 + WordSpace.nameGroup.length * 15) / 1280, game.config.height * (680 + this.wordText.length * 10 + (Math.random() * 20 - 10)) / 720
]);
ScenesData.gameScene.tweens.add({
targets: this.follower,
t: 1,
ease: 'Sine',
duration: 2000,
repeat: 0
});
//이동경로 디버그
/*var graphics = ScenesData.gameScene.add.graphics();
graphics.lineStyle(2, 0xffffff, 1);
this.path.draw(graphics);*/
}
}
}
class ItemWord extends WordObject
{
constructor(_itemType)
{
super(_itemType);
this.wordWeight = 2;
this.itemType = _itemType
//console.log('Name : ' + player.nickname + ', Strong : ' + this.isStrong + ', Weight : ' + this.wordWeight);
}
instantiate(scene, lenRate)
{
let spriteName = null;
let textColor = null;
switch(this.itemType)
{
case Enums.item.invincible:
spriteName = 'item0';
textColor = '#23D9B7'
break;
case Enums.item.nameList:
spriteName = 'item1';
textColor = '#FFB28F'
break;
case Enums.item.charge:
spriteName = 'item2';
textColor = '#FF9515'
break;
case Enums.item.clean:
spriteName = 'item3';
textColor = '#263387'
break;
case Enums.item.heavy:
spriteName = 'item4';
textColor = '#dddddd'
break;
case Enums.item.dark:
spriteName = 'item5';
textColor = '#dddd70'
break;
default:
console.log("Item type is inappropriate. Item type : " + this.itemType);
break;
}
super.instantiate(scene, spriteName, textColor, lenRate);
}
destroy(isNormallyRemoved = true)
{
super.destroy();
if(isNormallyRemoved)
{
WordSpace.attackGauge.add(0.5);
switch(this.itemType)
{
case Enums.item.invincible:
WordSpace.isInvincible = true;
setTimeout(() => {
WordSpace.isInvincible = false;
}, 5000);
break;
case Enums.item.nameList:
let tempNames = [];
RoomData.players.forEach(function(element){
if(element.id != RoomData.myself.id && element.isAlive) tempNames.push(element.index)
});
let length = Math.min(tempNames.length, 8);
tempNames = Phaser.Utils.Array.Shuffle(tempNames);
for(let i = 0; i < length; i++)
{
let tempWord = WordSpace.generateWord.Name(ScenesData.gameScene, true, RoomData.players[tempNames[i]]);
tempWord.physicsObj.setPosition(this.physicsObj.x, this.physicsObj.y);
tempWord.wordObj.setPosition(tempWord.physicsObj.x, tempWord.physicsObj.y);
tempWord.destroy();
}
break;
case Enums.item.charge:
WordSpace.attackGauge.add(11);
break;
case Enums.item.clean:
let tempWords = [];
WordSpace.wordGroup.forEach(function(element){
tempWords.push(WordSpace.wordGroup.indexOf(element));
});
tempWords = Phaser.Utils.Array.Shuffle(tempWords);
let tempLenth = tempWords.length * 0.3;
for(let i = 0; i < tempLenth; i++)
if(WordSpace.wordGroup[tempWords[i]] != null) WordSpace.wordGroup[tempWords[i]].destroy(false);
break;
case Enums.item.heavy:
Input.attackOption.isHeavy = true;
break;
case Enums.item.dark:
Input.attackOption.isDark = true;
break;
default:
console.log("Item type is inappropriate. Item type : " + this.itemType);
break;
}
}
this.wordObj.destroy();
this.physicsObj.destroy();
}
}
\ No newline at end of file
var WordReader = WordReader || {};
WordReader.normalWeight = [3, 5, 7, 10];
WordReader.attackWeight = [6, 8, 12, 15];
WordReader.strongAttackWeight = [10, 13, 16, 20];
//초성의 타수를 반환함
WordReader.firstSound = function(charText)
{
......@@ -54,6 +58,32 @@ WordReader.getWordGrade = function(_wordTyping)
17 <= _wordTyping && _wordTyping < 26 ? 0 : -1;
}
WordReader.normalWeight = [3, 5, 7, 10];
WordReader.attackWeight = [6, 8, 12, 15];
WordReader.strongAttackWeight = [10, 13, 16, 20];
\ No newline at end of file
WordReader.getEditDistance = function(input, check) {
var inputWords = [], checkWords = []
for(let i = 0; i < input.length; i++)
{
inputWords.push(parseInt(((input[i].charCodeAt(0) - parseInt('0xac00',16)) /28) / 21) + parseInt('0x1100',16));
inputWords.push(parseInt(((input[i].charCodeAt(0)- parseInt('0xac00',16)) / 28) % 21) + parseInt('0x1161',16));
inputWords.push(parseInt((input[i].charCodeAt(0) - parseInt('0xac00',16)) % 28) + parseInt('0x11A8') -1);
}
for(let i = 0; i < check.length; i++)
{
checkWords.push(parseInt(((check[i].charCodeAt(0) - parseInt('0xac00',16)) /28) / 21) + parseInt('0x1100',16));
checkWords.push(parseInt(((check[i].charCodeAt(0)- parseInt('0xac00',16)) / 28) % 21) + parseInt('0x1161',16));
checkWords.push(parseInt((check[i].charCodeAt(0) - parseInt('0xac00',16)) % 28) + parseInt('0x11A8') -1);
}
var matrix = [];
var i, j;
for(i = 0; i <= checkWords.length; i++) // increment along the first column of each row
matrix[i] = [i];
for(j = 0; j <= inputWords.length; j++) // increment each column in the first row
matrix[0][j] = j;
for(i = 1; i <= checkWords.length; i++) // Fill in the rest of the matrix
for(j = 1; j <= inputWords.length; j++){
if(checkWords[i-1] == inputWords[j-1]) matrix[i][j] = matrix[i-1][j-1];
else matrix[i][j] = Math.min(matrix[i-1][j-1] + 1, // substitution
Math.min(matrix[i][j-1] + 1, // insertion
matrix[i-1][j] + 1)); // deletion
}
return matrix[checkWords.length][inputWords.length];
}
\ No newline at end of file
......@@ -12,16 +12,18 @@ WordSpace.totalWordNum = 0;
WordSpace.brainCapacity = 200; //수용 가능한 단어 무게 최대치
WordSpace.gameTimer = null; //현재 게임 플레이 시간 타이머
WordSpace.isTimerOn = false;
WordSpace.isInvincible = false;
WordSpace.pyeongminAnims = [];
WordSpace.wordGroup = [];
WordSpace.nameGroup = [];
WordSpace.attackPaperGroup = [];
WordSpace.wordForcedGroup = [];
WordSpace.wordPhysicsGroup = null;
WordSpace.GradeProb = [0.35, 0.6, 0.8];
WordSpace.Phase = {READY: 0, START: 1, MAIN: 2, MUSIC: 3};
WordSpace.CurrentPhase = WordSpace.Phase.READY;
WordSpace.CurrentPhase = WordSpace.Phase.START;
WordSpace.playerTyping = 0;
WordSpace.playerTypingRate = 0;
......@@ -36,14 +38,14 @@ WordSpace.delay =
WordSpace.NameSpawnReduce = 1000;
WordSpace.gravityPoint = {x: 640, y: 280};
WordSpace.gravityPoint = {x: 960, y: 420};
WordSpace.getSpawnPoint = function(_lenRate)
{
let lenRate = 1;
if(typeof _lenRate == 'number') lenRate = _lenRate;
let xLen = 550 * lenRate;
let yLen = 350 * lenRate;
let xLen = 650 * lenRate;
let yLen = 500 * lenRate;
const angle = Math.random() * Math.PI * 2;
let _x = xLen * Math.cos(angle) + this.gravityPoint.x;
let _y = yLen * Math.sin(angle) + this.gravityPoint.y;
......@@ -65,16 +67,7 @@ WordSpace.spaceInitiate = function(scene)
WordSpace.AdjustVarByPhase = function(typingRate, phase)
{
if(phase == WordSpace.Phase.READY)
{
WordSpace.delay.WordSpawn = 10000;
WordSpace.delay.NameSpawn = 10000;
WordSpace.NameSpawnReduce = 0;
WordSpace.GradeProb[0] = 1;
WordSpace.GradeProb[1] = 1;
WordSpace.GradeProb[2] = 1;
}
else if(phase == WordSpace.Phase.START)
if(phase == WordSpace.Phase.START)
{
WordSpace.delay.WordSpawn = 3000;
WordSpace.delay.NameSpawn = 15000;
......@@ -111,15 +104,15 @@ WordSpace.attackGauge =
gradeColor: ['#111124','#EBB435','#A42FFF','#1D22EB','#83947F'],
setRect: function()
{
this.rectUI.setSize(20 * this.value, 11);
this.rectUI.setPosition(640 - 10 * this.value, 547);
this.rectUI.setSize(game.config.width / 64 * this.value, game.config.height * 11 / 720);
this.rectUI.setPosition(game.config.width * (640 - 10 * this.value) / 1280, game.config.height * 547 / 720);
let tmp = this.getAttackOption();
this.rectUI.setFillStyle(Phaser.Display.Color.HexStringToColor(this.gradeColor[tmp.wordGrade + 1]).color);
},
generate: function(scene)
{
//console.log("created");
this.rectUI = scene.add.rectangle(640,600,0,11).setDepth(11);
this.rectUI = scene.add.rectangle(game.config.width / 2, game.config.height * 5 / 6, 0, game.config.height * 11 / 720).setDepth(11);
},
add: function(plus)
{
......@@ -175,64 +168,6 @@ WordSpace.genWordByProb = function(scene)
//WordSpace.generateWord(scene, SelectWord.selectWord(wordIdx));
}
WordSpace.loadImage = function(scene)
{
for (let i = 0; i < 4; i++)
{
for (let j = 2; j < 7; j++)
{
scene.load.image(('wordBgr' + i + '_' + j), ('assets/placeholder/'+i + '_' + j + '.png'));
}
}
for (let i = 0; i < 4; i++)
{
scene.load.image('attackAlert' + i, 'assets/placeholder/attackalert' + (i+1) + '.png');
}
for (let i = 2; i < 7; i++)
{
scene.load.image('nameBgr' + i, 'assets/placeholder/name' + i + '.png');
scene.load.image('strongBgr' + i, 'assets/placeholder/strong' + i + '.png');
}
scene.load.spritesheet('wordBreak', 'assets/image/word/wordbreak.png', { frameWidth: 180, frameHeight: 180 });
scene.load.spritesheet('pyeongminWrite', 'assets/image/character/pyeongmin/write/pyeong_write.png', { frameWidth: 490, frameHeight: 423 });
scene.load.spritesheet('pyeongminThrow', 'assets/image/character/pyeongmin/throw/pyeong_throw.png', { frameWidth: 490, frameHeight: 423 });
WordSpace.weightTextObjForTest = scene.add.text(100, 75, '뇌의 무게: (현재) 0 / ' + this.brainCapacity + ' (전체)').setDepth(10).setColor('#000000');
WordSpace.killLogTextForTest = scene.add.text(1000, 50, WordSpace.killLogForTest).setDepth(10).setColor('#000000').setAlign('right');
}
WordSpace.loadAnimation = function(scene)
{
scene.anims.create({
key: 'wordBreakAnim',
frames: scene.anims.generateFrameNumbers('wordBreak'),
frameRate: 10,
repeat: 0,
hideOnComplete: false
});
WordSpace.pyeongminAnims[Enums.characterAnim.write] = scene.anims.create({
key: 'pyeongminWriteAnim',
frames: scene.anims.generateFrameNumbers('pyeongminWrite'),
frameRate: 10,
repeat: 0,
hideOnComplete: false
});
WordSpace.pyeongminAnims[Enums.characterAnim.attackWrite] = scene.anims.create({
key: 'pyeongminattackWriteAnim',
frames: scene.anims.generateFrameNumbers('pyeongminWrite'),
frameRate: 10,
repeat: -1,
hideOnComplete: false
});
WordSpace.pyeongminAnims[Enums.characterAnim.throw] = scene.anims.create({
key: 'pyeongminThrowAnim',
frames: scene.anims.generateFrameNumbers('pyeongminThrow'),
frameRate: 10,
repeat: 0,
hideOnComplete: false
});
}
WordSpace.generateWord =
{
Normal: function(scene, grade, lenRate)
......@@ -241,17 +176,27 @@ WordSpace.generateWord =
WordSpace.pushWord(scene, word, lenRate);
return word;
},
Attack: function(scene, wordText, grade, attacker, isStrong, isCountable, lenRate)
Attack: function(scene, wordText, grade, attacker, attackOption, lenRate)
{
word = new AttackWord(wordText, grade, attacker, isStrong, isCountable);
word = new AttackWord(wordText, grade, attacker, attackOption);
WordSpace.pushWord(scene, word, lenRate);
return word;
},
Name: function(scene, isStrong, newPlayerData, lenRate)
{
if(newPlayerData == null) word = new NameWord(WordSpace.nameQueue.pop(), isStrong);
if(newPlayerData == null)
{
let temp = WordSpace.nameQueue.pop();
if(temp == null) return null;
word = new NameWord(temp, isStrong);
}
else word = new NameWord(newPlayerData, isStrong);
//word = new NameWord(RoomData.myself, false);
WordSpace.pushWord(scene, word, lenRate);
return word;
},
Item: function(scene, itemType, lenRate)
{
word = new ItemWord(itemType);
WordSpace.pushWord(scene, word, lenRate);
return word;
}
......@@ -277,7 +222,7 @@ function gameOver()
socket.emit('defeated');
console.log('defeat');
ScenesData.gameScene.add.text(640, 360, '패배', {fontSize: '30pt'})
ScenesData.gameScene.add.text(game.config.width / 2, game.config.height / 2, '패배', {fontSize: '30pt'})
.setPadding(5,5,5,5).setOrigin(0.5, 0.5).setDepth(10)
.setColor('#000000').setBackgroundColor('#ffffff');
//alert('defeat');
......@@ -329,13 +274,32 @@ WordSpace.findWord = function(wordText)
else if (wordText === '공격' && WordSpace.attackGauge.value >= 3 && WordSpace.nameGroup.length > 0) // 공격모드 진입.
{
console.log('attack mode');
Input.attackOption = this.attackGauge.getAttackOption();
let tempAttackOption = this.attackGauge.getAttackOption();
Input.attackOption.wordCount = tempAttackOption.wordCount;
Input.attackOption.wordGrade = tempAttackOption.wordGrade;
Input.maxInput = Input.attackOption.wordCount;
Input.attackMode = true;
WordSpace.attackGauge.pauseCycle(true);
WordSpace.setPlayerTyping.add(wordText);
BackGround.myCharacter.play(WordSpace.pyeongminAnims[Enums.characterAnim.attackWrite]);
BackGround.myCharacter.anims.msPerFrame /= (4 - WordSpace.attackGauge.getAttackOption().wordGrade);
switch(tempAttackOption.wordCount)
{
case 2:
RoomData.myself.playerImage.play(WordSpace.pyeongminAnims[Enums.characterAnim.notBurning]);
break;
case 3:
RoomData.myself.playerImage.play(WordSpace.pyeongminAnims[Enums.characterAnim.smallBurning]);
break;
case 4:
RoomData.myself.playerImage.play(WordSpace.pyeongminAnims[Enums.characterAnim.smallBurning]);
break;
case 5:
RoomData.myself.playerImage.play(WordSpace.pyeongminAnims[Enums.characterAnim.bigBurning]);
break;
default:
console.log('Improper attack option.');
break;
}
RoomData.myself.playerImage.anims.msPerFrame /= (4 - Input.attackOption.wordGrade);
}
else // 오타 체크
{
......@@ -345,21 +309,22 @@ WordSpace.findWord = function(wordText)
{
if(element instanceof AttackWord)
{
tempDist = WordSpace.getEditDistance(wordText, element.wordText);
tempDist = WordReader.getEditDistance(wordText, element.wordText);
attackWords.push(element);
if(tempDist <= minDist) minDist = tempDist;
}
});
attackWords.some(function(element)
{
if(WordSpace.getEditDistance(wordText, element.wordText) == minDist)
if(WordReader.getEditDistance(wordText, element.wordText) == minDist)
{
console.log('Attack word : ' + element.wordText + ' of ' + element.attacker.nickname + ' 오타임');
let victimData =
{
roomNum: RoomData.roomId,
victim: RoomData.myself,
target: element.attacker.id
attackerId: element.attacker.id,
victimId: RoomData.myself.id,
word: element.wordText
}
socket.emit('defenseFailed', victimData);
return true;
......@@ -372,11 +337,13 @@ WordSpace.findWord = function(wordText)
WordSpace.setPlayerTyping =
{
totalTyping: 0,
writeWord: false,
add: function(wordText)
{
this.totalTyping += wordText != null ? WordReader.getWordTyping(wordText) : 0;
WordSpace.playerTyping = this.totalTyping / WordSpace.gameTimer.now * 60 * 1000;
this.text.setText('현재 타수 : ' + WordSpace.playerTyping.toFixed(1));
this.writeWord = wordText != '' ? true : false;
},
initiate: function(scene)
{
......@@ -390,29 +357,56 @@ WordSpace.attack = function(wordText, grade)
if (wordText != '')
{
console.log('attack ' + wordText + ', grade: ' + grade);
Audio.playSound(ScenesData.gameScene, 'attack');
let toSend = [];
WordSpace.nameGroup.forEach(function(element)
{
//console.log(RoomData.myself);
let attackData =
let victimId = element.ownerId;
let sendIdx = toSend.findIndex(function(element)
{
return element.victimId === victimId;
});
if (sendIdx != -1) toSend[sendIdx].multiple++;
else
{
roomNum: RoomData.roomId,
attacker: RoomData.myself,
target: element.ownerId,
text: wordText,
grade: grade,
isStrong: element.isStrong
let target = RoomData.players.find(function(_element) {
return _element.id == element.ownerId;
});
let attackData =
{
roomNum: RoomData.roomId,
attackerId: RoomData.myself.id,
victimId: target.id,
text: wordText,
grade: grade,
attackOption: {
isStrong: element.isStrong,
isCountable: true,
isHeavy: Input.attackOption.isHeavy,
isDark: Input.attackOption.isDark
},
multiple: 1
}
toSend.push(attackData);
}
socket.emit('attack', attackData);
element.physicsObj.destroy();
element.wordObj.destroy();
});
toSend.forEach(function(element)
{
socket.emit('attack', element);
});
WordSpace.generateWord.Name(ScenesData.gameScene, false, null);
WordSpace.generateWord.Name(ScenesData.gameScene, false, null);
WordSpace.nameGroup = [];
WordSpace.attackGauge.resetValue();
WordSpace.setPlayerTyping.add(wordText);
BackGround.myCharacter.play(WordSpace.pyeongminAnims[Enums.characterAnim.throw]);
RoomData.myself.playerImage.play(WordSpace.pyeongminAnims[Enums.characterAnim.throw]);
RoomData.myself.playerImage.anims.chain(WordSpace.pyeongminAnims[Enums.characterAnim.sit]);
Input.attackOption.isHeavy = false;
Input.attackOption.isDark = false;
}
else WordSpace.attackGauge.cutValue(0.3);
Input.maxInput = 6;
......@@ -420,68 +414,76 @@ WordSpace.attack = function(wordText, grade)
WordSpace.attackGauge.pauseCycle(false);
}
WordSpace.makeAttackPaper = function(scene, attackFrom, attackTo, multiple)
{
var attackPaper = scene.add.sprite(attackFrom.x, attackFrom.y, 'attackPaper').setScale(0.5 * multiple).setDepth(3);
attackPaper.mask = new Phaser.Display.Masks.BitmapMask(scene, BackGround.gameBackground);
attackPaper.throwTarget = attackTo;
attackPaper.follower = { t: 0, vec: new Phaser.Math.Vector2() };
attackPaper.path = new Phaser.Curves.Spline([
attackFrom.x, attackFrom.y,
(attackFrom.x + attackPaper.throwTarget.x) / 2, Math.min(attackFrom.y, attackPaper.throwTarget.y) - 100,
attackPaper.throwTarget.x, attackPaper.throwTarget.y - 10
]);
scene.tweens.add({
targets: attackPaper.follower,
t: 1,
ease: 'Linear',
duration: 4000,
repeat: 0,
onComplete: function() {
attackPaper.destroy();
WordSpace.attackPaperGroup = [];
}
});
attackPaper.moveObject = function(obj)
{
obj.path.getPoint(obj.follower.t, obj.follower.vec);
obj.setPosition(obj.follower.vec.x, obj.follower.vec.y);
obj.angle = 720 * obj.follower.t;
}
WordSpace.attackPaperGroup.push(attackPaper);
}
WordSpace.nameQueue =
{
queue: [],
shuffle: function()
{
let tempIdx, tempElement, tempLength, tempQueue = [];
let tempQueue = [];
RoomData.players.forEach(function(element){
tempQueue.push(element.index)
tempQueue.push(element.index);
})
for(tempLength = tempQueue.length; tempLength; tempLength -= 1)
{
tempIdx = Math.floor(Math.random() * tempLength);
tempElement = tempQueue[tempLength - 1];
tempQueue[tempLength - 1] = tempQueue[tempIdx];
tempQueue[tempIdx] = tempElement;
}
Phaser.Utils.Array.Shuffle(tempQueue);
tempQueue.forEach(function(element)
{
if(RoomData.players[element].id != PlayerData.id && RoomData.players[element].isAlive)
if(RoomData.players[element].id != PlayerData.id && RoomData.players[element].isAlive && WordSpace.nameQueue.getCount(RoomData.players[element]) < 3)
WordSpace.nameQueue.queue.push(element);
});
},
pop: function()
{
if(WordSpace.nameQueue.queue.length <= RoomData.aliveCount - 1) this.shuffle();
if(WordSpace.nameQueue.queue.length == 0) return null;
let tempElement = WordSpace.nameQueue.queue.shift();
if(WordSpace.nameQueue.queue.length <= RoomData.aliveCount) this.shuffle();
if(!RoomData.players[tempElement].isAlive) return WordSpace.nameQueue.pop();
if(!RoomData.players[tempElement].isAlive || WordSpace.nameQueue.getCount(RoomData.players[tempElement]) >= 3) return WordSpace.nameQueue.pop();
else return RoomData.players[tempElement];
},
getCount: function(player)
{
WordSpace.nameQueue.counter = 0;
WordSpace.nameGroup.forEach(function(element){
if(element.id == player.id) WordSpace.nameQueue.counter++;
})
WordSpace.wordGroup.forEach(function(element){
if(element instanceof NameWord && element.ownerId == player.id) WordSpace.nameQueue.counter++;
})
return WordSpace.nameQueue.counter;
},
counter: 0,
initiate: function()
{
this.shuffle();
this.shuffle();
}
}
WordSpace.getEditDistance = function(input, check) {
var inputWords = [], checkWords = []
for(let i = 0; i < input.length; i++)
{
inputWords.push(parseInt(((input[i].charCodeAt(0) - parseInt('0xac00',16)) /28) / 21) + parseInt('0x1100',16));
inputWords.push(parseInt(((input[i].charCodeAt(0)- parseInt('0xac00',16)) / 28) % 21) + parseInt('0x1161',16));
inputWords.push(parseInt((input[i].charCodeAt(0) - parseInt('0xac00',16)) % 28) + parseInt('0x11A8') -1);
}
for(let i = 0; i < check.length; i++)
{
checkWords.push(parseInt(((check[i].charCodeAt(0) - parseInt('0xac00',16)) /28) / 21) + parseInt('0x1100',16));
checkWords.push(parseInt(((check[i].charCodeAt(0)- parseInt('0xac00',16)) / 28) % 21) + parseInt('0x1161',16));
checkWords.push(parseInt((check[i].charCodeAt(0) - parseInt('0xac00',16)) % 28) + parseInt('0x11A8') -1);
}
var matrix = [];
var i, j;
for(i = 0; i <= checkWords.length; i++) // increment along the first column of each row
matrix[i] = [i];
for(j = 0; j <= inputWords.length; j++) // increment each column in the first row
matrix[0][j] = j;
for(i = 1; i <= checkWords.length; i++) // Fill in the rest of the matrix
for(j = 1; j <= inputWords.length; j++){
if(checkWords[i-1] == inputWords[j-1]) matrix[i][j] = matrix[i-1][j-1];
else matrix[i][j] = Math.min(matrix[i-1][j-1] + 1, // substitution
Math.min(matrix[i][j-1] + 1, // insertion
matrix[i-1][j] + 1)); // deletion
}
return matrix[checkWords.length][inputWords.length];
}
\ No newline at end of file
var config = {
type: Phaser.AUTO,
width: 1280,
height: 720,
width: 1920,
height: 1080,
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH
......@@ -13,18 +13,19 @@ var config = {
debug: false
}
},
backgroundColor: Phaser.Display.Color.HexStringToColor('#F0CB85').color,//GetColor(245,208,138),
scene: [ menuScene, roomScene, gameScene ]
backgroundColor: Phaser.Display.Color.HexStringToColor('#ffffff').color,//GetColor(245,208,138),
scene: [ menuScene, hopaeScene, roomScene, gameScene ]
};
var game = new Phaser.Game(config)
var game = null;
//플레이어 정보, 서버 통신시 필요할 듯
//테스트용이므로 차후 수정 요망
var PlayerData = PlayerData || {};
PlayerData.id = -1; //플레이어 아이디, 고유 번호
PlayerData.nickname = '홍길동'; //플레이어 닉네임
PlayerData.nickname = ''; //플레이어 닉네임
PlayerData.userData = null;
// 현재 들어가있는 Game Room의 정보
var RoomData = RoomData || {};
......@@ -32,4 +33,8 @@ var RoomData = RoomData || {};
RoomData.roomId = -1;
RoomData.myself = null;
RoomData.players = null;
RoomData.aliveCount = -1;
\ No newline at end of file
RoomData.aliveCount = -1;
RoomData.findPlayer = function(playerId)
{
return RoomData.players.find(function(element){ return element.id == playerId; });
}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -38,6 +38,11 @@
"resolved": "https://registry.npmjs.org/backo2/-/backo2-1.0.2.tgz",
"integrity": "sha1-MasayLEpNjRj41s+u2n038+6eUc="
},
"balanced-match": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
"integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c="
},
"base64-arraybuffer": {
"version": "0.1.5",
"resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-0.1.5.tgz",
......@@ -78,6 +83,15 @@
"type-is": "~1.6.17"
}
},
"brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"requires": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"browser-media-mime-type": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/browser-media-mime-type/-/browser-media-mime-type-1.0.0.tgz",
......@@ -93,6 +107,15 @@
"resolved": "https://registry.npmjs.org/callsite/-/callsite-1.0.0.tgz",
"integrity": "sha1-KAOY5dZkvXQDi28JBRU+borxvCA="
},
"cli": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/cli/-/cli-1.0.1.tgz",
"integrity": "sha1-IoF1NPJL+klQw01TLUjsvGIbjBQ=",
"requires": {
"exit": "0.1.2",
"glob": "^7.1.1"
}
},
"component-bind": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/component-bind/-/component-bind-1.0.0.tgz",
......@@ -108,6 +131,19 @@
"resolved": "https://registry.npmjs.org/component-inherit/-/component-inherit-0.0.3.tgz",
"integrity": "sha1-ZF/ErfWLcrZJ1crmUTVhnbJv8UM="
},
"concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s="
},
"console-browserify": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz",
"integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=",
"requires": {
"date-now": "^0.1.4"
}
},
"content-disposition": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz",
......@@ -131,6 +167,16 @@
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw="
},
"core-util-is": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
"integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac="
},
"date-now": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz",
"integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs="
},
"debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
......@@ -157,11 +203,54 @@
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
"integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
},
"dom-serializer": {
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.2.1.tgz",
"integrity": "sha512-sK3ujri04WyjwQXVoK4PU3y8ula1stq10GJZpqHIUgoGZdsGzAGu65BnU3d08aTVSvO7mGPZUc0wTEDL+qGE0Q==",
"requires": {
"domelementtype": "^2.0.1",
"entities": "^2.0.0"
},
"dependencies": {
"domelementtype": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.0.1.tgz",
"integrity": "sha512-5HOHUDsYZWV8FGWN0Njbr/Rn7f/eWSQi1v7+HsUVwXgn8nWWlL64zKDkS0n8ZmQ3mlWOMuXOnR+7Nx/5tMO5AQ=="
},
"entities": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-2.0.0.tgz",
"integrity": "sha512-D9f7V0JSRwIxlRI2mjMqufDrRDnx8p+eEOz7aUM9SuvF8gsBzra0/6tbjl1m8eQHrZlYj6PxqE00hZ1SAIKPLw=="
}
}
},
"dom-walk": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/dom-walk/-/dom-walk-0.1.1.tgz",
"integrity": "sha1-ZyIm3HTI95mtNTB9+TaroRrNYBg="
},
"domelementtype": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz",
"integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w=="
},
"domhandler": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.3.0.tgz",
"integrity": "sha1-LeWaCCLVAn+r/28DLCsloqir5zg=",
"requires": {
"domelementtype": "1"
}
},
"domutils": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz",
"integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=",
"requires": {
"dom-serializer": "0",
"domelementtype": "1"
}
},
"ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
......@@ -240,6 +329,11 @@
"has-binary2": "~1.0.2"
}
},
"entities": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-1.0.0.tgz",
"integrity": "sha1-sph6o4ITR/zeZCsk/fyeT7cSvyY="
},
"es-abstract": {
"version": "1.13.0",
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.13.0.tgz",
......@@ -273,6 +367,11 @@
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc="
},
"exit": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz",
"integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw="
},
"express": {
"version": "4.17.1",
"resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz",
......@@ -342,11 +441,29 @@
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac="
},
"fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8="
},
"function-bind": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
"integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A=="
},
"glob": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz",
"integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==",
"requires": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^3.0.4",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
}
},
"global": {
"version": "4.3.2",
"resolved": "https://registry.npmjs.org/global/-/global-4.3.2.tgz",
......@@ -382,6 +499,18 @@
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.0.tgz",
"integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q="
},
"htmlparser2": {
"version": "3.8.3",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.8.3.tgz",
"integrity": "sha1-mWwosZFRaovoZQGn15dX5ccMEGg=",
"requires": {
"domelementtype": "1",
"domhandler": "2.3",
"domutils": "1.5",
"entities": "1.0",
"readable-stream": "1.1"
}
},
"http-errors": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz",
......@@ -407,6 +536,15 @@
"resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz",
"integrity": "sha1-gtwzbSMrkGIXnQWrMpOmYFn9Q10="
},
"inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
"integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=",
"requires": {
"once": "^1.3.0",
"wrappy": "1"
}
},
"inherits": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
......@@ -472,6 +610,26 @@
"resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.1.tgz",
"integrity": "sha1-o32U7ZzaLVmGXJ92/llu4fM4dB4="
},
"jshint": {
"version": "2.10.2",
"resolved": "https://registry.npmjs.org/jshint/-/jshint-2.10.2.tgz",
"integrity": "sha512-e7KZgCSXMJxznE/4WULzybCMNXNAd/bf5TSrvVEq78Q/K8ZwFpmBqQeDtNiHc3l49nV4E/+YeHU/JZjSUIrLAA==",
"requires": {
"cli": "~1.0.0",
"console-browserify": "1.1.x",
"exit": "0.1.x",
"htmlparser2": "3.8.x",
"lodash": "~4.17.11",
"minimatch": "~3.0.2",
"shelljs": "0.3.x",
"strip-json-comments": "1.0.x"
}
},
"lodash": {
"version": "4.17.15",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz",
"integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A=="
},
"media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
......@@ -513,6 +671,14 @@
"dom-walk": "^0.1.0"
}
},
"minimatch": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
"integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
"requires": {
"brace-expansion": "^1.1.7"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
......@@ -546,6 +712,14 @@
"ee-first": "1.1.1"
}
},
"once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
"requires": {
"wrappy": "1"
}
},
"parse-headers": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/parse-headers/-/parse-headers-2.0.2.tgz",
......@@ -576,6 +750,11 @@
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="
},
"path-is-absolute": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
"integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18="
},
"path-to-regexp": {
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
......@@ -616,6 +795,24 @@
"unpipe": "1.0.0"
}
},
"readable-stream": {
"version": "1.1.14",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz",
"integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=",
"requires": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.1",
"isarray": "0.0.1",
"string_decoder": "~0.10.x"
},
"dependencies": {
"isarray": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
"integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8="
}
}
},
"right-now": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/right-now/-/right-now-1.0.0.tgz",
......@@ -674,6 +871,11 @@
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
"integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw=="
},
"shelljs": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.3.0.tgz",
"integrity": "sha1-NZbmMHp4FUT1kfN9phg2DzHbV7E="
},
"simple-media-element": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/simple-media-element/-/simple-media-element-1.1.0.tgz",
......@@ -782,6 +984,16 @@
"function-bind": "^1.0.2"
}
},
"string_decoder": {
"version": "0.10.31",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz",
"integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ="
},
"strip-json-comments": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.4.tgz",
"integrity": "sha1-HhX7ysl9Pumb8tc7TGVrCCu6+5E="
},
"to-array": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/to-array/-/to-array-0.1.4.tgz",
......@@ -829,6 +1041,11 @@
"xhr-progress": "0.0.0"
}
},
"wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8="
},
"ws": {
"version": "6.1.4",
"resolved": "https://registry.npmjs.org/ws/-/ws-6.1.4.tgz",
......
......@@ -14,6 +14,7 @@
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"jshint": "^2.10.2",
"socket.io": "^2.2.0",
"web-audio-player": "^1.3.3"
}
......
......@@ -15,11 +15,15 @@ app.get('/', function(req, res) {
// http 기본 포트(80)에 서버 열기
server.listen(80, function() {
console.log('[SERVER] Listening on port ' + server.address().port);
GameServer.serverNumber = Math.floor(Math.random() * 1000 + 1);
console.log('[SERVER] server number is ${GameServer.serverNumber}');
});
// 클라이언트 요청에 대한 콜백 정의
io.on('connection', function(socket)
{
socket.emit('syncServer', GameServer.serverNumber);
socket.on('idRequest', function() {
socket.playerData =
{
......@@ -36,21 +40,26 @@ io.on('connection', function(socket)
str: 'your number is ' + socket.playerData.id,
num: socket.playerData.id
});
GameServer.connectCount++;
});
socket.on('setNickname', function(msg) // string new_nickname
socket.on('enterRoom', function(msg) // string new_nickname
{
let isAlreadyHave = false;
GameServer.currentPlayer.forEach(function(element)
{
if (element.playerData.nickname === msg) isAlreadyHave = true;
});
if (isAlreadyHave) socket.emit('alert' ,'errNicknameOverlaped');
if(msg.length < 1) socket.emit('alert' ,'errNicknameEmpty');
else
{
socket.playerData.nickname = msg;
console.log('['+socket.playerData.id+'] nickname set to ' + msg);
GameServer.enterEmptyRoom(socket);
let isAlreadyHave = false;
GameServer.currentPlayer.forEach(function(element)
{
if (element.playerData.nickname === msg) isAlreadyHave = true;
});
if (isAlreadyHave) socket.emit('alert' ,'errNicknameOverlaped');
else
{
socket.playerData.nickname = msg;
console.log('['+socket.playerData.id+'] nickname set to ' + msg);
GameServer.enterEmptyRoom(socket);
}
}
});
......@@ -58,22 +67,29 @@ io.on('connection', function(socket)
{
try
{
socket.playerData.playingData.playerTyping = msg;
if (socket.playerData.currentRoom.maxTypingPlayer.playerTyping < msg)
socket.playerData.playingData.playerTyping = msg.playerTyping;
if (socket.playerData.currentRoom.maxTypingPlayer.playerTyping < msg.playerTyping)
{
socket.playerData.currentRoom.maxTypingPlayer = socket.playerData.playingData;
}
if (socket.playerData.currentRoom.minTypingPlayer.playerTyping > msg)
if (socket.playerData.currentRoom.minTypingPlayer.playerTyping > msg.playerTyping)
{
socket.playerData.currentRoom.minTypingPlayer = socket.playerData.playingData;
}
let playerTypingRate = (msg - (socket.playerData.currentRoom.minTypingPlayer.playerTyping - socket.playerData.currentRoom.rateArrangePoint)) /
let playerTypingRate = (msg.playerTyping - (socket.playerData.currentRoom.minTypingPlayer.playerTyping - socket.playerData.currentRoom.rateArrangePoint)) /
(socket.playerData.currentRoom.maxTypingPlayer.playerTyping - socket.playerData.currentRoom.minTypingPlayer.playerTyping + socket.playerData.currentRoom.rateArrangePoint * 2);
socket.emit('setPlayerTypingRate', playerTypingRate);
if (msg.isWord)
{
socket.playerData.currentRoom.announceToRoom('writeWord', socket.playerData.id);
}
if (msg.isAttackMode)
{
socket.playerData.currentRoom.announceToRoom('attackMode', socket.playerData.id);
}
}
catch (e)
{
}
catch (e) {console.error('[ERR] error catched on setPlayerTyping')}
});
socket.on('endCount', function()
......@@ -87,27 +103,27 @@ io.on('connection', function(socket)
socket.on('attack', function(msg)
{
socket.playerData.currentRoom.announceToTarget(msg.target, 'attacked', msg);
//console.log('attack ' + msg.target + ' by ' + msg.attacker.id + ' with ' + msg.text);
socket.playerData.currentRoom.announceToTarget(msg.victimId, 'attacked', msg);
socket.playerData.currentRoom.announceToRoom('someoneAttacked', {attackerId: msg.attackerId, victimId: msg.victimId, multiple: msg.multiple});
//console.log('attack ' + msg.victimId + ' by ' + msg.attackerId + ' with ' + msg.text);
setTimeout(function()
{
let target = GameServer.findPlayerSocket(msg.target);
let target = GameServer.findPlayerSocket(msg.victimId);
if (target != null)
{
let dataToPush =
{
attackerId: msg.attacker.id,
attacker: msg.attacker.nickname,
attackerId: msg.attackerId,
wrongCount: 0,
word: msg.text,
wordGrade: msg.grade,
time: Date.now()
}
if (target.playerData.playingData.lastAttacks.length < 5) target.playerData.playingData.lastAttacks.push(dataToPush);
else
target.playerData.playingData.lastAttacks.push(dataToPush);
while (target.playerData.playingData.lastAttacks[0].time + 20000 < Date.now())
{
target.playerData.playingData.lastAttacks.splice(0, 1);
target.playerData.playingData.lastAttacks.push(dataToPush);
}
}
}, 4000);
......@@ -120,56 +136,70 @@ io.on('connection', function(socket)
socket.on('defenseFailed', function(msg)
{
socket.playerData.currentRoom.announceToTarget(msg.target, 'attackSucceed', msg);
socket.playerData.currentRoom.announceToTarget(msg.attackerId, 'attackSucceed', msg);
let wrongCountIndex = socket.playerData.playingData.lastAttacks.findIndex(function(element)
{
return (element.word === msg.word) && (element.attackerId === msg.victimId);
});
if (wrongCountIndex !== -1) socket.playerData.playingData.lastAttacks[wrongCountIndex].wrongCount++;
});
socket.on('disconnect', function(reason)
{
GameServer.disconnectCount++;
let data = socket.playerData;
if (typeof data.id === undefined)
if (typeof data === undefined)
{
console.log('[ERROR] data.id is undefined');
console.log(GameServer.currentPlayer);
console.error('[ERROR] data is undefined');
console.table(GameServer.currentPlayer);
}
else // data.id is not undefined
{
console.log('['+ data.id +'] client disconnected, reason: ' + reason);
let idxToDel = GameServer.currentPlayer.findIndex(function(element)
{
return element.playerData.id === data.id;
});
if (idxToDel != -1)
disconnectUser(data, reason);
}
const connectDiff = GameServer.connectCount - GameServer.disconnectCount;
const playerCount = GameServer.currentPlayer.length
console.log({ connectDiff, playerCount });
});
});
var disconnectUser = function(data, reason)
{
console.log('['+ data.id +'] client disconnected, reason: ' + reason);
let idxToDel = GameServer.currentPlayer.findIndex(function(element)
{
return element.playerData.id === data.id;
});
if (idxToDel != -1)
{
// 룸에서도 제거
if (data.currentRoom != null)
{
if (data.currentRoom.currentPhase === GameServer.Phase.READY || data.currentRoom.currentPhase === GameServer.Phase.COUNT)
{
// 룸에서도 제거
if (data.currentRoom != null)
data.currentRoom.exitRoom(data.id);
if (data.currentRoom.aliveCount < data.currentRoom.startCount)
{
if (data.currentRoom.currentPhase === GameServer.Phase.READY || data.currentRoom.currentPhase === GameServer.Phase.COUNT)
{
data.currentRoom.exitRoom(data.id);
if (data.currentRoom.aliveCount < data.currentRoom.startCount)
{
data.currentRoom.announceToRoom('setRoomCount',
{
isEnable: false, endTime: 0, playerCount: data.currentRoom.currentPlayer.length,
isEnter: false, player: data.playingData
});
data.currentRoom.currentPhase = GameServer.Phase.READY;
}
else data.currentRoom.announceToRoom('setRoomCount',
{
isEnable: true, endTime: data.currentRoom.endTime, playerCount: data.currentRoom.currentPlayer.length,
isEnter: false, player: data.playingData
});
}
else if (data.playingData.isAlive)
data.currentRoom.announceToRoom('setRoomCount',
{
data.playingData.defeat();
data.currentRoom.announceToRoom('userDisconnect', data.playingData);
}
isEnable: false, endTime: 0, playerCount: data.currentRoom.currentPlayer.length,
isEnter: false, player: data.playingData
});
data.currentRoom.currentPhase = GameServer.Phase.READY;
}
GameServer.currentPlayer.splice(idxToDel, 1);
else data.currentRoom.announceToRoom('setRoomCount',
{
isEnable: true, endTime: data.currentRoom.endTime, playerCount: data.currentRoom.currentPlayer.length,
isEnter: false, player: data.playingData
});
}
else if (data.playingData.isAlive)
{
data.playingData.defeat();
data.currentRoom.announceToRoom('userDisconnect', data.playingData);
}
console.log('['+ data.id +'] disconnect complete');
}
});
});
\ No newline at end of file
GameServer.currentPlayer.splice(idxToDel, 1);
}
console.log('['+ data.id +'] disconnect complete');
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment