-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2048kivy.py
executable file
·216 lines (188 loc) · 6.93 KB
/
2048kivy.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
#!/usr/bin/env python3
import argparse
import itertools
import os
from players.user_player import KivyPlayer
os.environ["KIVY_NO_CONSOLELOG"] = "1"
os.environ["KIVY_NO_ARGS"] = "1"
import kivy
from kivy.app import App
from kivy.clock import Clock
from kivy.config import Config
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
# import players
from players import player_factory
from grid2048 import STATE, Grid2048
kivy.require("2.1.0")
Config.set("graphics", "resizable", "0")
# register KivyPlayer instead of UserPlayer
player_factory.register("user", KivyPlayer)
COLORS = {
"0": (0.808, 0.757, 0.710, 1.0),
"2": (0.937, 0.894, 0.859, 1.0),
"4": (0.937, 0.878, 0.788, 1.0),
"8": (0.973, 0.694, 0.494, 1.0),
"16": (0.992, 0.588, 0.408, 1.0),
"32": (1.000, 0.490, 0.388, 1.0),
"64": (1.000, 0.376, 0.255, 1.0),
"128": (0.945, 0.808, 0.475, 1.0),
"256": (0.945, 0.800, 0.420, 1.0),
"512": (0.945, 0.784, 0.365, 1.0),
"1024": (0.957, 0.765, 0.310, 1.0),
"2048": (0.949, 0.769, 0.255, 1.0),
"4096": (0.180, 0.196, 0.169, 1.0),
"8192": (0.180, 0.196, 0.169, 1.0),
"16384": (0.180, 0.196, 0.169, 1.0),
"32768": (0.180, 0.196, 0.169, 1.0),
"65536": (0.170, 0.200, 0.150, 1.0),
}
TXT_LOW_COLOR = (0.471, 0.431, 0.400, 1.0)
TXT_HI_COLOR = (0.929, 0.898, 0.867, 1.0)
class Grid(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = width
self.rows = height
self.spacing = 10, 10
self.padding = 10, 10, 10, 10
self.game_board = Grid2048(self.cols, self.rows)
self.player = player_factory.create(player, self.game_board)
# self.game_board.data = [
# [0, 2, 4, 8],
# [16, 32, 64, 128],
# [256, 512, 1024, 2048],
# [4096, 8192, 16384, 32768],
# ]
self.create_widgets()
def create_widgets(self):
for _ in range(self.cols * self.rows):
tile = Button(
text="",
disabled=True,
font_size=32,
bold=True,
size_hint=(0.25, 0.25),
size=(80, 80),
disabled_color=(0.471, 0.431, 0.400, 1.0), # text color
background_color=(0.808, 0.757, 0.710, 1.0), # tile color
background_disabled_normal="",
)
self.add_widget(tile)
self.update_widgets()
def update_widgets(self):
for col, row in itertools.product(range(self.cols), range(self.rows)):
tile = self.children[row * self.cols + col]
tile.text = (
str(self.game_board[row][col]) if self.game_board[row][col] > 0 else ""
)
tile.background_color = COLORS[str(self.game_board[row][col])]
tile.color = (
TXT_LOW_COLOR if self.game_board[row][col] < 8 else TXT_HI_COLOR
)
self.children.reverse()
if self.parent:
self.parent.update_score(self.game_board.score)
if self.game_board.no_moves:
self.parent.game_over()
def play(self, **kwargs):
if self.game_board.state == STATE.RUNNING or self.game_board.no_moves:
return
moved = self.player.play(**kwargs)
if moved:
self.update_widgets()
class Game2048(BoxLayout):
paused = False
step = False
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.orientation = "vertical"
title_layout = BoxLayout(
orientation="horizontal",
size_hint=(1, 0.2),
)
self.title_btn = Button(
disabled=True,
text="2048",
font_size=40,
bold=True,
size_hint=(0.7, 1),
color=(0.937, 0.894, 0.859, 1.0),
disabled_color=(0.361, 0.306, 0.282, 1.0),
background_color=(0.741, 0.678, 0.631, 1.0),
background_disabled_normal="",
)
self.title_btn.bind(on_press=self.reset)
title_layout.add_widget(self.title_btn)
self.score_label = Label(
text="Score: 0",
font_size=20,
bold=True,
color=(1.0, 1.0, 1.0, 1.0),
)
title_layout.add_widget(self.score_label)
self.add_widget(title_layout)
self.grid = kwargs.get("grid", Grid())
self.add_widget(self.grid)
def update_score(self, score):
self.score_label.text = f"Score: {score}"
def reset(self, *args):
self.grid.game_board.reset()
self.grid.update_widgets()
self.title_btn.text = "2048"
self.title_btn.disabled = True
self.paused = False
def game_over(self):
self.title_btn.text = "Reset"
self.title_btn.disabled = False
def play(self, *args, **kwargs):
if not self.paused:
self.grid.play(**kwargs)
elif self.step:
self.grid.play(**kwargs)
self.step = False
class Game2048App(App):
def build(self):
global width, height, player
# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument(
"-c", "--cols", "--width", type=int, help="width of the grid"
)
parser.add_argument(
"-r", "--rows", "--height", type=int, help="height of the grid"
)
parser.add_argument("-i", "--interval", type=int, help="interval between moves")
parser.add_argument("-p", "--player", type=str, help="player type")
args = parser.parse_args()
interval = args.interval or 10
width = args.cols or 4
height = args.rows or 4
player = args.player or "user"
if player not in player_factory.container.keys():
# workaround for Kivy won't show the error messags when console is off
print(f"Invalid player type: {player!r}")
raise ValueError(f"Invalid player type: {player!r}")
print(f"Starting game with {width}x{height} grid and {player!r} player")
Window.size = width * 100, height * 100 + 80
Window.clearcolor = (0.741, 0.678, 0.631, 1.0)
Window.bind(on_key_down=self.key_pressed)
# Create game
self.game = Game2048()
self.title = f"2048 - {width}x{height} {player!r}"
if player != "user":
Clock.schedule_interval(self.game.play, interval / 60.0)
return self.game
def key_pressed(self, window, key, scancode, codepoint, modifier):
if key in [32]: # space
self.game.paused = not self.game.paused
if key in [13]: # enter
self.game.step = not self.game.step
if player == "user" and key in [273, 274, 275, 276]: # up, down, right, left
self.game.play(**{"dir": key})
if __name__ == "__main__":
app = Game2048App()
app.run()