我目前正在学习Pygame游戏开发教程中的代码:
https://www.youtube.com/watch?v=fcryHcZE_sM
我已经将代码完全复制到Pycharm中,我相信它应该可以工作。
#Pygame Sprite Example
import pygame
import random
import os
WIDTH = 360
HEIGHT = 480
FPS = 30
#Colours
BLACK = (0, 0, 0)
WHITE= (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# set up assets folders
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "img")
class Player(pygame.sprite.Sprite):
# sprite for the player
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(os.path.join(img_folder, "p1_jump.png")).convert()
self.image.set_colourkey(BLACK)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
def update(self):
self.rect.x += 5
if self.rect.left > WIDTH:
self.rect.right = 0
#initialise pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
#Game Loop
running = True
while running:
#keep loop running at right speed
clock.tick(FPS)
#Process Input/Events
for event in pygame.event.get():
#check for closing window
if event.type == pygame.QUIT:
running = False
#Update
all_sprites.update()
#Draw/Render
screen.fill(BLUE)
all_sprites.draw(screen)
# *after drawing everything, flip the display*
pygame.display.flip()
pygame.quit()
当我运行它时,它给了我这个错误:
C:\Users\George\PycharmProjects\app\venv1\Scripts\python.exe "C:/Users/George/Documents/School/Year 12/IT/Coursework/SpriteExample.py"
Traceback (most recent call last):
File "C:/Users/George/Documents/School/Year 12/IT/Coursework/SpriteExample.py", line 46, in <module>
player = Player()
File "C:/Users/George/Documents/School/Year 12/IT/Coursework/SpriteExample.py", line 28, in __init__
self.image = pygame.image.load(os.path.join(img_folder, "p1_jump.png")).convert()
pygame.error: Couldn't open C:/Users/George/Documents/School/Year 12/IT/Coursework\img\p1_jump.png
Process finished with exit code 1
在教程视频中,这家伙正在使用Mac,而我正在使用Windows笔记本电脑(运行Windows 7)。
我试过在网站上进行研究,但是找不到任何具体的错误。我还尝试将类Player
的初始化中的代码更改为:
game_folder = os.path.dirname(os.path.abspath(__file__))
img_folder = os.path.join(game_folder, "img")
image1 = pygame.image.load(os.path.join(img_folder, "p1_jump.png" ))
class Player(pygame.sprite.Sprite):
# sprite for the player
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = image1.convert()
self.image.set_colourkey(BLACK)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
它仍然无效。
答案 0 :(得分:0)
如果您将其命名为my_path.py或类似名称,然后将其放置在documents文件夹中并运行它,则将其命名为my_path.py。 它将帮助您看到sprite2.py文件应该位于documents文件夹中,并且您需要在文档中有一个名为“ img”并包含“ png”文件的子文件夹。然后游戏应该运行正常。因此,game_folder实际上是“文档文件夹”,而img_folder是文档中的img。我希望可以更清楚一点,如果您在另一个文件夹中有游戏,则可以修改sprite2.py之上或之内的代码
game_folder = os.path.dirname(__file__)
print(game_folder)
img_folder = os.path.join(game_folder, "img")
print(img_folder)