python - 为什么蛇不向下移动(向下键盘)
问题描述
我正在用 python 编写一个蛇游戏,蛇能够向上、向左和向右移动,当我尝试向下移动它时(使用箭头)总是出现错误。我正在处理碰撞,因为蛇会与自身相撞(蛇头接触身体)屏幕将显示“游戏结束-你输了”。
Traceback (most recent call last): File "/Users/myname/Documents/SnakeGame.py", line 107, in <module> collision_y = playerRect.centrex AttributeError: 'pygame.Rect' object has no attribute 'centrex'
#timer for the game and frames per second
startTime = time.perf_counter()
FPS = 300
elapsedTime = 0
#creating numbers and text
GameOverFont = pygame.font.SysFont ('arial', 20)
GameOverMsg = GameOverFont.render("GAME OVER - YOU LOST", True, (RED))
screen.blit (GameOverMsg, [screenCentreX, screenCentreY])
collision_x = 0
collision_y = 0
collision_colour = None
clock = pygame.time.Clock()
speed = 3
screen.fill(WHITE)
#create a Rect to hold the player
# you need to give it the x,y, width, height parameters
playerRect = pygame.Rect(startX,startY,32,32)
# set main loop to True so it will run
main = True
# main loop
while main:
for event in pygame.event.get():
if event.type ==pygame.QUIT:
main = False
if event.type ==pygame.KEYDOWN:
if event.key == pygame.K_UP:
dx = 0
dy = -speed
elif event.key == pygame.K_DOWN:
dx = 0
dy = speed
elif event.key == pygame.K_LEFT: # note: this section of code
dx = -speed # doesn't have to change from
dy = 0 # code not using Rects
elif event.key == pygame.K_RIGHT:
dx = speed
dy = 0
elif event. key == pygame.K_q:
pygame.quit()
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
dx = 0
dy = 0
elif event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
dx = 0
dy = 0
#frames per second the program is running on
clock.tick(FPS)
if dx > 0:
collision_x = playerRect.right + 1
collision_y = playerRect.centery
collision_colour = screen.get_at((collision_x,collision_y))
elif dx < 0:
collision_x = playerRect.left - 1
collision_y = playerRect.centery
collision_colour = screen.get_at((collision_x,collision_y))
elif dy > 0:
collision_x = playerRect.bottom + 1
collision_y = playerRect.centrex
collision_colour = screen.get_at((collision_x,collision_y))
elif dy < 0:
collision_x = playerRect.top - 1
collision_y = playerRect.centerx
collision_colour = screen.get_at((collision_x,collision_y))
if collision_colour == BLUE:
screen.fill(BLACK)
startX = screenCentreX
startY = screenCentreY
dx = 0
dy = 0
main = False
gameover = True
elapsedTime = int(time.perf_counter() - startTime)
解决方案
You have a misspelled center on the line collision_y = playerRect.centrex
in the elif dy < 0:
推荐阅读
- regex - 使用正则表达式和 Notepad++ 将浮点秒转换为毫秒
- ios - 从 Tableview 中的 CollectionCell 执行 segue
- timer - ESP32 Arduino:BluetoothSerial.h 的 .println() 破坏了其他内核上的硬件定时器中断
- tensorflow - ImportError:python39.dll 的模块使用与此版本的 Python 冲突
- php - 如何在输入框中的 PHP 中添加空格?
- pdf - 如何引用预格式化 PDF (QDF) 中的文本内容?
- c# - 在 Android 和 iOS 上点击自定义按钮时实现“突出显示效果”而不是“涟漪效果”
- swift - 使用 void* 访问 MTLBuffer 内容
- javascript - 如何仅在按钮显示特定文本时才显示弹出窗口
- javascript - caches.delete 没有删除任何内容