如何解决Pygame 块精灵未在屏幕上绘制
我对 python 和 pygame 非常陌生,我正在尝试制作一款自上而下的射击游戏。我设法让许多组件正常工作,但我无法让我射击的方块显示在我在游戏中创建的房间中。我将它的代码移到了游戏功能中,它显示在屏幕上,但是当你在房间之间移动时,它们保持不变,暂时我注释掉了那部分。我希望每个房间都有自己可以拍摄的积木,但是当我尝试将代码放入每个房间类时,它不会显示在屏幕上。我很确定没有什么是画在它上面的。我想知道为什么要绘制墙壁而不是块。任何帮助表示赞赏。
import pygame,sys,math,random
BLACK = (0,0)
WHITE = (255,255,255)
BLUE = (0,255)
GREEN = (0,0)
RED = (255,0)
PURPLE = (255,255)
click = False
# Call this function so the Pygame library can initialize itself
pygame.init()
# Create an 800x600 sized screen
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode([WIDTH,HEIGHT])
# Set the title of the window
pygame.display.set_caption('Maze Runner')
class Wall(pygame.sprite.Sprite):
def __init__(self,x,y,width,height,color):
# Call the parent's constructor
super().__init__()
# Make a BLUE wall,of the size specified in the parameters
self.image = pygame.Surface([width,height])
self.image.fill(color)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
class Block(pygame.sprite.Sprite):
def __init__(self,color):
# Call the parent class (Sprite) constructor
super().__init__()
self.image = pygame.Surface([20,20])
self.image.fill(color)
self.rect = self.image.get_rect()
class Player(pygame.sprite.Sprite):
# Set speed vector
change_x = 0
change_y = 0
def __init__(self,y):
# Call the parent's constructor
super().__init__()
# Set height,width
self.image = pygame.Surface([15,15])
self.image.fill(WHITE)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
def changespeed(self,y):
self.change_x += x
self.change_y += y
def move(self,walls):
# Move left/right
self.rect.x += self.change_x
# Did this update cause us to hit a wall?
block_hit_list = pygame.sprite.spritecollide(self,walls,False)
for block in block_hit_list:
# If we are moving right,set our right side to the left side of
# the item we hit
if self.change_x > 0:
self.rect.right = block.rect.left
else:
# Otherwise if we are moving left,do the opposite.
self.rect.left = block.rect.right
# Move up/down
self.rect.y += self.change_y
# Check and see if we hit anything
block_hit_list = pygame.sprite.spritecollide(self,False)
for block in block_hit_list:
# Reset our position based on the top/bottom of the object.
if self.change_y > 0:
self.rect.bottom = block.rect.top
else:
self.rect.top = block.rect.bottom
class Bullet(pygame.sprite.Sprite):
def __init__(self,start_x,start_y,dest_x,dest_y):
# Call the parent class (Sprite) constructor
super().__init__()
# Set up the image for the bullet
self.image = pygame.Surface([5,5])
self.image.fill(BLUE)
self.rect = self.image.get_rect()
# Move the bullet to our starting location
self.rect.x = start_x
self.rect.y = start_y
# Because rect.x and rect.y are automatically converted
# to integers,we need to create different variables that
# store the location as floating point numbers. Integers
# are not accurate enough for aiming.
self.floating_point_x = start_x
self.floating_point_y = start_y
# Calculation the angle in radians between the start points
# and end points. This is the angle the bullet will travel.
x_diff = dest_x - start_x
y_diff = dest_y - start_y
angle = math.atan2(y_diff,x_diff);
# Taking into account the angle,calculate our change_x
# and change_y. VeLocity is how fast the bullet travels.
veLocity = 5
self.change_x = math.cos(angle) * veLocity
self.change_y = math.sin(angle) * veLocity
def update(self):
""" Move the bullet. """
# The floating point x and y hold our more accurate location.
self.floating_point_y += self.change_y
self.floating_point_x += self.change_x
# The rect.x and rect.y are converted to integers.
self.rect.y = int(self.floating_point_y)
self.rect.x = int(self.floating_point_x)
# If the bullet flies of the screen,get rid of it.
if self.rect.x < 0 or self.rect.x > WIDTH or self.rect.y < 0 or self.rect.y > HEIGHT:
self.kill()
class Room(object):
# Each room has a list of walls,and of enemy sprites.
wall_list = None
enemy_sprites = None
block_list = None
def __init__(self):
""" Constructor,create our lists. """
self.wall_list = pygame.sprite.Group()
self.enemy_sprites = pygame.sprite.Group()
self.block_list = pygame.sprite.Group()
self.movingsprites = pygame.sprite.Group()
class Room1(Room):
def __init__(self):
super().__init__()
# Make the walls. (x_pos,y_pos,height)
# This is a list of walls. Each is in the form [x,height]
walls = [[0,20,250,WHITE],[0,350,[780,[20,760,580,[390,50,500,BLUE]
]
# Loop through the list. Create the wall,add it to the list
for item in walls:
wall = Wall(item[0],item[1],item[2],item[3],item[4])
self.wall_list.add(wall)
for i in range(10):
# This represents a block
block = Block(GREEN)
# Set a random location for the block
block.rect.x = random.randrange(WIDTH - 50)
block.rect.y = random.randrange(HEIGHT - 50)
# Add the block to the list of objects
self.block_list.add(block)
self.movingsprites.add(block)
class Room2(Room):
def __init__(self):
super().__init__()
walls = [[0,RED],[190,GREEN],[590,GREEN]
]
for item in walls:
wall = Wall(item[0],item[4])
self.wall_list.add(wall)
block = Block(RED)
block.rect.x = 200
block.rect.y = 200
self.block_list.add(block)
self.movingsprites.add(block)
class Room3(Room):
def __init__(self):
super().__init__()
walls = [[0,PURPLE],PURPLE]
]
for item in walls:
wall = Wall(item[0],item[4])
self.wall_list.add(wall)
for x in range(100,800,100):
for y in range(50,451,300):
wall = Wall(x,200,RED)
self.wall_list.add(wall)
for x in range(150,700,100):
wall = Wall(x,WHITE)
self.wall_list.add(wall)
def draw_text(text,font,color,surface,y):
textobj = font.render(text,1,color)
textrect = textobj.get_rect()
textrect.topleft = (x,y)
surface.blit(textobj,textrect)
def main_menu():
done = False
while not done:
font = pygame.font.SysFont('Calibri',True,False)
clock = pygame.time.Clock()
screen.fill(BLACK)
draw_text('main menu',WHITE,screen,20)
mx,my = pygame.mouse.get_pos()
button_1 = pygame.Rect(50,100,50)
if button_1.collidepoint((mx,my)):
if click:
game()
pygame.draw.rect(screen,RED,button_1)
draw_text('Play',60,110)
click = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.flip()
clock.tick(60)
pygame.quit()
def game():
# Create the player paddle object
player = Player(50,50)
movingsprites = pygame.sprite.Group()
movingsprites.add(player)
bullet_list = pygame.sprite.Group()
walls = pygame.sprite.Group()
wall_list = pygame.sprite.Group()
block_list = pygame.sprite.Group()
#for i in range(10):
## This represents a block
#block = Block(GREEN)
## Set a random location for the block
#block.rect.x = random.randrange(WIDTH - 50)
#block.rect.y = random.randrange(HEIGHT - 50)
## Add the block to the list of objects
#block_list.add(block)
#movingsprites.add(block)
rooms = []
room = Room1()
rooms.append(room)
room = Room2()
rooms.append(room)
room = Room3()
rooms.append(room)
current_room_no = 0
current_room = rooms[current_room_no]
clock = pygame.time.Clock()
done = False
while not done:
# --- Event Processing ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.changespeed(-5,0)
if event.key == pygame.K_RIGHT:
player.changespeed(5,0)
if event.key == pygame.K_UP:
player.changespeed(0,-5)
if event.key == pygame.K_DOWN:
player.changespeed(0,5)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
done = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player.changespeed(5,0)
if event.key == pygame.K_RIGHT:
player.changespeed(-5,5)
if event.key == pygame.K_DOWN:
player.changespeed(0,-5)
if event.type == pygame.MOUSEBUTTONDOWN:
# Fire a bullet if the user clicks the mouse button
# Get the mouse position
pos = pygame.mouse.get_pos()
mouse_x = pos[0]
mouse_y = pos[1]
# Create the bullet based on where we are,and where we want to go.
bullet = Bullet(player.rect.x,player.rect.y,mouse_x,mouse_y)
# Add the bullet to the lists
movingsprites.add(bullet)
bullet_list.add(bullet)
# --- Game Logic ---
player.move(current_room.wall_list)
movingsprites.update()
if player.rect.x < -15:
if current_room_no == 0:
current_room_no = 2
current_room = rooms[current_room_no]
player.rect.x = 790
elif current_room_no == 2:
current_room_no = 1
current_room = rooms[current_room_no]
player.rect.x = 790
else:
current_room_no = 0
current_room = rooms[current_room_no]
player.rect.x = 790
if player.rect.x > WIDTH + 1:
if current_room_no == 0:
current_room_no = 1
current_room = rooms[current_room_no]
player.rect.x = 0
elif current_room_no == 1:
current_room_no = 2
current_room = rooms[current_room_no]
player.rect.x = 0
else:
current_room_no = 0
current_room = rooms[current_room_no]
player.rect.x = 0
for bullet in bullet_list:
# See if it hit a block
block_hit_list = pygame.sprite.spritecollide(bullet,block_list,True)
# For each block hit,remove the bullet and add to the score
for block in block_hit_list:
bullet_list.remove(bullet)
movingsprites.remove(bullet)
# Remove the bullet if it flies up off the screen
if bullet.rect.y < -10:
bullet_list.remove(bullet)
movingsprites.remove(bullet)
# --- Drawing ---
screen.fill(BLACK)
block_list.draw(screen)
movingsprites.draw(screen)
current_room.wall_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
if __name__ == "__main__":
main_menu()
解决方法
您需要将块列表作为房间类的属性,然后在 draw 中绘制它们。注意如何在绘制中调用
current_room.block_list.draw(screen)
这就是你的意思:
import pygame,sys,math,random
BLACK = (0,0)
WHITE = (255,255,255)
BLUE = (0,255)
GREEN = (0,0)
RED = (255,0)
PURPLE = (255,255)
click = False
# Call this function so the Pygame library can initialize itself
pygame.init()
# Create an 800x600 sized screen
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode([WIDTH,HEIGHT])
# Set the title of the window
pygame.display.set_caption('Maze Runner')
class Wall(pygame.sprite.Sprite):
def __init__(self,x,y,width,height,color):
# Call the parent's constructor
super().__init__()
# Make a BLUE wall,of the size specified in the parameters
self.image = pygame.Surface([width,height])
self.image.fill(color)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
class Block(pygame.sprite.Sprite):
def __init__(self,color):
# Call the parent class (Sprite) constructor
super().__init__()
self.image = pygame.Surface([20,20])
self.image.fill(color)
self.rect = self.image.get_rect()
class Player(pygame.sprite.Sprite):
# Set speed vector
change_x = 0
change_y = 0
def __init__(self,y):
# Call the parent's constructor
super().__init__()
# Set height,width
self.image = pygame.Surface([15,15])
self.image.fill(WHITE)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
def changespeed(self,y):
self.change_x += x
self.change_y += y
def move(self,walls):
# Move left/right
self.rect.x += self.change_x
# Did this update cause us to hit a wall?
block_hit_list = pygame.sprite.spritecollide(self,walls,False)
for block in block_hit_list:
# If we are moving right,set our right side to the left side of
# the item we hit
if self.change_x > 0:
self.rect.right = block.rect.left
else:
# Otherwise if we are moving left,do the opposite.
self.rect.left = block.rect.right
# Move up/down
self.rect.y += self.change_y
# Check and see if we hit anything
block_hit_list = pygame.sprite.spritecollide(self,False)
for block in block_hit_list:
# Reset our position based on the top/bottom of the object.
if self.change_y > 0:
self.rect.bottom = block.rect.top
else:
self.rect.top = block.rect.bottom
class Bullet(pygame.sprite.Sprite):
def __init__(self,start_x,start_y,dest_x,dest_y):
# Call the parent class (Sprite) constructor
super().__init__()
# Set up the image for the bullet
self.image = pygame.Surface([5,5])
self.image.fill(BLUE)
self.rect = self.image.get_rect()
# Move the bullet to our starting location
self.rect.x = start_x
self.rect.y = start_y
# Because rect.x and rect.y are automatically converted
# to integers,we need to create different variables that
# store the location as floating point numbers. Integers
# are not accurate enough for aiming.
self.floating_point_x = start_x
self.floating_point_y = start_y
# Calculation the angle in radians between the start points
# and end points. This is the angle the bullet will travel.
x_diff = dest_x - start_x
y_diff = dest_y - start_y
angle = math.atan2(y_diff,x_diff);
# Taking into account the angle,calculate our change_x
# and change_y. Velocity is how fast the bullet travels.
velocity = 5
self.change_x = math.cos(angle) * velocity
self.change_y = math.sin(angle) * velocity
def update(self):
""" Move the bullet. """
# The floating point x and y hold our more accurate location.
self.floating_point_y += self.change_y
self.floating_point_x += self.change_x
# The rect.x and rect.y are converted to integers.
self.rect.y = int(self.floating_point_y)
self.rect.x = int(self.floating_point_x)
# If the bullet flies of the screen,get rid of it.
if self.rect.x < 0 or self.rect.x > WIDTH or self.rect.y < 0 or self.rect.y > HEIGHT:
self.kill()
class Room(object):
# Each room has a list of walls,and of enemy sprites.
wall_list = None
enemy_sprites = None
block_list = None
def __init__(self):
""" Constructor,create our lists. """
self.wall_list = pygame.sprite.Group()
self.enemy_sprites = pygame.sprite.Group()
self.block_list = pygame.sprite.Group()
self.movingsprites = pygame.sprite.Group()
for i in range(10):
# This represents a block
block = Block(GREEN)
# Set a random location for the block
block.rect.x = random.randrange(WIDTH - 50)
block.rect.y = random.randrange(HEIGHT - 50)
# Add the block to the list of objects
self.block_list.add(block)
self.movingsprites.add(block)
class Room1(Room):
def __init__(self):
super().__init__()
# Make the walls. (x_pos,y_pos,height)
# This is a list of walls. Each is in the form [x,height]
walls = [[0,20,250,WHITE],[0,350,[780,[20,760,580,[390,50,500,BLUE]
]
# Loop through the list. Create the wall,add it to the list
for item in walls:
wall = Wall(item[0],item[1],item[2],item[3],item[4])
self.wall_list.add(wall)
for i in range(10):
# This represents a block
block = Block(GREEN)
# Set a random location for the block
block.rect.x = random.randrange(WIDTH - 50)
block.rect.y = random.randrange(HEIGHT - 50)
# Add the block to the list of objects
self.block_list.add(block)
self.movingsprites.add(block)
class Room2(Room):
def __init__(self):
super().__init__()
walls = [[0,RED],[190,GREEN],[590,GREEN]
]
for item in walls:
wall = Wall(item[0],item[4])
self.wall_list.add(wall)
block = Block(RED)
block.rect.x = 200
block.rect.y = 200
self.block_list.add(block)
self.movingsprites.add(block)
class Room3(Room):
def __init__(self):
super().__init__()
walls = [[0,PURPLE],PURPLE]
]
for item in walls:
wall = Wall(item[0],item[4])
self.wall_list.add(wall)
for x in range(100,800,100):
for y in range(50,451,300):
wall = Wall(x,200,RED)
self.wall_list.add(wall)
for x in range(150,700,100):
wall = Wall(x,WHITE)
self.wall_list.add(wall)
def draw_text(text,font,color,surface,y):
textobj = font.render(text,1,color)
textrect = textobj.get_rect()
textrect.topleft = (x,y)
surface.blit(textobj,textrect)
def main_menu():
done = False
while not done:
font = pygame.font.SysFont('Calibri',True,False)
clock = pygame.time.Clock()
screen.fill(BLACK)
draw_text('main menu',WHITE,screen,20)
mx,my = pygame.mouse.get_pos()
button_1 = pygame.Rect(50,100,50)
if button_1.collidepoint((mx,my)):
if click:
game()
pygame.draw.rect(screen,RED,button_1)
draw_text('Play',60,110)
click = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.flip()
clock.tick(60)
pygame.quit()
def game():
# Create the player paddle object
player = Player(50,50)
movingsprites = pygame.sprite.Group()
movingsprites.add(player)
bullet_list = pygame.sprite.Group()
walls = pygame.sprite.Group()
wall_list = pygame.sprite.Group()
block_list = pygame.sprite.Group()
rooms = []
room = Room1()
rooms.append(room)
room = Room2()
rooms.append(room)
room = Room3()
rooms.append(room)
current_room_no = 0
current_room = rooms[current_room_no]
clock = pygame.time.Clock()
done = False
while not done:
# --- Event Processing ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.changespeed(-5,0)
if event.key == pygame.K_RIGHT:
player.changespeed(5,0)
if event.key == pygame.K_UP:
player.changespeed(0,-5)
if event.key == pygame.K_DOWN:
player.changespeed(0,5)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
done = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player.changespeed(5,0)
if event.key == pygame.K_RIGHT:
player.changespeed(-5,5)
if event.key == pygame.K_DOWN:
player.changespeed(0,-5)
if event.type == pygame.MOUSEBUTTONDOWN:
# Fire a bullet if the user clicks the mouse button
# Get the mouse position
pos = pygame.mouse.get_pos()
mouse_x = pos[0]
mouse_y = pos[1]
# Create the bullet based on where we are,and where we want to go.
bullet = Bullet(player.rect.x,player.rect.y,mouse_x,mouse_y)
# Add the bullet to the lists
movingsprites.add(bullet)
bullet_list.add(bullet)
# --- Game Logic ---
player.move(current_room.wall_list)
movingsprites.update()
if player.rect.x < -15:
if current_room_no == 0:
current_room_no = 2
current_room = rooms[current_room_no]
player.rect.x = 790
elif current_room_no == 2:
current_room_no = 1
current_room = rooms[current_room_no]
player.rect.x = 790
else:
current_room_no = 0
current_room = rooms[current_room_no]
player.rect.x = 790
if player.rect.x > WIDTH + 1:
if current_room_no == 0:
current_room_no = 1
current_room = rooms[current_room_no]
player.rect.x = 0
elif current_room_no == 1:
current_room_no = 2
current_room = rooms[current_room_no]
player.rect.x = 0
else:
current_room_no = 0
current_room = rooms[current_room_no]
player.rect.x = 0
for bullet in bullet_list:
# See if it hit a block
block_hit_list = pygame.sprite.spritecollide(bullet,block_list,True)
# For each block hit,remove the bullet and add to the score
for block in block_hit_list:
bullet_list.remove(bullet)
movingsprites.remove(bullet)
# Remove the bullet if it flies up off the screen
if bullet.rect.y < -10:
bullet_list.remove(bullet)
movingsprites.remove(bullet)
# --- Drawing ---
screen.fill(BLACK)
current_room.block_list.draw(screen)
movingsprites.draw(screen)
current_room.wall_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
if __name__ == "__main__":
main_menu()
此外,如果您将碰撞检测更改为:
for bullet in bullet_list:
# See if it hit a block
block_hit_list = pygame.sprite.spritecollide(bullet,current_room.block_list,True)
它将检测子弹击中房间块
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。