pygame代码中的错误
# INTIALISATION
import pygame, math, sys
from pygame.locals import *
screen = pygame.display.set_mode((1024, 768))
car = pygame.image.load('car.png')
clock = pygame.time.Clock()
k_up = k_down = k_left = k_right = 0
speed = direction = 0
position = (100, 100)
TURN_SPEED = 5
ACCELERATION = 2
MAX_FORWARD_SPEED = 10
MAX_REVERSE_SPEED = 5
BLACK = (0,0,0)
while 1:
# USER INPUT
clock.tick(30)
for event in pygame.event.get():
if not hasattr(event, 'key'): continue
down = event.type == KEYDOWN # key down or up?
if event.key == K_RIGHT: k_right = down * 5
elif event.key == K_LEFT: k_left = down * 5
elif event.key == K_UP: k_up = down * 2
elif event.key == K_DOWN: k_down = down * 2
elif event.key == K_ESCAPE: sys.exit(0) # quit the game
screen.fill(BLACK)
# SIMULATION
# .. new speed and direction based on acceleration and turn
speed += (k_up + k_down)
if speed > MAX_FORWARD_SPEED: speed = MAX_FORWARD_SPEED
if speed < MAX_REVERSE_SPEED: speed = MAX_REVERSE_SPEED
direction += (k_right + k_left)
# .. new position based on current position, speed and direction
x, y = position
rad = direction * math.pi / 180
x += speed*math.sin(rad)
y += speed*math.cos(rad)
position = (x, y)
# RENDERING
# .. rotate the car image for direction
rotated = pygame.transform.rotate(car, direction)
# .. position the car on screen
rect = rotated.get_rect()
rect.center = position
# .. render the car to screen
screen.blit(rotated, rect)
pygame.display.flip()
enter code here
我遇到的错误是:在文件 race1.py 的第13行有一个非ASCII字符 '\xc2',但没有声明编码;详细信息请查看 http://www.python.org/peps/pep-0263.html
我不太明白这个错误是什么,以及该怎么解决它?
2 个回答
4
在第13行,你有一个非ASCII字符。Python不接受源文件中的UTF-8编码,除非你在文件的开头加上一条特别的注释:
# encoding: UTF-8
2
正如Greg所说,你的代码里有一个非ASCII字符——在第13行的5
前面看起来像一个减号的符号。这个符号叫做“软连字符”。在你的代码中,有几个地方用这个符号代替了减号。你需要把这些符号删掉,换成真正的减号。
你上面的代码没有显示出这个字符。我也不知道为什么。当我把它复制粘贴到文本编辑器里时,我能看到这个字符。
如果你在代码的顶部加一个编码注释,比如:
# -*- coding: utf-8 -*-
那么你会因为这个“软连字符”而出现语法错误。所以你需要把它们全部替换成减号。(这样你就不需要在代码顶部加编码注释了。)