pythonの勉強としてゲーム作ってみようということでpygameを使って簡単に作ってみた。音とか点数計算はできません。また詰んで進めなくなっても終了判定されない雑な作りです。
プログラミングも才能無いけどとりあえず手を動かしていく。
コード
samegame.py
#!/usr/bin/env python
import random
import math
from functools import reduce
import pygame
from pygame.locals import *
length = 600
height = 400
ballSize = 20
vBallNum = int(height/(2*ballSize))
hBallNum = int(length/(2*ballSize))
WHITE = (255,255,255)
RED = (255,0,0)
YELLOW = (255,255,0)
GREEN = (0, 128,0)
BLUE = (0, 0, 255)
CYAN = (0,255,255)
BLACK = (0,0,0)
balls = [RED, YELLOW, GREEN, BLUE, CYAN]
screen = pygame.display.set_mode((length,height))
board = [[random.choice(balls) for y in range(vBallNum)] for x in range(hBallNum)]
def drawBalls(bd):
for x, cs in enumerate(bd):
for y, c in enumerate(cs):
pygame.draw.circle(screen,c,(ballSize*(2*x+1), ballSize*((vBallNum - y - 1)*2+1)),ballSize-1)
return 0
def pickBall(ps,bd):
print(*ps)
for p in ps:
if isValidPos(p,bd): del bd[p[0]][p[1]]
align(bd)
return None
def align(bd):
for x in reversed([x for x, c in enumerate(bd) if len(c) == 0]):
del bd[x]
return None
def selectBall(p):
x = math.floor(p[0]/(2*ballSize))
y = vBallNum - 1 - math.floor(p[1]/(2*ballSize))
return (x,y)
def isValidPos(p, bd):
if p == None: return False
if p[0] < 0 or p[1] < 0: return False
if len(bd) == 0: return False
try:
bd[p[0]][p[1]]
except IndexError: return False
else: return True
def markBall(bd,pos):
if not isValidPos(pos,bd): return []
ball = bd[pos[0]][pos[1]]
def marking(p,stck):
if not isValidPos(p,bd): return stck
if p in stck: return stck
if ball == bd[p[0]][p[1]]:
stck.append(p)
return reduce(lambda stk, xy: marking(xy,stk),[(p[0],p[1]+1),(p[0],p[1]-1),(p[0]+1,p[1]),(p[0]-1,p[1])],stck)
return stck
return marking(pos,[])
pygame.init()
while True:
screen.fill(BLACK)
drawBalls(board)
pygame.display.update()
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN and event.button == 1:
print(event.pos)
ms = markBall(board,selectBall(event.pos))
if len(ms) > 1:
ms.sort(reverse=True)
print(ms)
pickBall(ms,board)
if event.type == QUIT:
pygame.quit()
sys.exit()