【问题标题】:error in a pygame codepygame 代码中的错误
【发布时间】:2011-02-08 13:54:48
【问题描述】:
# 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

我得到的错误是第 13 行文件race1.py 中的这个非ASCII 字符'\xc2',但没有声明编码;详情见http://www.python.org/peps/pep-0263.html

无法理解错误是什么以及如何摆脱它?

【问题讨论】:

    标签: python


    【解决方案1】:

    您在第 13 行有一个非 ASCII 字符。Python 不接受源文件中的 UTF-8,除非您在文件顶部添加特殊注释:

    # encoding: UTF-8
    

    【讨论】:

      【解决方案2】:

      正如 Greg 所说,您的代码中有一个非 ascii 字符 - 在第 13 行的 5 前面看起来像一个减号。它被称为“软连字符”。此字符出现在代码中的几个位置,而不是减号。删除这些字符并用减号替换。

      您上面的代码没有显示该字符。不知道为什么。当我将其复制并粘贴到文本编辑器中时,我可以看到该字符。

      如果您在代码顶部放置编码注释,例如:

      # -*- coding: utf-8 -*-
      

      您将收到带有“软连字符”的语法错误。所以你需要用减号替换它们。 (这样就不需要代码顶部的编码注释了。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-16
        • 2011-06-04
        相关资源
        最近更新 更多