【发布时间】:2020-07-24 22:50:29
【问题描述】:
我正在尝试使用 python 中的 turtle 模块创建游戏俄罗斯方块,但遇到了一些问题。
以前我遇到过一个问题,即构成我的方形块的一些块会从左向右移动,但不是全部。我意识到问题在于脚本在 for 循环的中间接收玩家的输入,在一些块已经移动后更新了 update_pos() 函数中的位置。
我的解决方案是在更新块的 for 循环运行时禁用玩家输入
scn.onkeypress(None, "a")
scn.onkeypress(None, "d")
但是一旦我这样做了,这些块将不再向左或向右移动。我能猜到的只是玩家输入从未正确重新启用,但我不知道为什么。
import turtle
import time
import random
last_check = time.time()
spawn_pos = (-12.5, 345)
interval = 2.5
x_input, y_input = 0, 0
colors = ["red", "yellow", "green", "blue"]
scn = turtle.Screen()
scn.setup(1280, 720)
brick = turtle.Turtle()
brick.penup()
brick.pencolor("black")
brick.speed(0)
brick.shape("square")
brick.shapesize(1.05, 1.05, 1.5)
def update_pos(current_shape):
global x_input, y_input
scn.onkeypress(None, "a")
scn.onkeypress(None, "d")
for a in range(4):
current_shape[a][1].setpos((current_shape[a][1].xcor() + x_input), (current_shape[a][1].ycor() + y_input - 25))
x_input, y_input = 0, 0
scn.onkeypress(move_left, "a")
scn.onkeypress(move_right, "d")
def spawn_square():
shape = [[(0, 0)], [(25, 0)], [(25, -25)], [(0, -25)]]
brick.fillcolor("yellow")
brick.setpos(spawn_pos)
move_bricks(shape)
return(shape)
def move_bricks(shape):
for i in range(4):
brick.fillcolor(colors[i])
shape[i].append(brick.clone())
shape[i][1].setpos((shape[i][1].xcor() + shape[i][0][0]), (shape[i][1].ycor() + shape[i][0][1]))
def move_left():
global x_input
x_input -= 25
def move_right():
global x_input
x_input += 25
scn.onkeypress(move_left, "a")
scn.onkeypress(move_right, "d")
scn.listen()
current_shape = spawn_square()
while True:
if time.time() - last_check > interval:
last_check = time.time()
if current_shape[3][1].ycor() <= -300:
y_input = 600
update_pos(current_shape)
【问题讨论】:
标签: python tetris python-turtle