Python 3代码不能像我预期的那样工作

时间:2018-02-28 14:38:00

标签: python python-3.x turtle-graphics

当我遇到问题时,我正在开发一个简单的python turtle模块游戏。游戏的重点是你(红色方块)避开障碍物(蓝色圆圈)。每当蓝色圆圈到达屏幕底部时,它应该重置到顶部。当这种情况发生时,圆圈会重置一秒钟然后再传送回来。这是我的代码

#Import modules
import turtle
import time
import random

#Create window
screen = turtle.Screen()
screen.title("Street Raiders")
screen.bgcolor("black")
screen.screensize(400, 400)

#Draw border
borderPen = turtle.Turtle()
borderPen.color("white")
borderPen.pensize(3)
borderPen.speed(0)
borderPen.penup()
borderPen.hideturtle()
borderPen.setposition(-100, -100)
borderPen.pendown()

for sides in range(4):
    borderPen.fd(200)
    borderPen.lt(90)

#Create player
playerCar = turtle.Turtle()
playerCar.speed(0)
playerCar.color("red")
playerCar.shape("square")
playerCar.setheading(90)
playerCar.penup()
playerCar.setposition(0, -75)
playerX = playerCar.xcor()

#Define player movement functions
def move_left():
    global playerX
    if playerX < -85 or playerX == -85:
        playerX = -75
        playerCar.setx(playerX)
    else:
        playerX -= 10
        playerCar.setx(playerX)

def move_right():
    global playerX
    if playerX > 85 or playerX == 85:
        playerX = 75
        playerCar.setx(playerX)
    else:
        playerX += 10
        playerCar.setx(playerX)
#Allow player movement
turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")

#Create obstacles
obstacleY = 75
obstacle = turtle.Turtle()
obstacle.speed(0)
obstacle.shape("circle")
obstacle.color("blue")
obstacle.penup()
obstacle.setposition(random.randint(-80, 81), obstacleY)

#Move obstacles
alive = True
while True:
    if alive:
        obstacle.sety(75)
        obstacle.setx(random.randint(-80, 81))
        for moves in range(30):
            time.sleep(0.1)
            obstacleY -= 5
            obstacle.sety(obstacleY)
else:
    print("GAME OVER... TRY AGAIN")

`

如果你知道它为什么不起作用请回复。谢谢!

2 个答案:

答案 0 :(得分:2)

在游戏循环中,您没有将变量obstacleY的值重置为屏幕顶部;相反,你暂时设置障碍物的位置,然后它恢复了它的路线:

while True:
    if alive:
#         obstacle.sety(75)               # <-- replace this
        obstacleY = 75                    # <-- with that
        obstacle.setx(random.randint(-80, 81))
        for moves in range(30):
            time.sleep(0.1)
            obstacleY -= 5
            obstacle.sety(obstacleY)
else:
    print("GAME OVER... TRY AGAIN")

答案 1 :(得分:0)

while True:
    if alive:
        obstacle.sety(75)
        obstacle.setx(random.randint(-80, 81))
        for moves in range(30):
            time.sleep(0.1)
            obstacleY -= 5
            obstacle.sety(obstacleY)
else:
    print("GAME OVER... TRY AGAIN")

应该

while alive:
    obstacle.sety(75)
    obstacle.setx(random.randint(-80, 81))
    for moves in range(30):
        time.sleep(0.1)
        obstacleY -= 5
        obstacle.sety(obstacleY)
else:
    print("GAME OVER... TRY AGAIN")