开发者社区> 问答> 正文

初次尝试pygame,遇到了按键盘没响应的问题,求助?报错

跟着那个12岁的少年学pygame的时候,遇到点问题,原文地址:青少年如何使用Python开发游戏

http://www.oschina.net/translate/beginning-game-programming-for-teens-with-python?p=1#comments

做完第三步之后,怎么按键盘都反应,也没有报错,win32,pygame1.9.1,python2.7

#1 - Import library
import pygame
from pygame.locals import *

#2 - Initialize the game
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
keys = [False, False, False, False]
playerpos = [100, 100]

#3 - Load images
player = pygame.image.load('resources/images/dude.png')
grass = pygame.image.load('resources/images/grass.png')
castle = pygame.image.load('resources/images/castle.png')

#4 - keep looping through
while 1:
    #5 - clear the screen before drawing it again
    screen.fill(0)
    
    #6 - draw the screen elements
    for x in range(width/grass.get_width()+1):
        for y in range(height/grass.get_height()+1):
            screen.blit(grass,(x*100, y*100))
    screen.blit(player, playerpos)
    screen.blit(castle, (0,30))
    screen.blit(castle, (0,135))
    screen.blit(castle, (0,240))
    screen.blit(castle, (0,345))
    
    
    #7 - update the screen
    pygame.display.flip()
    
    #8 - loop through the events
    for event in pygame.event.get():
        #check if the event is the X button
        if event.type == pygame.QUIT:
            #if it is quit the game
            pygame.quit()
            exit(0)
        if event.type == pygame.KEYDOWN:
            if event.key == K_w:
                keys[0] == True
            elif event.key == K_a:
                keys[1] == True
            elif event.key == K_s:
                keys[2] == True
            elif event.key == K_d:
                keys[3] == True
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_w:
                keys[0] = False
            elif event.key == pygame.K_a:
                keys[1] = False
            elif event.key == pygame.K_s:
                keys[2] = False
            elif event.key == pygame.K_d:
                keys[3] = False
                
    #9 - Move player
    if keys[0]:
        playerpos[1] -= 5
    elif keys[2]:
        playerpos[1] += 5
    if keys[1]:
        playerpos[0] -= 5
    elif keys[3]:
        playerpos[0] += 5

 

展开
收起
爱吃鱼的程序员 2020-06-22 16:59:43 2019 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    问题已解决。。。原因是ifevent.type==pygame.KEYDOWN:代码块里的keys[n]==True改为keys[n]=True........低级错误,一开始检查了很多遍,怎么也看不出来,下午又仔细检查了一边才发现。。。。

    2020-06-22 17:00:02
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载