Created
September 27, 2014 10:58
-
-
Save yonchu/e25a7550a6626da8dcc0 to your computer and use it in GitHub Desktop.
Puyo in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding:utf-8 -*- | |
""" | |
Puyo in Python. | |
Original code: | |
http://qiita.com/arc279/items/d0a0bc2cfc710f7b1ffe | |
http://okajima.air-nifty.com/b/2011/01/2011-ffac.html | |
""" | |
from __future__ import print_function | |
from decimal import Decimal | |
import time | |
puyo_array = [ | |
' GYRR', | |
'RYYGYG', | |
'GYGYRR', | |
'RYGYRG', | |
'YGYRYG', | |
'GYRYRG', | |
'YGYRYR', | |
'YGYRYR', | |
'YRRGRG', | |
'RYGYGG', | |
'GRYGYR', | |
'GRYGYR', | |
'GRYGYR', | |
] | |
puyo = [bytearray(line, 'utf-8') for line in puyo_array] | |
height = len(puyo) | |
width = len(puyo[0]) | |
# 隣接4方向のベクトル | |
dxy = ((1, 0), (0, 1), (-1, 0), (0, -1)) | |
def show(): | |
"""Show puyo.""" | |
print('-' * 8) | |
for x in puyo: | |
print('|{}|'.format(x.decode('utf-8'))) | |
print('-' * 8) | |
print() | |
def same_puyo(cur, same): | |
u"""隣接する同じぷよを再帰的に探す. | |
cur: (x, y) - 現在点 | |
same: list - 同じぷよの座標リスト [(x, y), ...] | |
Returns: same | |
""" | |
# 現在点を same に追加 | |
same.append(cur) | |
# 移動4方向をループ | |
for di in dxy: | |
# 隣接点 nex | |
nex = (cur[0] + di[0], cur[1] + di[1]) | |
# 隣接点と現在点のぷよが同じか、探索済みかどうかを判定 | |
if 0 <= nex[0] < width and 0 <= nex[1] < height \ | |
and nex not in same \ | |
and puyo[nex[1]][nex[0]] == puyo[cur[1]][cur[0]]: | |
same_puyo(nex, same) | |
return same | |
def erase(): | |
u"""ぷよを消す.""" | |
for y in range(height): | |
for x in range(width): | |
if chr(puyo[y][x]) == ' ': | |
continue | |
same = same_puyo((x, y), []) | |
if len(same) < 4: | |
continue | |
# 消去 | |
for p in same: | |
puyo[p[1]][p[0]] = ord(' ') | |
def drop(): | |
u"""浮いてるの落とす.""" | |
is_zenkeshi = True | |
for x in range(width): | |
for y in range(height)[::-1]: | |
if chr(puyo[y][x]) == ' ': | |
for y2 in range(y + 1)[::-1]: | |
if chr(puyo[y2][x]) != ' ': | |
puyo[y][x] = puyo[y2][x] | |
puyo[y2][x] = ord(' ') | |
break | |
else: | |
is_zenkeshi = False | |
# 全部消えてたらTrue | |
return is_zenkeshi | |
def solve(): | |
"""Solve Puyo-Puyo.""" | |
i = 0 | |
while 1: | |
print(i) | |
i += 1 | |
show() | |
erase() | |
if drop(): | |
break | |
print(i) | |
print('finish!!') | |
show() | |
if __name__ == '__main__': | |
start = Decimal(time.clock()) | |
solve() | |
print('time:', format(Decimal(time.clock()) - start, '.3g')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment