代码在使用turtle模块的Python中不起作用

时间:2018-03-06 21:56:59

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

我正在用py龟在python中创建一个游戏并遇到错误。游戏的目标是移动坦克并射击敌方坦克。我还没完呢。我添加了一个白色边框,但是当我尝试对坦克进行编程以使其无法超出边界时,它不起作用。这是我的代码:

#Import modules
import turtle
import time
import random

#Create screen
map = turtle.Screen()
map.bgcolor("limegreen")

#Create player tank
tank = turtle.Turtle()
tank.shape("triangle")
tank.color("blue")
tank.speed(0)
tank.penup()
tank.setposition(0, 0)
tank.setheading(90)

#Create border
borderPen = turtle.Turtle()
borderPen.speed(0)
borderPen.hideturtle()
borderPen.penup()
borderPen.setposition(-300, -300)
borderPen.color("white")
borderPen.pendown()

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


#Define update coords function
global playerX
global playerY
global playerHeading
global tankSpeed
tankSpeed = 5

def update_coords():
  playerX = tank.xcor()
  playerY = tank.ycor()
  playerHeading = tank.heading()

#Define player movement functions
def move_forward():
  tank.fd(5)
  update_coords();
  if playerX > 300 or playerX == 300:
    tank.setx(playerX - 5)
    update_coords();
  elif playerX < -300 or playerX == -300:
    tank.setx(playerX + 5)
    update_coords();
  elif playerY > 300 or playerY == 300:
    tank.sety(playerY - 5)
    update_coords();
  elif playerY < -300 or playerY == -300:
    tank.sety(playerY + 5)
    update_coords();

def turn_left():
  tank.lt(10)

def turn_right():
  tank.rt(10)
#Allow player movement
map.listen()
map.onkey(move_forward, "Up")
map.onkey(turn_left, "Left")
map.onkey(turn_right, "Right")

#Create bullet
bullet = turtle.Turtle()
bullet.penup()
bullet.speed(0)
bullet.color("black")
bullet.hideturtle()

如果您知道代码无效的原因,请回复。谢谢!

1 个答案:

答案 0 :(得分:0)

初始化变量sed: -e expression #1, char 1: unknown command: `'' 2018/03/07 11:48:01 exit status 1 playerX时,您没有指定它们是全局变量,因此该函数正在尝试设置不存在的局部变量的值。

要在playerY功能添加update_coords

的开头修复此问题

这告诉计算机global playerX, playerYplayerX是您之前创建的全局变量。

新功能如下:

playerY