python - 如何在这个 PyGame 代码中找到逻辑错误?
问题描述
这是我目前正在为一个项目开发的游戏的早期原型。但是,我似乎遇到了无法显示玩家角色的障碍,正如您在代码中看到的那样,我为玩家创建了一个类
import pygame
pygame.init()
win = pygame.display.set_mode((500,480))#initialises the game window
pygame.display.set_caption("Hello world")
bg = pygame.image.load('bg.jpg')
#player class
class player:
def __init__(self,x,y):
self.x = x
self.y = y
self.width = 64
self.height = 64
self.standing = True
self.left = False
self.right = True
self.vel = 5
self.jumping = False
self.jumpCount = 10
def move(self,x,y):
self.k = pygame.key.get_pressed()
if self.k[pygame.K_LEFT] and self.x > 0 + self.vel + self.width:
left = True
right = False
self.standing = False
self.x -= vel
elif self.k[pygame.K_RIGHT] and self.x < 500-self.vel-self.width:
self.right = True
self.left = False
self.standing = False
self.x += vel
else:
self.standing = True
if self.jumping:#checks if users jumping intiating jump
if self.k[pygame.K_SPACE]:
if self.jumpCount >= -10:
neg = 1
if self.JumpCount < 0:
neg = -1
self.y -= (jumpCount ** 2) * 0.5 * neg
self.jumpCount -= 1
else:
self.jumping = False
self.jumpCount = 10
def draw(self,win,move):
wLeft = pygame.image.load('runningleft.png')
wRight = pygame.image.load('running.png')
char = pygame.image.load('idleright.png')
if not(self.standing):
if self.left:
win.blit(wleft,(self.x,self.y))
elif self.right:
win.blit(wright,(self.x,self.y))
else:
win.blit(char,(self.x,self.y))
pygame.display.update()
pygame.display.update()
wizard = player(50,450)
run = True
while run:#main game loop
for event in pygame.event.get():#loops through a list of keyboard or mouse events
if event.type == pygame.QUIT:
run = False
wizard.move(wizard.x,wizard.y)
wizard.draw(win)
win.blit(bg,(0,0))
pygame.display.update()
pygame.quit()
背景显示在主游戏窗口中,而角色则不显示。如前所述,我试图将项目转换为 OOP,这是我的代码停止的地方。如何诊断代码中的问题?
解决方案
你的指令顺序是错误的。您需要wizard
在绘制背景之后和更新显示之前绘制播放器 ( ):
win.blit(bg,(0,0))
wizard.draw(win)
pygame.display.update()
wizard = player(50,450)
#main game loop
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
wizard.move(wizard.x,wizard.y)
win.blit(bg,(0,0))
wizard.draw(win)
pygame.display.update()
在循环结束时更新一次显示就足够了,所以pygame.display.update()
从player.draw
. 多次更新显示会导致闪烁。请参阅为什么 PyGame 动画闪烁
推荐阅读
- python - 如何为以下场景编写正则表达式?
- google-sheets - 如果记录不存在,Google 表格会将某些字段复制到新表格
- react-native - 使用 yarn 下载 expo 时出错 - yarn 或 expo 有问题吗?
- java - hibernate-5.4.0-upgrade-causes-ij000453-unable-to-get-managed-connection-for java:/xa-Datasource
- vue.js - 图像 URL 无法在 Vue 组件中解析
- excel - 一个 Do until 循环嵌套在一个 do while 循环中,该循环不能在 excel VBA 中编译
- string - 如何将字符串拆分为长度为 n 的子字符串?
- csv - 如何使用 cypher-shell neo4j 命令从终端运行密码脚本文件?
- javascript - 我可以使用 csv 文件作为我的网站使用哪些图像的参考吗?
- django - AttributeError 没有属性“对象”