-
Notifications
You must be signed in to change notification settings - Fork 31
/
game.coffee
16360 lines (15570 loc) · 576 KB
/
game.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#,type シェアするやつ
Shared=
game:require '../../../client/code/shared/game.coffee'
prize:require '../../../client/code/shared/prize.coffee'
libarray = require '../../libs/array.coffee'
libblacklist = require '../../libs/blacklist.coffee'
libuserlogs = require '../../libs/userlogs.coffee'
libsavelogs = require '../../libs/savelogs.coffee'
libi18n = require '../../libs/i18n.coffee'
libgame = require '../../libs/game.coffee'
libcasting = require '../../libs/casting.coffee'
libtime = require '../../libs/time.coffee'
libspeak = require '../../libs/speak.coffee'
cron=require 'cron'
i18n = libi18n.getWithDefaultNS "game"
# 身代わりセーフティありのときの除外役職一覧
SAFETY_EXCLUDED_JOBS = Shared.game.SAFETY_EXCLUDED_JOBS
# jobs that not welcome while rebirth
REBIRTH_EXCLUDED_JOBS = ["MinionSelector","Thief","GameMaster","Helper","QuantumPlayer","Waiting","Watching","GotChocolate","HooliganGuard","HooliganAttacker","Listener","SpaceWerewolfCrew","SpaceWerewolfImposter","SpaceWerewolfObserver","SpaceWerewolfGuard","SpaceWerewolfSabotage"]
# 冒涜者によって冒涜されない役職
BLASPHEMY_DEFENCE_JOBS = ["Fugitive","QueenSpectator","Liar","Spy2","LoneWolf","AbsoluteWolf","RemoteWorker"]
# 占い結果すぐに分かるを無効化する役職
DIVINER_NOIMMEDIATE_JOBS = ["WolfBoy", "ObstructiveMad", "Pumpkin", "Patissiere", "Hypnotist", "DecoyWolf", "Shadow"]
# 会話覗き役職
LOG_PEEKING_JOBS = ["NightRabbit"]
# 村人だと思い込む役職
HUMAN_DISP_JOBS = ["Oracle","Fate","Sleepwalker","Dreamer"]
# 狩人仲間の役職
GUARD_JOBS = ["Guard", "Cosplayer", "WanderingGuard", "Samurai", "Trapper", "DragonKnight", "Elementaler"]
# 配信者が獲得できる役職
STREAMER_AVAILABLE_JOBS = [
"Diviner","Liar","PI","Forensic","Ninja","Synesthete",
"Guard","Spellcaster","Priest","Witch","Counselor","Cosplayer","MementoDisposer","Interpreter",
]
# フェイズの一覧
Phase =
# 開始前
preparing: 'preparing'
# 希望役職制
rolerequesting: 'rolerequesting'
# 昼の議論時間
day: 'day'
# 昼の猶予
day_remain: 'day_remain'
# 昼の投票専用時間
day_voting: 'day_voting'
# 夜の議論時間
night: 'night'
# 夜の猶予
night_remain: 'night_remain'
# ハンター選択中
hunter: 'hunter'
# フェイズ判定メソッド
isBeforeStart: (phase)-> phase in [Phase.preparing, Phase.rolerequesting]
isDay: (phase)-> phase in [Phase.day, Phase.day_remain, Phase.day_voting]
isNight: (phase)-> phase in [Phase.night, Phase.night_remain]
isRemain: (phase)-> phase in [Phase.day_remain, Phase.night_remain]
# Code of fortune result.
FortuneResult =
# Human
human: "human"
# Werewolf
werewolf: "werewolf"
# Vampire
vampire: "vampire"
# pumpkin
pumpkin: "pumpkin"
# oni
oni: "oni"
# Code of psychic result.
# Actual result may be string of array of string.
PsychicResult =
# Human
human: "human"
# Werewolf
werewolf: "werewolf"
# BigWolf
BigWolf: "BigWolf"
# TinyFox
TinyFox: "TinyFox"
# oni
oni: "oni"
# priority of resutls in chemical.
_chemicalPriority:
human: 0
oni: 1
werewolf: 2
BigWolf: 3
TinyFox: 3
# function to combine two results in chemical.
# filter out low priority results.
combineChemical: (res1, res2)->
# convert string result into array result.
res1 = if "string" == typeof res1
[res1]
else
res1
res2 = if "string" == typeof res2
[res2]
else
res2
both = res1.concat res2
maxPriority = Math.max both.map((res)-> PsychicResult._chemicalPriority[res])...
filtered = both.filter (res)-> maxPriority == PsychicResult._chemicalPriority[res]
result = libarray.sortedUnique filtered.sort()
# If singleton, return as string.
if result.length == 1
result[0]
else
result
# render psychic result to string.
renderToString: (res, i18n)->
# string is just rendered.
if "string" == typeof res
return i18n.t "roles:psychic.#{res}"
# if array, join them using delimiter.
delimiter = i18n.t "roles:psychic._delimiter"
return res.map((r)-> i18n.t "roles:psychic.#{r}").join delimiter
# guard_logにおける襲撃の種類
AttackKind =
werewolf: 'werewolf'
# 襲撃失敗理由
GuardReason =
# 耐性
tolerance: 'tolerance'
# 護衛
guard: 'guard'
# 何者かが身代わりになる
cover: 'cover'
# 逃亡者
absent: 'absent'
# 悪魔の力
devil: 'devil'
# 呪いの力
cursed: 'cursed'
# 聖職者・巫女
holy: 'holy'
# 罠
trap: 'trap'
# 雪女
snow: 'snow'
# 曲芸師
acrobat: 'acrobat'
# Type of open forms.
FormType =
# 必須
required: 'required'
# 任意(毎晩使用可能)
optional: 'optional'
# 任意(1回のみ)
optionalOnce: 'optionalOnce'
# utility for founds
Found =
# whether this is a guardable werewolf attack.
isGuardableWerewolfAttack: (found)->
found in ["werewolf"]
# whether this is a guardable attack.
isGuardableAttack:(found)->
found == "vampire" || Found.isGuardableWerewolfAttack(found)
# whether this is a werewolf attack.
isNormalWerewolfAttack: (found)->
found in ["werewolf", "trickedWerewolf"]
# whether this is any kind of werewolf attack.
isWerewolfAttack: (found)->
found in ["werewolf", "werewolf2", "trickedWerewolf"]
# whether this is a vampire attack.
isNormalVampireAttack: (found)->
found == "vampire"
# getAttributeで使用可能なattr
PlayerAttribute =
# ドラキュラに噛まれているフラグ
draculaBitten: "draculaBitten"
# ドラキュラの吸血を回避できるフラグ
draculaResistance: "draculaResistance"
# 浅いコピー
copyObject=(obj)->
result=Object.create Object.getPrototypeOf obj
for key in Object.keys(obj)
result[key]=obj[key]
result
# ゲームオブジェクトを読み込む
loadGame = (roomid, ss, callback)->
if games[roomid]?
callback null, games[roomid]
else
M.games.findOne {id:roomid}, { logs: 0 }, (err,doc)=>
if err?
console.error err
callback err, null
else if !doc?
callback i18n.t("error.common.noSuchGame"), null
else if games[roomid]?
# prevents duplicate instantiation of Game
callback null, games[roomid]
else
games[roomid] = Game.unserialize doc, ss
callback null, games[roomid]
#内部用
module.exports=
newGame: (room,ss, cb)->
game=new Game ss,room
games[room.id]=game
M.games.insertOne game.serialize(), {w: 1}, cb
# ゲームオブジェクトを読み込んで使用可能にする
###
loadDB:(roomid,ss,cb)->
if games[roomid]
# 既に読み込んでいる
cb games[roomid]
return
M.games.find({finished:false}).each (err,doc)->
return unless doc?
if err?
console.log err
throw err
games[doc.id]=Game.unserialize doc,ss
###
# Check whether a new user can enter an endless game
# maxnum: a maximum player number of this room
endlessCanEnter:(roomid, userid, maxnum)->
game = games[roomid]
if game?
# Check the number of existing players
num = game.players.filter((x)->!x.dead || !x.norevive).length
if num >= maxnum
return false
# Check whether a player already exists
if game.participants.some((x)-> x.realid == userid)
return false
return true
return false
# プレイヤーが入室したぞ!
inlog:(room,player)->
name="#{player.name}"
pr=""
unless room.blind in ["complete","yes"]
# 覆面のときは称号OFF
player.nowprize?.forEach? (x)->
if x.type=="prize"
prname=Server.prize.prizeName x.value
if prname?
pr+=prname
else
# 接続
pr+=x.value
# theme may have built-in prize.
if room.blind in ["complete","yes"] && room.theme
theme = Server.game.themes.getTheme room.theme
if theme != null && player.tpr
pr = player.tpr
if pr
name="#{Server.prize.prizeQuote pr}#{name}"
game = games[room.id]
unless game && !game.participants.some((p)->p.realid==player.realid)
return
if room.mode=="waiting"
# 開始前(ふつう)
log=
comment: i18n.t "system.rooms.enter", {name: name}
userid:-1
name:null
mode:"system"
if game
splashlog room.id, game, log
# プレイヤーを追加
newpl=Player.factory "Waiting", game
newpl.setProfile {
id:player.userid
realid:player.realid
name:player.name
}
newpl.setTarget null
game.players.push newpl
game.participants.push newpl
else if room.mode=="playing" && room.jobrule=="特殊ルール.エンドレス闇鍋"
# エンドレス闇鍋に途中参加
if game
log=
comment: i18n.t "system.rooms.entering", {name: name}
mode:"inlog"
to:player.userid
splashlog room.id,game,log
# プレイヤーを追加(まだ参加しない系のひと)
newpl=Player.factory "Watching", game
newpl.setProfile {
id:player.userid
realid:player.realid
name:player.name
}
newpl.setTarget null
# アイコン追加
game.iconcollection[newpl.id]=player.icon
# playersには追加しない(翌朝追加)
game.participants.push newpl
outlog:(room,player)->
log=
comment: i18n.t "system.rooms.leave", {name: player.name}
userid:-1
name:null
mode:"system"
if games[room.id]
splashlog room.id,games[room.id], log
games[room.id].players=games[room.id].players.filter (pl)->pl.realid!=player.realid
games[room.id].participants=games[room.id].participants.filter (pl)->pl.realid!=player.realid
kicklog:(room,player)->
log=
comment: i18n.t "system.rooms.kicked", {name: player.name}
userid:-1
name:null
mode:"system"
if games[room.id]
splashlog room.id,games[room.id], log
games[room.id].players=games[room.id].players.filter (pl)->pl.realid!=player.realid
games[room.id].participants=games[room.id].participants.filter (pl)->pl.realid!=player.realid
helperlog:(ss,room,player,topl)->
loadGame room.id, ss, (err,game)->
log=null
if topl?
log=
comment: i18n.t "system.rooms.helper", {helper: player.name, target: topl.name}
userid:-1
name:null
mode:"system"
else
log=
comment: i18n.t "system.rooms.stophelper", {name: player.name}
userid:-1
name:null
mode:"system"
if game?
splashlog room.id,game, log
deletedlog:(ss,room)->
loadGame room.id, ss, (err,game)->
if game?
log=
comment: i18n.t "system.rooms.abandoned"
userid:-1
name:null
mode:"system"
splashlog room.id,game, log
# 状況に応じたチャンネルを割り当てる
playerchannel:(ss,roomid,session)->
loadGame roomid, ss, (err,game)->
unless game?
return
player=game.getPlayerReal session.userId
unless player?
session.channel.subscribe "room#{roomid}_audience"
#session.channel.subscribe "room#{roomid}_notwerewolf"
#session.channel.subscribe "room#{roomid}_notcouple"
return
if player.isJobType "GameMaster"
session.channel.subscribe "room#{roomid}_gamemaster"
return
###
if player.dead
session.channel.subscribe "room#{roomid}_heaven"
if game.rule.heavenview!="view" || !player.dead
if player.isWerewolf()
session.channel.subscribe "room#{roomid}_werewolf"
else
session.channel.subscribe "room#{roomid}_notwerewolf"
if game.rule.heavenview!="view" || !player.dead
if player.isJobType "Couple"
session.channel.subscribe "room#{roomid}_couple"
else
session.channel.subscribe "room#{roomid}_notcouple"
if player.isJobType "Fox"
session.channel.subscribe "room#{roomid}_fox"
###
suddenDeathPunish:(ss, roomid, voter, targets)->
# voter: realid of voter
# targets: userids of punishment targets
game = games[roomid]
unless game?
return null
# Get the punishment data for this game
sdp = game.suddenDeathPunishment
console.log "suddenDeathPunish", roomid, voter, targets, sdp
unless sdp?
return null
# Am I a valid voter?
unless sdp.voters[voter] == true
return game.i18n.t "error.suddenDeathPunish.notvoter"
# Are all the targets valid?
unless targets.every((id)-> sdp.targets[id]?)
return game.i18n.t "error.suddenDeathPunish.invalid"
# 投票を実行
sdp.voters[voter] = false
for id in targets
banpl = sdp.targets[id]
query =
userid:banpl.realid
types:["create_account", "play"]
reason: game.i18n.t "common.suddenDeathPenalty"
banMinutes:sdp.banMinutes
libblacklist.extendBlacklist query,(result)->
ss.publish.channel "room#{roomid}", "punishresult", {id:roomid,name:banpl.name}
# 即時反映
ss.publish.user banpl.realid, "forcereload"
return null
Server=
game:
game:module.exports
rooms:require './rooms.coffee'
themes:require './themes.coffee'
prize:require '../../prize.coffee'
oauth:require '../../oauth.coffee'
log:require '../../log.coffee'
class Game
constructor:(@ss,room)->
@i18n = i18n
@players=[] # 村人たち
@participants=[] # 参加者全て(@playersと同じ内容含む)
# @ss: ss
if room?
@id=room.id
# GMがいる場合
@gm= if room.gm then room.owner.userid else null
# 観戦者の発言が許可されているか
@watchspeak = room.watchspeak
if room.gm
# GMは最初から追加されている
gmpls = room.players.filter (pl)-> pl.mode == "gm"
if gmpls[0]?
gmpl = Player.factory "GameMaster", this
gmpl.setProfile {
id: gmpls[0].userid
realid: gmpls[0].realid
name: gmpls[0].name
}
@participants.push gmpl
@rule=null
@finished=false #終了したかどうか
@day=0 #何日目か(0=準備中)
@phase = Phase.preparing
@winner=null # 勝ったチーム名
@quantum_patterns=[] # 全部の場合を列挙({(id):{jobtype:"Jobname",dead:Boolean},...})
# ログの保存モード
# v2: DBのgamelogs collectionに保存する
# v1: DBのgames内にオブジェクトのlogプロパティとして保存する
@log_save_mode = "v2"
# ----- DBには現れないプロパティ -----
@timerid=null
@timer_start=null # 残り時間のカウント開始時間(秒)
@timer_remain=null # 残り時間全体(秒)
@timer_mode=null # タイマーの名前
@revote_num=0 # 再投票を行った回数
@last_time=Date.now() # 最後に動きがあった時間
@werewolf_target=[] # 人狼の襲い先
@werewolf_target_remain=0 #襲撃先をあと何人設定できるか
@werewolf_flag=[] # 人狼襲撃に関するフラグ
# ドラキュラの吸血の成否 (true -> 成功, false -> 失敗)
@dracula_result = null
@revive_log = [] # 蘇生した人の記録
@nextturn_deferred_log = []
@guard_log = [] # 襲撃阻止の記録(for 瞳狼)
@ninja_data =
@slientexpires=0 # 静かにしてろ!(この時間まで)
@heavenview=false # 霊界表示がどうなっているか
@gamelogs=[]
@iconcollection={} #(id):(url)
# 決定配役(DBに入らないかも・・・)
@joblist=null
# ゲームスタートに必要な情報
@startoptions=null
@startplayers=null
@startsupporters=null
# 希望役職制の選択一覧
@rolerequesttable={} # 一覧{(id):(jobtype)}
# 投票箱を用意しておく
@votingbox=new VotingBox this
# 特殊ログイベント
@timeBasedEvent = null
# 保存用の時間
@finish_time=null
# ログ保存用のオブジェクト
@logsaver = new libsavelogs.LogSaver this
# 突然死の罰用のデータ
@suddenDeathPunishment = null
# ハンター割り込み処理用の次の処理フラグ
@nextScene = null
# 夜能力の対象選択に対するフック
@skillTargetHook = new SkillTargetHook this
@initTimeBasedEvent()
initTimeBasedEvent:->
@timeBasedEvent = new libtime.TimeKeeper "newyear", ->
# 来年になる瞬間
d = new Date
# 来年の1月1日にセット
d.setFullYear d.getFullYear() + 1, 0, 1
# 時刻を0時にセット
d.setHours 0, 0, 0, 0
d
# 時刻イベントを処理
# phase:
# "nextturn" if called on nextturn
# "day" if called during day
handleTimeBasedEvent:(event, phase)->
switch event.type
when "newyear"
# 新年メッセージ
if phase == "nextturn"
log=
mode: "nextturn"
day: @day
night: Phase.isNight @phase
userid: -1
name: null
comment: @i18n.t "system.phase.newyear", {year: event.goal.getFullYear()}
splashlog @id, this, log
else
log=
mode:"system"
comment: @i18n.t "system.phase.newyear", {year: event.goal.getFullYear()}
splashlog @id, this, log
###
さまざまな出来事
id: 動作した人
gamelogs=[
{id:(id),type:(type/null),target:(id,null),event:(String),flag:(String),day:(Number)},
{...},
###
# JSON用object化(DB保存用)
serialize:->
{
id:@id
#logs:@logs
rule:@rule
players:@players.map (x)->x.serialize()
# 差分
additionalParticipants: @participants?.filter((x)=>@players.indexOf(x)<0).map (x)->x.serialize()
finished:@finished
day:@day
phase:@phase
winner:@winner
jobscount:@jobscount
gamelogs:@gamelogs
gm:@gm
watchspeak:@watchspeak
iconcollection:@iconcollection
werewolf_flag:@werewolf_flag
werewolf_target:@werewolf_target
werewolf_target_remain:@werewolf_target_remain
#quantum_patterns:@quantum_patterns
finish_time:@finish_time
log_save_mode: @log_save_mode
}
#DB用をもとにコンストラクト
@unserialize:(obj,ss)->
game=new Game ss
game.id=obj.id
game.gm=obj.gm
game.watchspeak=obj.watchspeak
#game.logs=obj.logs
game.rule=obj.rule
game.players=obj.players.map (x)=>Player.unserialize x, game
# 追加する
if obj.additionalParticipants
game.participants=game.players.concat obj.additionalParticipants.map (x)->Player.unserialize x, game
else
game.participants=game.players.concat []
game.finished=obj.finished
game.day=obj.day
game.phase=obj.phase
game.winner=obj.winner
game.jobscount=obj.jobscount
game.gamelogs=obj.gamelogs ? {}
game.gm=obj.gm
game.iconcollection=obj.iconcollection ? {}
game.werewolf_flag=if Array.isArray obj.werewolf_flag
# 配列ではなく文字列/nullだった時代のあれ
obj.werewolf_flag
else if obj.werewolf_flag?
[obj.werewolf_flag]
else
[]
game.werewolf_target=obj.werewolf_target ? []
game.werewolf_target_remain=obj.werewolf_target_remain ? 0
game.log_save_mode = obj.log_save_mode ? "v1"
# 開始前ならルーム情報からプレイヤーを復元
if game.day==0
Server.game.rooms.oneRoomS game.id,(room)->
if room.error?
return
game.players=[]
supporters=[]
for plobj in room.players
if plobj.mode == "gm"
newpl = Player.factory "GameMaster", game
else
newpl=Player.factory "Waiting", game
newpl.setProfile {
id:plobj.userid
realid:plobj.realid
name:plobj.name
}
newpl.setTarget null
if plobj.mode == "gm"
game.players.push newpl
else
supporters.push newpl
game.participants=game.players.concat supporters
game.quantum_patterns=obj.quantum_patterns ? []
game.finish_time=obj.finish_time ? null
unless game.finished
if game.rule
game.timer()
if game.day>0 && Phase.isDay(game.phase)
# 昼の場合投票箱をつくる
game.votingbox.setCandidates game.players.filter (x)->!x.dead
if game.day>0 && Phase.isNight(game.phase)
# 夜の場合は夜の開始処理を行っておく
game.runSunset()
game.runScapegoatJobs()
if game.phase == Phase.hunter
# XXX hunterの場合あれを捏造
game.nextScene = "nextturn"
game
# 公開情報
publicinfo:(obj)-> #obj:オプション
{
rule:@rule
finished:@finished
players:@players.map (x)=>
r=x.publicinfo()
r.icon= @iconcollection[x.id] ? null
if obj?.openjob
r.jobname=x.getJobname()
#r.option=x.optionString()
r.option=""
r.originalJobname=x.originalJobname
r.winner=x.winner
if obj?.gm || not (@rule?.blind=="complete" || (@rule?.blind=="yes" && !@finished))
# 公開してもよい
r.realid=x.realid
r
day:@day
# for backward compatibility
night:Phase.isNight(@phase)
phase:@phase
jobscount:@jobscount
# whether watch speak is allowed.
watchspeak: @watchspeak != false
}
# IDからプレイヤー
getPlayer:(id)->
@players.filter((x)->x.id==id)[0]
getPlayerReal:(realid)->
@participants.filter((x)->x.realid==realid)[0]
# 指定したIDのプレイヤーを設定
setPlayer:(id, pl)->
for x, i in @players
if x.id == id
@players[i] = pl
for x, i in @participants
if x.id == id
@participants[i] = pl
# DBにセーブ
save:->
M.games.update {id:@id},{
$set: @serialize()
$setOnInsert: {
logs: []
}
}
# gamelogsに追加
addGamelog:(obj)->
@gamelogs ?= []
@gamelogs.push {
id:obj.id ? null
type:obj.type ? null
target:obj.target ? null
event:obj.event ? null
flag:obj.flag ? null
day:@day # 何気なく日付も追加
}
setrule:(rule)->@rule=rule
# ゲーム開始時にプレイヤー数が合ってるかチェック
checkPlayerNumber:()->
joblist = @joblist
# number of required jobs
jallnum = @startplayers.length
# 身代わり君を入れる
if @rule.scapegoat == "on"
jallnum++
# ケミカル人狼は1人2つ
if @rule.chemical == "on"
jallnum *= 2
# sum up all numbers
jnumber = 0
for job, num of joblist
n = parseInt num, 10
if Number.isNaN(n) || n < 0
return @i18n.t "error.gamestart.playerNumberInvalid1", {job: job, num: num}
jnumber += n
if jnumber != jallnum
return @i18n.t "error.gamestart.playerNumberInvalid2", {request: jnumber, jallnum: jallnum, players: @players.length}
return null
#成功:null
#players: 参加者 supporters: その他
setplayers:(res)->
options=@startoptions
players=@startplayers
supporters=@startsupporters
jnumber=0
joblist=@joblist
players=players.concat [] #コピー
plsl=players.length #実際の参加人数(身代わり含む)
if @rule.scapegoat=="on"
plsl++
# 必要な役職の
jallnum = plsl
if @rule.chemical == "on"
jallnum *= 2
@players=[]
@iconcollection={}
for job,num of joblist
unless isNaN num
jnumber+=parseInt num
if parseInt(num)<0
res @i18n.t("error.gamestart.playerNumberInvalid1", {job: job, num: num})
return
if jnumber!=jallnum
# 数が合わない
res @i18n.t("error.gamestart.playerNumberInvalid2", {request: jnumber, jallnum: jallnum, players: players.length})
return
# 名前と数を出したやつ
@jobscount={}
unless options.yaminabe_hidejobs # 公開モード
for job,num of joblist
continue unless num>0
# 村人だと思い込むシリーズは村人にまとめる
if job in HUMAN_DISP_JOBS
job = "Human"
num += (@jobscount.Human?.number ? 0)
@jobscount[job]=
name: @i18n.t "roles:jobname.#{job}"
number:num
# 盗賊の処理
thief_jobs=[]
if joblist.Thief>0
# 盗人一人につき2回抜く
for i in [0...(joblist.Thief*2)]
# 1つ抜く
keys=[]
# 数に比例した役職一覧を作る
for job,num of joblist
# 盗人自身と人外は抜かない
unless job == "Thief" || (job in Shared.game.nonhumans)
for j in [0...num]
keys.push job
keys=shuffle keys
until keys.length==0 || joblist[keys[0]]>0
# 抜けない
keys.splice 0,1
# これは抜ける
if keys.length==0
# もう無い
res @i18n.t "error.gamestart.thiefFailed"
return
thief_jobs.push keys[0]
joblist[keys[0]]--
# 代わりに村人1つ入れる
joblist.Human ?= 0
joblist.Human++
# 1人に対していくつ役職を選出するか
jobperpl = 1
if @rule.chemical == "on"
jobperpl = 2
# まず身代わりくんを決めてあげる
if @rule.scapegoat=="on"
# 人狼、妖狐にはならない
nogoat=[] #身代わりがならない役職
if @rule.safety!="free"
nogoat=nogoat.concat Shared.game.nonhumans #人外は除く
if @rule.safety=="full"
# 危ない
nogoat=nogoat.concat SAFETY_EXCLUDED_JOBS
jobss=[]
for job in Object.keys jobs
continue if !joblist[job] || (job in nogoat)
j=0
while j<joblist[job]
jobss.push job
j++
# 獲得した役職
gotjs = []
i=0 # 無限ループ防止
while ++i<100 && gotjs.length < jobperpl
r=Math.floor Math.random()*jobss.length
continue unless joblist[jobss[r]]>0
# 役職はjobss[r]
gotjs.push jobss[r]
joblist[jobss[r]]--
j++
if gotjs.length < jobperpl
# 決まっていない
res @i18n.t "error.gamestart.castingFailed"
return
# 身代わりくんのプロフィール
profile = {
id:"身代わりくん"
realid:"身代わりくん"
name: @i18n.t "common.scapegoat"
}
if @rule.chemical == "on"
# ケミカル人狼なので合体役職にする
pl1 = Player.factory gotjs[0], this
pl1.setProfile profile
pl1.scapegoat = true
pl2 = Player.factory gotjs[1], this
pl2.setProfile profile
pl2.scapegoat = true
# ケミカル合体
newpl = Player.factory null, this, pl1, pl2, Chemical
newpl.setProfile profile
newpl.scapegoat = true
newpl.setOriginalJobname newpl.getJobname()
@players.push newpl
else
# ふつーに
newpl=Player.factory gotjs[0], this #身代わりくん
newpl.setProfile profile
newpl.scapegoat = true
@players.push newpl
if @rule.rolerequest=="on" && @rule.chemical != "on"
# 希望役職制ありの場合はまず希望を優先してあげる
# (ケミカル人狼のときは面倒なのでパス)
for job,num of joblist
while num>0
# 候補を集める
conpls=players.filter (x)=>
@rolerequesttable[x.userid]==job
if conpls.length==0
# もうない
break
# 候補がいたので決めてあげる
r=Math.floor Math.random()*conpls.length
pl=conpls[r]
players=players.filter (x)->x!=pl
newpl=Player.factory job, this
newpl.setProfile {
id:pl.userid
realid:pl.realid
name:pl.name
}
@players.push newpl
if pl.icon
@iconcollection[newpl.id]=pl.icon
if pl.scapegoat
# 身代わりくん
newpl.scapegoat=true
num--
# 残った分は戻す
joblist[job]=num
# 各プレイヤーの獲得役職の一覧
gotjs = []
for i in [0...(players.length)]
gotjs.push []
# 人狼系と妖狐系を全て数える(やや適当)
all_wolves = 0
all_foxes = 0
for job,num of joblist
unless isNaN num
if job in Shared.game.categories.Werewolf
all_wolves += num
if job in Shared.game.categories.Fox
all_foxes += num
# 無限ループ防止用カウンタ
loop_count = 0
for job,num of joblist
i=0
while i++<num
r=Math.floor Math.random()*players.length
if @rule.chemical == "on" && gotjs[r].length == 1
# ケミカル人狼の場合調整が入る
if all_wolves == 1
# 人狼が1人のときは人狼を消さない
if (gotjs[r][0] in Shared.game.categories.Werewolf && job in Shared.game.categories.Fox) || (gotjs[r][0] in Shared.game.categories.Fox && job in Shared.game.categories.Werewolf)
# 人狼×妖狐はまずい
i--
if loop_count++ >= 100
# 配役失敗
res @i18n.t "error.gamestart.castingFailed"
return
continue
gotjs[r].push job
if gotjs[r].length >= jobperpl
# 必要な役職を獲得した
gotjs[r] = shuffle gotjs[r]
pl=players[r]
profile = {
id:pl.userid
realid:pl.realid
name:pl.name
}
if @rule.chemical == "on"
# ケミカル人狼
pl1 = Player.factory gotjs[r][0], this
pl1.setProfile profile
pl2 = Player.factory gotjs[r][1], this
pl2.setProfile profile
newpl = Player.factory null, this, pl1, pl2, Chemical
newpl.setProfile profile
newpl.setOriginalJobname newpl.getJobname()
@players.push newpl
else
# ふつうの人狼
newpl=Player.factory gotjs[r][0], this
newpl.setProfile profile
@players.push newpl
players.splice r,1
gotjs.splice r,1
if pl.icon
@iconcollection[newpl.id]=pl.icon
if pl.scapegoat
# 身代わりくん
newpl.scapegoat=true
if joblist.Thief>0
# 盗人がいる場合
thieves=@players.filter (x)->x.isJobType "Thief"
for pl in thieves
ts = pl.accessByJobTypeAll "Thief"
for t in ts
t.setFlag JSON.stringify thief_jobs.splice 0,2
# サブ系
if options.decider
# 決定者を作る
r=Math.floor Math.random()*@players.length
pl=@players[r]
newpl=Player.factory null, this, pl,null,Decider # 酔っ払い
pl.transProfile newpl
pl.transform @,newpl,true,true
if options.authority
# 権力者を作る
r=Math.floor Math.random()*@players.length
pl=@players[r]