尝试使用pygame制作我的第一个python游戏。看来我让角色移动的方式可以防止游戏结束后循环播放。我真的是python和编程的新手,没有其他线程帮助我。
试图修改碰撞的结果,但只会产生更多的错误。这是错误消息:
if pressed[pygame.K_s] and y+51 < display_height: y += 15
UnboundLocalError: local variable 'pressed' referenced before assignment
import pygame
import random
import time
import os
os.chdir('/Users/william_rosa/desktop/school/python')
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
cwd = os.getcwd()
print(cwd)
gamedisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('MonkeyJump')
clock = pygame.time.Clock()
monkeyimg = pygame.image.load('still_monkey2.png')
background = pygame.image.load('jungle2.png')
missileimg = pygame.image.load('missile.png')
def missile(mx,my):
gamedisplay.blit(missileimg,(mx,my))
def monkey(x,y):
gamedisplay.blit(monkeyimg,(x,y))
def text_objects(text, font, color):
textsurface = font.render(text, True, red)
return textsurface, textsurface.get_rect()
def message_display(text):
largetext = pygame.font.Font('freesansbold.ttf',75)
textsurf, textrect = text_objects(text, largetext, red)
textrect.center = ((display_width/2),(display_height/2))
gamedisplay.blit(textsurf, textrect)
pygame.display.update()
time.sleep(5)
def dead():
message_display('The Monkey Is Dead')
def game_loop():
x = (display_width * 0.1)
y = (display_height * 0.45)
mx_start = display_width+200
my_start = random.randrange(0,display_height)
m_speed = -20
rect_monkey = monkeyimg.get_rect()
rect_missile = missileimg.get_rect()
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
pressed = pygame.key.get_pressed()
if pressed[pygame.K_s] and y+51<display_height: y += 15
if pressed[pygame.K_z] and y>9: y += -15
gamedisplay.blit(background,(0,0))
missile(mx_start,my_start)
mx_start += m_speed
monkey(x,y)
if mx_start+135 < 0:
mx_start = display_width
my_start = random.randrange(0,display_height)
if y in range(my_start-50,my_start+10):
if x in range(mx_start-40,mx_start+120):
dead()
game_loop()
pygame.init()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
答案 0 :(得分:1)
如果for
循环从不执行,则您永远不会设置pressed
。我认为这些if
语句必须位于循环内部。
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
pressed = pygame.key.get_pressed()
if pressed[pygame.K_s] and y+51<display_height: y += 15
if pressed[pygame.K_z] and y>9: y += -15
答案 1 :(得分:0)
正如巴尔玛所说,pressed = pygame.key.get_pressed()
行必须缩进。