【Python】俄罗斯方块源码
本帖最后由 wushaominkk 于 2018-6-1 10:49 编辑源码可能不容易看懂
附上两张流程图
注意:
1,图形旋转写的有些粗糙,玩起来可能有些小毛病
2,使用的是pygame玩的话要先安装库
import pygame, sys, random, time
# 第二版
def new_draw():
screen.fill(white)
for i in range(1, 21):
for j in range(10):
bolck = background
if bolck:
pygame.draw.rect(screen, blue, (j * 25 + 1, 500 - i * 25 + 1, 23, 23))
x, y = centre
for i, j in active:
i += x
j += y
pygame.draw.rect(screen, blue, (j * 25 + 1, 500 - i * 25 + 1, 23, 23))
pygame.display.update()
def move_LR(n):
"""n=-1代表向左,n=1代表向右"""
x, y = centre
y += n
for i, j in active:
i += x
j += y
if j < 0 or j > 9 or background:
break
else:
centre.clear()
centre.extend()
def rotate():
x, y = centre
l = [(-j, i) for i, j in active]
for i, j in l:
i += x
j += y
if j < 0 or j > 9 or background:
break
else:
active.clear()
active.extend(l)
def move_down():
x, y = centre
x -= 1
for i, j in active:
i += x
j += y
if background:
break
else:
centre.clear()
centre.extend()
return
# 如果新位置未被占用 通过return结束
# 如果新位置被占用则继续向下执行
x, y = centre
for i, j in active:
background = 1
l = []
for i in range(1, 20):
if 0 not in background:
l.append(i)
# l装 行号,鉴于删去后,部分索引变化,对其降序排列,倒着删除
l.sort(reverse=True)
for i in l:
background.pop(i)
background.append()
# 随删随补
score += len(l)
pygame.display.set_caption("分数:%d" % (score))
active.clear()
active.extend(list(random.choice(all_block)))
# all_block保存7种形状的信息,手打出来的
centre.clear()
centre.extend()
x, y = centre
for i, j in active:
i += x
j += y
if background:
break
else:
return
alive.append(1)
pygame.init()
screen = pygame.display.set_mode((250, 500))
pygame.display.set_caption("俄罗斯方块")
fclock = pygame.time.Clock()
all_block = (((0, 0), (0, -1), (0, 1), (0, 2)),
((0, 0), (0, 1), (-1, 0), (-1, 1)),
((0, 0), (0, -1), (-1, 0), (-1, 1)),
((0, 0), (0, 1), (-1, -1), (-1, 0)),
((0, 0), (0, 1), (1, 0), (0, -1)),
((0, 0), (1, 0), (-1, 0), (1, -1)),
((0, 0), (1, 0), (-1, 0), (1, 1)))
background = [ for j in range(24)]
background =
active = list(random.choice(all_block))
centre =
score =
black = 0, 0, 0
white = 255, 255, 255
blue = 0, 0, 255
times = 0
alive = []
press = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
move_LR(-1)
elif event.key == pygame.K_RIGHT:
move_LR(1)
elif event.key == pygame.K_UP:
rotate()
elif event.key == pygame.K_DOWN:
press = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN:
press = False
if press:
times += 10
if times >= 50:
move_down()
times = 0
else:
times += 1
if alive:
pygame.display.set_caption("over分数:%d" % (score))
time.sleep(3)
break
new_draw()
fclock.tick(100)
Hakon 发表于 2018-5-31 22:08
还是不太懂方块要如何与已有的“地形”做碰撞判定。
俄罗斯方块没那么复杂,,只是一个10X20二维的点阵
全局变量background二维数组,保存着背景 (0为空,1为有方块)
拿方块的坐标去挨个查数组就知道有没有 “重叠”“碰撞”了 linuxprobe 发表于 2018-5-31 21:23
老游戏了,现在还有源码写出来。
没办法的呀,适合新手练习的游戏并不多{:1_937:} 热心并受欢迎 学习了,。 挺不错的 学习了 大神······················ 感谢分享~~ 学习了~{ 学习下大神的思路 学习了,悲催,没学会 学习了大佬,你太厉害了 感谢分享,学习了