Python Pygame移动问题

Python Pygame移动问题,python,pygame,Python,Pygame,当我在PythonPyGame中使用移动代码时,它不会在我运行时加载代码 #right to repestic creatovrs import pygame, random, time, sys, pyscroll, pytmx from Bruh import * from pygame.locals import * from pytmx.util_pygame import load_pygame pygame.init() width, height = 800, 600 ba

当我在PythonPyGame中使用移动代码时,它不会在我运行时加载代码

#right to repestic creatovrs



import pygame, random, time, sys, pyscroll, pytmx
from Bruh import *
from pygame.locals import *
from pytmx.util_pygame import load_pygame

pygame.init()
width, height = 800, 600
backgroundColor = 255,  0,  0
screen = pygame.display.set_mode((width, height))

blue = (0, 0, 255)
darkblue = (20, 20, 70)
white = (255, 255, 255)
lightwhite = (170, 170, 170)
skin = (236, 188, 180)
floorcolor = (229,164,14)
sun = (250,255,63) 


#the four numbers go x axis, y axis, width, and then height
def drawLevel1(window):
  img = pygame.image.load("Overlay.png")
  window.blit(img, (0, 0))
def drawLevel2(window):
  img2 = pygame.image.load("Overlay2.png")
  window.blit(img, (0, 0))     

pygame.key.set_repeat(100,100)

Character = Bruh(35, 367)

Bruh.draw(Character, screen)

drawLevel1(screen)
'''
while True:
      for event in pygame.event.get():
          if event.type==QUIT or (event.type==KEYUP and event.key==K_ESCAPE):
            pygame.quit()
            sys.exit()
          elif event.type==KEYDOWN:

            if event.key==K_DOWN: 
                Character.moveUp()

            elif event.key==K_UP:
                Character.moveDown()

            elif event.key==K_LEFT:
                Character.moveLeft()

            elif event.key==K_RIGHT:
                Character.moveRight()

for event in pygame.event.get():
  if event.type==QUIT or (event.type==KEYUP and event.key==K_ESCAPE):
    pygame.quit()
    sys.exit()
  if event.key==K_DOWN:
    Character.moveUp()
  if event.key==K_UP:
    Character.moveDown()
  if event.key==K_LEFT:
    Character.moveLeft()
  if event.key==K_RIGHT:
    Character.moveRight
either of these won't work for some reason. it just wont load the game once these are placed in the code
'''
pygame.display.update()

while (True):
    for event in pygame.event.get() :
         if ( event.type == pygame.QUIT or (event.type==pygame.KEYDOWN and event.key==pygame.K_ESCAPE)):
              pygame.quit(); 
              sys.exit();
以及bruh.py中的代码:

import pygame
from pygame.locals import *

class Bruh:
    def __init__(self, newX, newY):
        self.x = newX
        self.y = newY
        self.img = pygame.image.load("Bruh.png")
    def draw(self, window):
        window.blit(self.img, (self.x,self.y))
    def moveLeft(self):
        self.x = self.x - 5
    def moveRight(self):
      self.x = self.x + 5
    def moveUp(self):
        self.y = self.y + 5
    def moveDown(self):
        self.y = self.y - 5
    def getRec(self):
        myRec = self.img.get_rect()
        return (self.x, self.y, myRec[2], myRec[3])      

这些都是.py文件,它们一定引起了一些问题。我没有收到任何错误消息,只是当我按run时它不会加载。我不明白为什么。如果有人能提供一些帮助,那就太好了

我认为pygame没有你想象的那么聪明。在
while
循环中,您正在移动角色,但在“移动”角色时所做的一切都是更新该对象上的数字。您没有告诉pygame任何事情都已更改,也没有重新绘制屏幕。光靠自己的力量是不够聪明的。有一些框架会跟踪您的价值观,并尝试更新显示以与它们保持同步(主要用于web开发),但pygame不是这样工作的

相反,实时视频游戏通常遵循以下模式:

while running:
    handle_events()  # check which keys have been pressed
    loop()           # handle, physics, AI, logic, etc
    render()         # re-draw a new version of the screen based on the new state of the world

更多信息,请参阅

在您的情况下,这可能看起来像:

pygame.key.set_repeat(100, 100)
character = Bruh(35, 367)

while True:
    for event in pygame.event.get():
        if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if event.key == K_DOWN:
                character.moveUp()
            elif event.key == K_UP:
                character.moveDown()
            elif event.key == K_LEFT:
                character.moveLeft()
            elif event.key == K_RIGHT:
                character.moveRight()

    screen.fill((0, 0, 0))
    drawLevel1(screen)
    character.draw(screen)

    pygame.display.update()

事实上,这不是一个很好的做事方式。行
pygame.key.set\u repeat(100100)
意味着每100ms(10次/秒)只能获得
KEYDOWN
事件。但是,
while
循环的运行次数要比这多得多。这意味着你的角色移动速度只能达到10FPS,但是你会消耗资源来更快地运行游戏

相反,我会这样做:

# make a clock to help us run at a consistent framerate
clock = pygame.time.Clock()

# a dictionary to help us keep track of which keys are currently held down
keys_down = {
    K_DOWN: False,
    K_UP: False,
    K_LEFT: False,
    K_RIGHT: False,
}

while True:
    for event in pygame.event.get():
        if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            # when the user presses a key, we keep track of the fact
            # that that key is down until they release it
            if event.key in keys_down:
                keys_down[event.key] = True
        elif event.type == KEYUP:
            # when the user releases a key, it's not down anymore
            if event.key in keys_down:
                keys_down[event.key] = False

    # This code will run *every loop*, regardless of
    # whether the user has pressed or released a key recently
    if keys_down[K_DOWN]:
        character.moveDown()
    if keys_down[K_UP]:
        character.moveUp()
    if keys_down[K_LEFT]:
        character.moveLeft()
    if keys_down[K_RIGHT]:
        character.moveRight()

    # Then, clear the screen and re-draw everything in the scene
    screen.fill((0, 0, 0))
    # drawLevel1(screen)
    character.draw(screen)
    pygame.display.update()

    # clock.tick gets the number of `ticks` (milliseconds) since the
    # last time it was called. If you specify a number like tick(30),
    # then it will also wait an amount of time equal to 30 minus that
    # number. Effectively it will limit you to 30fps.
    clock.tick(30)

事实上,即使这样也不理想。实际上,你应该尽可能快地跑,并更新游戏逻辑以考虑帧速率(即,如果你获得的帧速率较少,则每帧移动得更远),这样即使你获得的帧速率有所下降,你的角色也会始终以一致的速度移动。更好的是,让逻辑和渲染异步运行。不过,这正进入一些高级领域


编辑: 正如@Kingsley所指出的,pygame内置了这种功能。上述示例可以简化为:

# make a clock to help us run at a consistent framerate
clock = pygame.time.Clock()

# a dictionary to help us keep track of which keys are currently held down
keys_down = {
    K_DOWN: False,
    K_UP: False,
    K_LEFT: False,
    K_RIGHT: False,
}

while True:
    for event in pygame.event.get():
        if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            # when the user presses a key, we keep track of the fact
            # that that key is down until they release it
            if event.key in keys_down:
                keys_down[event.key] = True
        elif event.type == KEYUP:
            # when the user releases a key, it's not down anymore
            if event.key in keys_down:
                keys_down[event.key] = False

    # This code will run *every loop*, regardless of
    # whether the user has pressed or released a key recently
    if keys_down[K_DOWN]:
        character.moveDown()
    if keys_down[K_UP]:
        character.moveUp()
    if keys_down[K_LEFT]:
        character.moveLeft()
    if keys_down[K_RIGHT]:
        character.moveRight()

    # Then, clear the screen and re-draw everything in the scene
    screen.fill((0, 0, 0))
    # drawLevel1(screen)
    character.draw(screen)
    pygame.display.update()

    # clock.tick gets the number of `ticks` (milliseconds) since the
    # last time it was called. If you specify a number like tick(30),
    # then it will also wait an amount of time equal to 30 minus that
    # number. Effectively it will limit you to 30fps.
    clock.tick(30)

导入pygame
从pygame.locals导入*
clock=pygame.time.clock()
尽管如此:
对于pygame.event.get()中的事件:
如果event.type==QUIT或(event.type==KEYUP和event.key==K_ESCAPE):
pygame.quit()
sys.exit()
#这一行处理所有的KEYUP和KEYDOWN事件
#而不是手动操作
keys\u down=pygame.key.get\u pressed()
如果按键向下[K向下]:
character.moveDown()
如果按键向下[K向上]:
character.moveUp()
如果按下[左]键:
character.moveLeft()
如果按下[右]键:
character.moveRight()
屏幕填充((0,0,0))
drawLevel1(屏幕)
字符绘制(屏幕)
pygame.display.update()
时钟滴答(30)

当你说“它不会加载”时,你的意思是它不会打开窗口吗?或者不会在窗口中显示任何内容?首先,我会尝试执行绝对最小值——只需打开一个窗口并设置一个背景色——然后一次添加一个代码,直到出现故障。因此,我注意到,在主文件中,您有来自Bruh import*的
,但另一个文件名为
Bruh.py
(小写)
Bruh
类是大写的,但是当您导入时,您是从文件导入的,而不是从类导入的,因此如果我不够具体,它应该是小写的。当我添加代码的while true部分时,它只是在窗口上显示一个黑屏。但当我删除while true部分时,它将重新显示它之后的所有内容,如覆盖和角色。这是一个很好的答案,但是所展示的
keys\u down
的实现与
pygame.key.get\u pressed()
?@Kingsley不,看起来基本上是一样的。我不知道这个函数存在——使用它可能更好()。