1
我目前正在尝试使用龟图形在python中制作蛇游戏,并且遇到游戏打破错误时,如果您使用a和d键打开乌龟,前一回合。它似乎正在执行代码乱序,但我不知道发生了什么。代码以奇怪的顺序与乌龟图形执行
整个代码如下
import turtle
import random
import math
x = 400
y = 400
global speed
global points
points = 0
speed = 2
posList = ['']
# turns your character left
def left():
global speed
global posList
key = True
char.fd(speed)
char.left(90)
char.fd(speed)
# turns your character left
def right():
global speed
global posList
key = True
char.fd(speed)
char.right(90)
char.fd(speed)
# adds one box to the point counter
def point():
global points
points += 1
wall.speed(0)
wall.pendown()
wall.forward(50)
wall.seth(90)
wall.forward(10)
wall.seth(180)
wall.forward(50)
wall.seth(270)
wall.forward(10)
wall.penup()
wall.seth(90)
wall.forward(12)
wall.seth(0)
dot.setx(random.randint(-200,200))
dot.sety(random.randint(-200,200))
print(points)
# checks if curren posisition is anywhere you have ever been
def checkBracktrack(pos, poslist):
found = False
for thing in posList:
if thing == pos:
found=True
return found
# creates the box that the game occurs in
turtle.colormode(255)
screen = turtle.Screen()
dot = turtle.Turtle()
dot.penup()
dot.speed(0)
dot.shape('turtle')
dot.setx(random.randint(-200,200))
dot.sety(random.randint(-200,200))
wall = turtle.Turtle()
wall.speed(0)
wall.penup()
wall.goto(x/2,y/2)
wall.pendown()
wall.seth(180)
wall.forward(400)
wall.seth(270)
wall.forward(400)
wall.seth(0)
wall.forward(400)
wall.seth(90)
wall.forward(400)
wall.seth(270)
wall.forward(400)
wall.seth(0)
wall.penup()
wall.forward(100)
char = turtle.Turtle()
x = 0
y = 0
# updates the position of the player turtle
while True:
screen.onkey(left,"a")
screen.onkey(right,"d")
char.hideturtle()
char.forward(speed)
char.speed(0)
turtle.listen(xdummy=None, ydummy=None)
print(char.pos())
print(posList[(len(posList)-1)])
# checks if current position is the same as any position it has ever been in !this is the bit that is having problems!
if checkBracktrack(char.pos(),posList):
speed = 0
break
# checks if it is close enough to a point marker to
if char.ycor() in range(dot.ycor()-10,dot.ycor()+10) and char.xcor() in range(dot.xcor()-10,dot.xcor()+10):
point()
# checks if in the box
if char.ycor() not in range(-200,200) or char.xcor() not in range(-200,200):
speed = 0
# adds current location to the list
posList.append(char.pos())
char.fd(speed)
print('you travelled',len(posList),'pixels')
print('collided with yourself')
print(char.pos())
print(posList)
name = input('quit')
screen.mainloop()
你设法解决我是有重大错误,但在你的代码中的碰撞检测似乎是在我的测试不可靠。感谢您一直以来的帮助 –