-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathgame_manager.py
1133 lines (1034 loc) · 50.5 KB
/
game_manager.py
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from PyQt6.QtWidgets import QMainWindow, QFrame, QApplication, QHBoxLayout, QLabel
from PyQt6.QtCore import Qt, QBasicTimer, pyqtSignal
from PyQt6.QtGui import QPainter, QColor, QFont
from board_manager import BOARD_DATA, Shape
from block_controller import BLOCK_CONTROLLER
from block_controller_sample import BLOCK_CONTROLLER_SAMPLE
from argparse import ArgumentParser
import time
import json
import pprint
################################
# Option 取得
###############################
def get_option(game_time, mode, nextShapeMode, drop_interval, random_seed, obstacle_height, obstacle_probability, all_block_clear_score, resultlogjson, train_yaml, predict_weight, user_name, ShapeListMax, BlockNumMax, art_config_filepath):
argparser = ArgumentParser()
argparser.add_argument('--game_time', type=int,
default=game_time,
help='Specify game time(s)')
argparser.add_argument('--mode', type=str,
default=mode,
help='Specify mode (keyboard/gamepad/sample/train/art) if necessary')
argparser.add_argument('--nextShapeMode', type=str,
default=nextShapeMode,
help='Specify nextShapeMode (default/hate) if necessary')
argparser.add_argument('--drop_interval', type=int,
default=drop_interval,
help='Specify drop_interval(s)')
argparser.add_argument('--seed', type=int,
default=random_seed,
help='Specify random seed')
argparser.add_argument('--obstacle_height', type=int,
default=obstacle_height,
help='Specify obstacle height')
argparser.add_argument('--obstacle_probability', type=int,
default=obstacle_probability,
help='Specify obstacle probability')
argparser.add_argument('--all_block_clear_score', type=int,
default=all_block_clear_score,
help='Specify all_block_clear_score')
argparser.add_argument('--resultlogjson', type=str,
default=resultlogjson,
help='result json log file path')
argparser.add_argument('--train_yaml', type=str,
default=train_yaml,
help='yaml file for machine learning')
argparser.add_argument('--predict_weight', type=str,
default=predict_weight,
help='weight file for machine learning')
argparser.add_argument('-u', '--user_name', type=str,
default=user_name,
help='Specigy user name if necessary')
argparser.add_argument('--ShapeListMax', type=int,
default=ShapeListMax,
help='Specigy NextShapeNumberMax if necessary')
argparser.add_argument('--BlockNumMax', type=int,
default=BlockNumMax,
help='Specigy BlockNumMax if necessary')
argparser.add_argument('--art_config_filepath', type=str,
default=art_config_filepath,
help='art_config file path')
return argparser.parse_args()
#####################################################################
#####################################################################
# Game Manager
#####################################################################
#####################################################################
class Game_Manager(QMainWindow):
# a[n] = n^2 - n + 1
LINE_SCORE_1 = 100
LINE_SCORE_2 = 300
LINE_SCORE_3 = 700
LINE_SCORE_4 = 1300
GAMEOVER_SCORE = -500
ALL_BLOCK_CLEAR_SCORE = 0 # specified by execute option
###############################################
# 初期化
###############################################
def __init__(self):
super().__init__()
self.isStarted = False
self.isPaused = False
self.nextMove = None
self.lastShape = Shape.shapeNone
self.game_time = -1
self.block_index = 0
self.mode = "default"
self.nextShapeMode = "default"
self.drop_interval = 1000
self.random_seed = time.time() * 10000000 # 0
self.obstacle_height = 0
self.obstacle_probability = 0
self.ShapeListMax = 6
self.BlockNumMax = -1
self.resultlogjson = ""
self.user_name = ""
self.train_yaml = None
self.predict_weight = None
self.art_config_filepath = None
args = get_option(self.game_time,
self.mode,
self.nextShapeMode,
self.drop_interval,
self.random_seed,
self.obstacle_height,
self.obstacle_probability,
self.ALL_BLOCK_CLEAR_SCORE,
self.resultlogjson,
self.train_yaml,
self.predict_weight,
self.user_name,
self.ShapeListMax,
self.BlockNumMax,
self.art_config_filepath)
if args.game_time >= 0:
self.game_time = args.game_time
if args.mode in ("keyboard", "gamepad", "sample", "art", "train", "predict", "train_sample", "predict_sample", "train_sample2", "predict_sample2", "train_sample3", "predict_sample3"):
self.mode = args.mode
if args.nextShapeMode in ("default", "hate"):
self.nextShapeMode = args.nextShapeMode
if args.drop_interval >= 0:
self.drop_interval = args.drop_interval
if args.seed >= 0:
self.random_seed = args.seed
if args.obstacle_height >= 0:
self.obstacle_height = args.obstacle_height
if args.obstacle_probability >= 0:
self.obstacle_probability = args.obstacle_probability
if args.all_block_clear_score != 0:
self.ALL_BLOCK_CLEAR_SCORE = args.all_block_clear_score
if len(args.resultlogjson) != 0:
self.resultlogjson = args.resultlogjson
if len(args.user_name) != 0:
self.user_name = args.user_name
if args.ShapeListMax > 0:
self.ShapeListMax = args.ShapeListMax
if args.BlockNumMax > 0:
self.BlockNumMax = args.BlockNumMax
if args.train_yaml.endswith('.yaml'):
self.train_yaml = args.train_yaml
if args.predict_weight != "default":
self.predict_weight = args.predict_weight
if args.art_config_filepath.endswith('.json'):
self.art_config_filepath = args.art_config_filepath
self.initUI()
###############################################
# UI 初期化
###############################################
def initUI(self):
self.gridSize = 22
self.NextShapeYOffset = 90
# display maximum 4 next blocks
self.NextShapeMaxAppear = min(4, self.ShapeListMax - 1)
self.speed = self.drop_interval # block drop speed
self.timer = QBasicTimer()
self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
hLayout = QHBoxLayout()
random_seed_Nextshape = self.random_seed
self.tboard = Board(self, self.gridSize,
self.game_time,
self.nextShapeMode,
random_seed_Nextshape,
self.obstacle_height,
self.obstacle_probability,
self.ShapeListMax,
self.art_config_filepath)
hLayout.addWidget(self.tboard)
self.sidePanel = SidePanel(self, self.gridSize, self.NextShapeYOffset, self.NextShapeMaxAppear)
hLayout.addWidget(self.sidePanel)
self.statusbar = self.statusBar()
self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)
self.start()
self.center()
WindowTitle = "Tetris"
if len(self.user_name) != 0:
WindowTitle = "Tetris_" + self.user_name
self.setWindowTitle(WindowTitle)
self.show()
self.setFixedSize(self.tboard.width() + self.sidePanel.width(),
self.sidePanel.height() + self.statusbar.height())
###############################################
# Window を中心へ移動
###############################################
def center(self):
screen = self.screen().availableGeometry()
size = self.geometry()
self.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2)
###############################################
# 開始
###############################################
def start(self):
if self.isPaused:
return
self.isStarted = True
self.tboard.score = 0
##画面ボードと現テトリミノ情報をクリア
BOARD_DATA.clear()
## 新しい予告テトリミノ配列作成
BOARD_DATA.createNewPiece()
self.tboard.msg2Statusbar.emit(str(self.tboard.score))
self.timer.start(self.speed, self)
###############################################
# ポーズ
###############################################
def pause(self):
if not self.isStarted:
return
self.isPaused = not self.isPaused
if self.isPaused:
self.timer.stop()
self.tboard.msg2Statusbar.emit("paused")
else:
self.timer.start(self.speed, self)
self.updateWindow()
###############################################
# ゲームリセット (ゲームオーバー)
###############################################
def resetfield(self):
# self.tboard.score = 0
self.tboard.reset_cnt += 1
self.tboard.score += Game_Manager.GAMEOVER_SCORE
##画面ボードと現テトリミノ情報をクリア
BOARD_DATA.clear()
## 新しい予告テトリミノ配列作成
BOARD_DATA.createNewPiece()
###############################################
# 画面リセット
###############################################
def reset_all_field(self):
# reset all field for debug
# this function is mainly for machine learning
self.tboard.reset_cnt = 0
self.tboard.score = 0
self.tboard.dropdownscore = 0
self.tboard.linescore = 0
self.tboard.line = 0
self.tboard.line_score_stat = [0, 0, 0, 0]
self.tboard.line_score_stat_len = [0, 0, 0, 0]
self.tboard.start_time = time.time()
##画面ボードと現テトリミノ情報をクリア
BOARD_DATA.clear()
## 新しい予告テトリミノ配列作成
BOARD_DATA.createNewPiece()
###############################################
# Window 情報 UPDATE
###############################################
def updateWindow(self):
self.tboard.updateData()
self.sidePanel.updateData()
self.update()
###############################################
# タイマーイベント
###############################################
def timerEvent(self, event):
# callback function for user control
if event.timerId() == self.timer.timerId():
next_x = 0
next_y_moveblocknum = 0
y_operation = -1
if BLOCK_CONTROLLER and not self.nextMove:
# update CurrentBlockIndex
if BOARD_DATA.currentY <= 1:
self.block_index = self.block_index + 1
# nextMove data structure
nextMove = {"strategy":
{
"direction": "none", # next shape direction ( 0 - 3 )
"x": "none", # next x position (range: 0 - (witdh-1) )
"y_operation": "none", # movedown or dropdown (0:movedown, 1:dropdown)
"y_moveblocknum": "none", # amount of next y movement
"use_hold_function": "n", # use hold function (y:yes, n:no)
},
"option":
{ "reset_callback_function_addr":None,
"reset_all_field": None,
"force_reset_field": None,
}
}
# get nextMove from GameController
GameStatus = self.getGameStatus()
if self.mode == "sample":
# sample
self.nextMove = BLOCK_CONTROLLER_SAMPLE.GetNextMove(nextMove, GameStatus)
elif self.mode == "train_sample" or self.mode == "predict_sample":
# sample train/predict
# import block_controller_train_sample, it's necessary to install pytorch to use.
from machine_learning.block_controller_train_sample import BLOCK_CONTROLLER_TRAIN_SAMPLE as BLOCK_CONTROLLER_TRAIN
self.nextMove = BLOCK_CONTROLLER_TRAIN.GetNextMove(nextMove, GameStatus,yaml_file="config/train_sample.yaml",weight=self.predict_weight)
elif self.mode == "train_sample2" or self.mode == "predict_sample2":
# sample train/predict
# import block_controller_train_sample, it's necessary to install pytorch to use.
from machine_learning.block_controller_train_sample2 import BLOCK_CONTROLLER_TRAIN_SAMPLE2 as BLOCK_CONTROLLER_TRAIN
self.nextMove = BLOCK_CONTROLLER_TRAIN.GetNextMove(nextMove, GameStatus,yaml_file="config/train_sample2.yaml",weight=self.predict_weight)
elif self.mode == "train_sample3" or self.mode == "predict_sample3":
# sample train/predict
# import block_controller_train_sample, it's necessary to install pytorch to use.
from machine_learning.block_controller_train_sample3 import BLOCK_CONTROLLER_TRAIN_SAMPLE3 as BLOCK_CONTROLLER_TRAIN
self.nextMove = BLOCK_CONTROLLER_TRAIN.GetNextMove(nextMove, GameStatus,yaml_file="config/train_sample3.yaml",weight=self.predict_weight)
elif self.mode == "train" or self.mode == "predict":
# train/predict
# import block_controller_train, it's necessary to install pytorch to use.
from machine_learning.block_controller_train import BLOCK_CONTROLLER_TRAIN
self.nextMove = BLOCK_CONTROLLER_TRAIN.GetNextMove(nextMove, GameStatus,yaml_file=self.train_yaml,weight=self.predict_weight)
elif self.mode == "art":
# art
# print GameStatus
import pprint
print("=================================================>")
pprint.pprint(GameStatus, width = 61, compact = True)
# get direction/x/y from art_config
d,x,y = BOARD_DATA.getnextShapeIndexListDXY(self.block_index-1)
nextMove["strategy"]["direction"] = d
nextMove["strategy"]["x"] = x
nextMove["strategy"]["y_operation"] = y
nextMove["strategy"]["y_moveblocknum"] = 1
self.nextMove = nextMove
else:
self.nextMove = BLOCK_CONTROLLER.GetNextMove(nextMove, GameStatus)
if self.mode in ("keyboard", "gamepad"):
# ignore nextMove, for keyboard/gamepad controll
self.nextMove["strategy"]["x"] = BOARD_DATA.currentX
# Move Down 数
self.nextMove["strategy"]["y_moveblocknum"] = 1
# Drop Down:1, Move Down:0
self.nextMove["strategy"]["y_operation"] = 0
# テトリミノ回転数
self.nextMove["strategy"]["direction"] = BOARD_DATA.currentDirection
#######################
## 次の手を動かす
if self.nextMove:
# shape direction operation
next_x = self.nextMove["strategy"]["x"]
# Move Down 数
next_y_moveblocknum = self.nextMove["strategy"]["y_moveblocknum"]
# Drop Down:1, Move Down:0
y_operation = self.nextMove["strategy"]["y_operation"]
# テトリミノ回転数
next_direction = self.nextMove["strategy"]["direction"]
use_hold_function = self.nextMove["strategy"]["use_hold_function"]
# if use_hold_function
self.tboard.hold_isdone = False
if use_hold_function == "y":
self.tboard.hold_isdone = True
isExchangeHoldShape = BOARD_DATA.exchangeholdShape()
if isExchangeHoldShape == False:
# if isExchangeHoldShape is False, this means no holdshape exists.
# so it needs to return immediately to use new shape.
# init nextMove
self.nextMove = None
return
k = 0
while BOARD_DATA.currentDirection != next_direction and k < 4:
ret = BOARD_DATA.rotateRight()
if ret == False:
#print("cannot rotateRight")
break
k += 1
# x operation
k = 0
while BOARD_DATA.currentX != next_x and k < 5:
if BOARD_DATA.currentX > next_x:
ret = BOARD_DATA.moveLeft()
if ret == False:
#print("cannot moveLeft")
break
elif BOARD_DATA.currentX < next_x:
ret = BOARD_DATA.moveRight()
if ret == False:
#print("cannot moveRight")
break
k += 1
# dropdown/movedown lines
dropdownlines = 0
removedlines = 0
if y_operation == 1: # dropdown
## テトリミノを一番下まで落とす
removedlines, dropdownlines = BOARD_DATA.dropDown()
else: # movedown, with next_y_moveblocknum lines
k = 0
# Move down を1つずつ処理
while True:
## テノリミノを1つ落とし消去ラインとテトリミノ落下数を返す
removedlines, movedownlines = BOARD_DATA.moveDown()
# Drop してたら除外 (テトリミノが1つも落下していない場合)
if movedownlines < 1:
# if already dropped
break
k += 1
if k >= next_y_moveblocknum:
# if already movedown next_y_moveblocknum block
break
# 消去ライン数と落下数によりスコア計算
self.UpdateScore(removedlines, dropdownlines)
##############################
#
# check reset field
#if BOARD_DATA.currentY < 1:
if BOARD_DATA.currentY < 1 or self.nextMove["option"]["force_reset_field"] == True:
# if Piece cannot movedown and stack, reset field
if self.nextMove["option"]["reset_callback_function_addr"] != None:
# if necessary, call reset_callback_function
reset_callback_function = self.nextMove["option"]["reset_callback_function_addr"]
reset_callback_function()
if self.nextMove["option"]["reset_all_field"] == True:
# reset all field if debug option is enabled
print("reset all field.")
self.reset_all_field()
else:
# ゲームリセット = ゲームオーバー
self.resetfield()
# init nextMove
self.nextMove = None
# update window
self.updateWindow()
return
else:
super(Game_Manager, self).timerEvent(event)
###############################################
# 消去ライン数と落下数によりスコア計算
###############################################
def UpdateScore(self, removedlines, dropdownlines):
# calculate and update current score
# 消去ライン数で計算
if removedlines == 1:
linescore = Game_Manager.LINE_SCORE_1
elif removedlines == 2:
linescore = Game_Manager.LINE_SCORE_2
elif removedlines == 3:
linescore = Game_Manager.LINE_SCORE_3
elif removedlines == 4:
linescore = Game_Manager.LINE_SCORE_4
else:
linescore = 0
# 落下スコア計算
dropdownscore = dropdownlines
self.tboard.dropdownscore += dropdownscore
# 合計計算
self.tboard.linescore += linescore
self.tboard.score += ( linescore + dropdownscore )
self.tboard.line += removedlines
# 同時消去数をカウント
if removedlines > 0:
self.tboard.line_score_stat[removedlines - 1] += 1
self.tboard.line_score_stat_len[removedlines - 1] += 1
else:
# 連続して消去していない場合の初期化
self.tboard.line_score_stat_len = [0, 0, 0, 0]
# perfect clear判定
self.tboard.allblockclear_isdone = False
if removedlines > 0:
width = BOARD_DATA.width
height = BOARD_DATA.height
data = BOARD_DATA.getData()
if data.count(0) == width*height:
self.tboard.allblockclear_isdone = True
self.tboard.score += self.ALL_BLOCK_CLEAR_SCORE
self.tboard.all_block_clear_cnt += 1
###############################################
# ゲーム情報の取得
###############################################
def getGameStatus(self):
# return current Board status.
# define status data.
status = {"field_info":
{
"width": "none",
"height": "none",
"backboard": "none",
"withblock": "none", # back board with current block
},
"block_info":
{
"currentX":"none",
"currentY":"none",
"currentDirection":"none",
"currentShape":{
"class":"none",
"index":"none",
"direction_range":"none",
},
"nextShape":{
"class":"none",
"index":"none",
"direction_range":"none",
},
"nextShapeList":{
},
"holdShape":{
"class":"none",
"index":"none",
"direction_range":"none",
},
},
"judge_info":
{
"elapsed_time":"none",
"game_time":"none",
"gameover_count":"none",
"all_block_clear_count":"none",
"score":"none",
"line":"none",
"block_index":"none",
"block_num_max":"none",
"mode":"none",
},
"debug_info":
{
"dropdownscore":"none",
"linescore":"none",
"line_score": {
"line1":"none",
"line2":"none",
"line3":"none",
"line4":"none",
"gameover":"none",
"all_block_clear":"none",
},
"shape_info": {
"shapeNone": {
"index" : "none",
"color" : "none",
},
"shapeI": {
"index" : "none",
"color" : "none",
},
"shapeL": {
"index" : "none",
"color" : "none",
},
"shapeJ": {
"index" : "none",
"color" : "none",
},
"shapeT": {
"index" : "none",
"color" : "none",
},
"shapeO": {
"index" : "none",
"color" : "none",
},
"shapeS": {
"index" : "none",
"color" : "none",
},
"shapeZ": {
"index" : "none",
"color" : "none",
},
},
"line_score_stat":"none",
"line_score_stat_len":"none",
"shape_info_stat":"none",
"random_seed":"none",
"obstacle_height":"none",
"obstacle_probability":"none"
},
}
# update status
## board
status["field_info"]["width"] = BOARD_DATA.width
status["field_info"]["height"] = BOARD_DATA.height
status["field_info"]["backboard"] = BOARD_DATA.getData()
status["field_info"]["withblock"] = BOARD_DATA.getDataWithCurrentBlock()
## shape
status["block_info"]["currentX"] = BOARD_DATA.currentX
status["block_info"]["currentY"] = BOARD_DATA.currentY
status["block_info"]["currentDirection"] = BOARD_DATA.currentDirection
### current shape
currentShapeClass, currentShapeIdx, currentShapeRange = BOARD_DATA.getShapeData(0)
status["block_info"]["currentShape"]["class"] = currentShapeClass
status["block_info"]["currentShape"]["index"] = currentShapeIdx
status["block_info"]["currentShape"]["direction_range"] = currentShapeRange
### next shape
nextShapeClass, nextShapeIdx, nextShapeRange = BOARD_DATA.getShapeData(1)
status["block_info"]["nextShape"]["class"] = nextShapeClass
status["block_info"]["nextShape"]["index"] = nextShapeIdx
status["block_info"]["nextShape"]["direction_range"] = nextShapeRange
### next shape list
for i in range(BOARD_DATA.getShapeListLength()):
ElementNo="element" + str(i)
ShapeClass, ShapeIdx, ShapeRange = BOARD_DATA.getShapeData(i)
status["block_info"]["nextShapeList"][ElementNo] = {
"class":ShapeClass,
"index":ShapeIdx,
"direction_range":ShapeRange,
}
### hold shape
holdShapeClass, holdShapeIdx, holdShapeRange = BOARD_DATA.getholdShapeData()
status["block_info"]["holdShape"]["class"] = holdShapeClass
status["block_info"]["holdShape"]["index"] = holdShapeIdx
status["block_info"]["holdShape"]["direction_range"] = holdShapeRange
### next shape
## judge_info
status["judge_info"]["elapsed_time"] = round(time.time() - self.tboard.start_time, 3)
status["judge_info"]["game_time"] = self.game_time
status["judge_info"]["gameover_count"] = self.tboard.reset_cnt
status["judge_info"]["all_block_clear_count"] = self.tboard.all_block_clear_cnt
status["judge_info"]["score"] = self.tboard.score
status["judge_info"]["line"] = self.tboard.line
status["judge_info"]["block_index"] = self.block_index
status["judge_info"]["block_num_max"] = self.BlockNumMax
status["judge_info"]["mode"] = self.mode
## debug_info
status["debug_info"]["dropdownscore"] = self.tboard.dropdownscore
status["debug_info"]["linescore"] = self.tboard.linescore
status["debug_info"]["line_score_stat"] = self.tboard.line_score_stat
status["debug_info"]["line_score_stat_len"] = self.tboard.line_score_stat_len
status["debug_info"]["shape_info_stat"] = BOARD_DATA.shape_info_stat
status["debug_info"]["hold_isdone"] = self.tboard.hold_isdone
status["debug_info"]["allblockclear_isdone"] = self.tboard.allblockclear_isdone
status["debug_info"]["line_score"]["line1"] = Game_Manager.LINE_SCORE_1
status["debug_info"]["line_score"]["line2"] = Game_Manager.LINE_SCORE_2
status["debug_info"]["line_score"]["line3"] = Game_Manager.LINE_SCORE_3
status["debug_info"]["line_score"]["line4"] = Game_Manager.LINE_SCORE_4
status["debug_info"]["line_score"]["gameover"] = Game_Manager.GAMEOVER_SCORE
status["debug_info"]["line_score"]["all_block_clear"] = self.ALL_BLOCK_CLEAR_SCORE
status["debug_info"]["shape_info"]["shapeNone"]["index"] = Shape.shapeNone
status["debug_info"]["shape_info"]["shapeI"]["index"] = Shape.shapeI
status["debug_info"]["shape_info"]["shapeI"]["color"] = "red"
status["debug_info"]["shape_info"]["shapeL"]["index"] = Shape.shapeL
status["debug_info"]["shape_info"]["shapeL"]["color"] = "green"
status["debug_info"]["shape_info"]["shapeJ"]["index"] = Shape.shapeJ
status["debug_info"]["shape_info"]["shapeJ"]["color"] = "purple"
status["debug_info"]["shape_info"]["shapeT"]["index"] = Shape.shapeT
status["debug_info"]["shape_info"]["shapeT"]["color"] = "gold"
status["debug_info"]["shape_info"]["shapeO"]["index"] = Shape.shapeO
status["debug_info"]["shape_info"]["shapeO"]["color"] = "pink"
status["debug_info"]["shape_info"]["shapeS"]["index"] = Shape.shapeS
status["debug_info"]["shape_info"]["shapeS"]["color"] = "blue"
status["debug_info"]["shape_info"]["shapeZ"]["index"] = Shape.shapeZ
status["debug_info"]["shape_info"]["shapeZ"]["color"] = "yellow"
status["debug_info"]["random_seed"] = self.random_seed
status["debug_info"]["obstacle_height"] = self.obstacle_height
status["debug_info"]["obstacle_probability"] = self.obstacle_probability
if currentShapeIdx == Shape.shapeNone:
print("warning: current shape is none !!!")
return status
def getGameStatusJson(self):
status = {
"debug_info":
{
"line_score": {
"line1":"none",
"line2":"none",
"line3":"none",
"line4":"none",
"gameover":"none",
"all_block_clear":"none",
},
"shape_info": {
"shapeNone": {
"index" : "none",
"color" : "none",
},
"shapeI": {
"index" : "none",
"color" : "none",
},
"shapeL": {
"index" : "none",
"color" : "none",
},
"shapeJ": {
"index" : "none",
"color" : "none",
},
"shapeT": {
"index" : "none",
"color" : "none",
},
"shapeO": {
"index" : "none",
"color" : "none",
},
"shapeS": {
"index" : "none",
"color" : "none",
},
"shapeZ": {
"index" : "none",
"color" : "none",
},
},
"line_score_stat":"none",
"line_score_stat_len":"none",
"shape_info_stat":"none",
"hold_isdone":"none",
"allblockclear_isdone":"none",
"random_seed":"none",
"obstacle_height":"none",
"obstacle_probability":"none",
},
"judge_info":
{
"elapsed_time":"none",
"game_time":"none",
"gameover_count":"none",
"all_block_clear_count":"none",
"score":"none",
"line":"none",
"block_index":"none",
"block_num_max":"none",
"mode":"none",
},
}
# update status
## debug_info
status["debug_info"]["line_score_stat"] = self.tboard.line_score_stat
status["debug_info"]["line_score_stat_len"] = self.tboard.line_score_stat_len
status["debug_info"]["shape_info_stat"] = BOARD_DATA.shape_info_stat
status["debug_info"]["hold_isdone"] = self.tboard.hold_isdone
status["debug_info"]["allblockclear_isdone"] = self.tboard.allblockclear_isdone
status["debug_info"]["line_score"]["line1"] = Game_Manager.LINE_SCORE_1
status["debug_info"]["line_score"]["line2"] = Game_Manager.LINE_SCORE_2
status["debug_info"]["line_score"]["line3"] = Game_Manager.LINE_SCORE_3
status["debug_info"]["line_score"]["line4"] = Game_Manager.LINE_SCORE_4
status["debug_info"]["line_score"]["gameover"] = Game_Manager.GAMEOVER_SCORE
status["debug_info"]["line_score"]["all_block_clear"] = self.ALL_BLOCK_CLEAR_SCORE
status["debug_info"]["shape_info"]["shapeNone"]["index"] = Shape.shapeNone
status["debug_info"]["shape_info"]["shapeI"]["index"] = Shape.shapeI
status["debug_info"]["shape_info"]["shapeI"]["color"] = "red"
status["debug_info"]["shape_info"]["shapeL"]["index"] = Shape.shapeL
status["debug_info"]["shape_info"]["shapeL"]["color"] = "green"
status["debug_info"]["shape_info"]["shapeJ"]["index"] = Shape.shapeJ
status["debug_info"]["shape_info"]["shapeJ"]["color"] = "purple"
status["debug_info"]["shape_info"]["shapeT"]["index"] = Shape.shapeT
status["debug_info"]["shape_info"]["shapeT"]["color"] = "gold"
status["debug_info"]["shape_info"]["shapeO"]["index"] = Shape.shapeO
status["debug_info"]["shape_info"]["shapeO"]["color"] = "pink"
status["debug_info"]["shape_info"]["shapeS"]["index"] = Shape.shapeS
status["debug_info"]["shape_info"]["shapeS"]["color"] = "blue"
status["debug_info"]["shape_info"]["shapeZ"]["index"] = Shape.shapeZ
status["debug_info"]["shape_info"]["shapeZ"]["color"] = "yellow"
status["debug_info"]["random_seed"] = self.random_seed
status["debug_info"]["obstacle_height"] = self.obstacle_height
status["debug_info"]["obstacle_probability"] = self.obstacle_probability
## judge_info
status["judge_info"]["elapsed_time"] = round(time.time() - self.tboard.start_time, 3)
status["judge_info"]["game_time"] = self.game_time
status["judge_info"]["gameover_count"] = self.tboard.reset_cnt
status["judge_info"]["all_block_clear_count"] = self.tboard.all_block_clear_cnt
status["judge_info"]["score"] = self.tboard.score
status["judge_info"]["line"] = self.tboard.line
status["judge_info"]["block_index"] = self.block_index
status["judge_info"]["block_num_max"] = self.BlockNumMax
status["judge_info"]["mode"] = self.mode
return json.dumps(status)
###############################################
# キー入力イベント処理 -m keyboard, gamepad
# QMainWindow 継承
###############################################
def keyPressEvent(self, event):
# for keyboard/gamepad control
# スタート前はキーキャプチャしない
if not self.isStarted or BOARD_DATA.currentShape == Shape.shapeNone:
super(Game_Manager, self).keyPressEvent(event)
return
key = event.key()
# key event handle process.
# depends on self.mode, it's better to make key config file.
# "keyboard" : PC keyboard controller
# "gamepad" : game controller. KeyUp, space are different
if key == Qt.Key.Key_P:
self.pause()
return
if self.isPaused:
return
elif key == Qt.Key.Key_Left:
BOARD_DATA.moveLeft()
elif key == Qt.Key.Key_Right:
BOARD_DATA.moveRight()
elif (key == Qt.Key.Key_Up and self.mode == 'keyboard') or (key == Qt.Key.Key_Space and self.mode == 'gamepad'):
BOARD_DATA.rotateLeft()
elif key == Qt.Key.Key_M:
## テノリミノを1つ落とし消去ラインとテトリミノ落下数を返す
removedlines, movedownlines = BOARD_DATA.moveDown()
# 消去ライン数によりスコア計算
self.UpdateScore(removedlines, 0)
elif (key == Qt.Key.Key_Space and self.mode == 'keyboard') or (key == Qt.Key.Key_Up and self.mode == 'gamepad'):
## テトリミノを一番下まで落とす
removedlines, dropdownlines = BOARD_DATA.dropDown()
# 消去ライン数と落下数によりスコア計算
self.UpdateScore(removedlines, dropdownlines)
elif key == Qt.Key.Key_C:
print("cc!!")
self.tboard.hold_isdone = True
BOARD_DATA.exchangeholdShape()
else:
# スタート前はキーキャプチャしない
super(Game_Manager, self).keyPressEvent(event)
self.updateWindow()
###############################################
# 四角形の描画
###############################################
def drawSquare(painter, x, y, val, s):
colorTable = BOARD_DATA.getcolorTable()
# treat values as integer explicitly
x = int(x)
y = int(y)
val = int(val)
s = int(s)
if val == 0:
return
color = QColor(colorTable[val])
painter.fillRect(x + 1, y + 1, s - 2, s - 2, color)
painter.setPen(color.lighter())
painter.drawLine(x, y + s - 1, x, y)
painter.drawLine(x, y, x + s - 1, y)
painter.setPen(color.darker())
painter.drawLine(x + 1, y + s - 1, x + s - 1, y + s - 1)
painter.drawLine(x + s - 1, y + s - 1, x + s - 1, y + 1)
###############################################
###############################################
# 横画面描画
###############################################
###############################################
class SidePanel(QFrame):
###############################################
# 初期化
###############################################
def __init__(self, parent, gridSize, NextShapeYOffset, NextShapeMaxAppear):
super().__init__(parent)
self.setFixedSize(gridSize * 5, gridSize * BOARD_DATA.height)
self.move(gridSize * BOARD_DATA.width, 0)
self.gridSize = gridSize
self.NextShapeYOffset = NextShapeYOffset
self.NextShapeMaxAppear = NextShapeMaxAppear
###############################################
# UPDATE
###############################################
def updateData(self):
self.update()
###############################################
# 描画イベント
###############################################
def paintEvent(self, event):
painter = QPainter(self)
ShapeListLength = BOARD_DATA.getShapeListLength()
# draw next shape
for i in range(ShapeListLength):
if i == 0:
# skip current shape
continue
if i > self.NextShapeMaxAppear:
break
ShapeClass, ShapeIdx, ShapeRange = BOARD_DATA.getShapeData(i) # nextShape
# テトリミノが原点から x,y 両方向に最大何マス占有するのか取得
minX, maxX, minY, maxY = ShapeClass.getBoundingOffsets(0)
dy = 1 * self.gridSize
dx = (self.width() - (maxX - minX) * self.gridSize) / 2
val = ShapeClass.shape
y_offset = self.NextShapeYOffset * (i - 1) #(self.NextShapeMaxAppear - i)
# テトリミノを配置すべき座標リストを取得していく
for x, y in ShapeClass.getCoords(0, 0, -minY):
drawSquare(painter, x * self.gridSize + dx, y * self.gridSize + dy + y_offset, val, self.gridSize)
# draw hold block area
painter.setPen(QColor(0x777777))
height_offset = self.height() - int(self.gridSize*4.65)
painter.drawLine(0, height_offset,
self.width(), height_offset)
painter.drawText(0, self.height(), 'HOLD');
# draw
holdShapeClass, holdShapeIdx, holdShapeRange = BOARD_DATA.getholdShapeData()
if holdShapeClass != None:
# if holdShape exists, try to draw
minX, maxX, minY, maxY = holdShapeClass.getBoundingOffsets(0)
dy = 1 * self.gridSize
dx = (self.width() - (maxX - minX) * self.gridSize) / 2
val = holdShapeClass.shape
y_offset = self.NextShapeYOffset * 4
for x, y in holdShapeClass.getCoords(0, 0, -minY):
drawSquare(painter, x * self.gridSize + dx, y * self.gridSize + dy + y_offset, val, self.gridSize)
#####################################################################
#####################################################################
# 画面ボード描画
#####################################################################
#####################################################################
class Board(QFrame):
msg2Statusbar = pyqtSignal(str)
###############################################
# 初期化
###############################################
def __init__(self, parent, gridSize, game_time, nextShapeMode, random_seed, obstacle_height, obstacle_probability, ShapeListMax, art_config_filepath):
super().__init__(parent)
self.setFixedSize(gridSize * BOARD_DATA.width, gridSize * BOARD_DATA.height)
self.gridSize = gridSize
self.game_time = game_time
self.initBoard(nextShapeMode, random_seed, obstacle_height, obstacle_probability, ShapeListMax, art_config_filepath)
###############################################
# 画面ボード初期化
###############################################
def initBoard(self, nextShapeMode, random_seed_Nextshape, obstacle_height, obstacle_probability, ShapeListMax, art_config_filepath):
self.score = 0
self.dropdownscore = 0
self.linescore = 0
self.line = 0
self.line_score_stat = [0, 0, 0, 0]
self.line_score_stat_len = [0, 0, 0, 0]
self.hold_isdone = False
self.allblockclear_isdone = False
self.all_block_clear_cnt = 0
self.reset_cnt = 0
self.start_time = time.time()
##画面ボードと現テトリミノ情報をクリア
BOARD_DATA.clear()
BOARD_DATA.init_randomseed(random_seed_Nextshape)
BOARD_DATA.init_obstacle_parameter(obstacle_height, obstacle_probability)
BOARD_DATA.init_shape_parameter(ShapeListMax, nextShapeMode)
BOARD_DATA.init_art_config(art_config_filepath)