如何让精灵随机生成?



我是pygame的新手,所以我需要一些帮助来解决一些问题。我正在做一个贪吃蛇游戏,但有敌人和"迷宫"。

我认为,我最大的问题是,如果你运行我的代码,会相当明显。我已经将"食物"编码为随机出现,但它不是随机出现在 1 个随机位置,而是在屏幕上移动。[已解决]

我的第二个问题是我想在随机位置生成几个敌人(大约 5 个),而不仅仅是一个敌人,但我不知道该怎么做。

我的第三个问题是子弹到墙壁的碰撞检测。如果我一次发射一颗子弹,它就会起作用,但如果我一次发射多颗子弹,除了最后一颗会击中墙壁的子弹外,所有子弹都会穿过墙壁。

这些是敌人的代码:

Code is removed for now. Will re-upload in 1 to 2 months.
enemy = Enemy(500, 500, 1, wall_list)
all_sprite_list.add(enemy)

这些是项目符号的代码:

Code is removed for now. Will re-upload in 1 to 2 months.
Code is removed for now. Will re-upload in 1 to 2 months.

如果有帮助,这就是我的全部代码:

Code is removed for now. Will re-upload in 1 to 2 months.

我很感激我能得到的任何帮助,即使它与我上面提出的问题无关。非常感谢您的帮助!

您可以将一个实例添加到 Enemy 类并生成它以添加另一个敌人,只需给它一些不同的坐标,然后是第一个。

enemy = Enemy(500, 500, 1, wall_list)
enemy2 = Enemy(400,400,1, wall_list)
all_sprite_list.add(enemy)
all_sprite_list.add(enemy2)

对于食物,id像以前一样添加另一个类。

class Food(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([10,10])
self.image.fill(green)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(20,780)
self.rect.y = random.randrange(20,780)

删除以下行:

pygame.draw.rect(win,green,[randfoodx,randfoody,10,10])

在生成敌人和玩家精灵的同一位置添加以下内容:

food = Food()
all_sprite_list.add(food)

对于您提到的项目符号问题,请更改以下行:

if pygame.sprite.spritecollideany(bullet, wall_list):

到:

if pygame.sprite.spritecollideany(self, wall_list):

这很重要,因为当您生成新项目符号时,项目符号变量名称将被覆盖。

一起:

#Import
import pygame
import math
import time
import random
from pygame.locals import *
#Initialize
pygame.init()
pygame.mixer.init()
clock=pygame.time.Clock()
win = pygame.display.set_mode((800,800))
pygame.display.set_caption("Essential Python CA1")
#Define
black = (0, 0, 0)
white = (255, 250, 250)
green = (0, 255, 0)
red = (255, 0, 0)
blue = (70,130,180)
font = pygame.font.Font(None, 60)
display_instructions = True
instruction_page = 1
#Bullet
class Bullet(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([5, 5])
self.image.fill(green)
self.rect = self.image.get_rect()
def update(self):
self.rect.move_ip(self.vec.x, self.vec.y)
if pygame.sprite.spritecollideany(self, wall_list):
self.kill()

#Enemy
class Enemy(pygame.sprite.Sprite):
def __init__(self, x, y, speed, walls):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([20, 20])
self.image.fill(red)
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
self.speed = speed # speed of the enemy
self.walls = walls # walls for the collision test
def move(self, player):
dx, dy = player.rect.x - self.rect.x, player.rect.y - self.rect.y
dist = math.hypot(dx, dy)
dx, dy = dx / dist, dy / dist
Enemy.move_x = dx * self.speed
Enemy.move_y = dy * self.speed
def update(self):
self.rect.x += round(self.move_x)
block_collide = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_collide:
if self.move_x > 0:
self.rect.right = block.rect.left
else:
self.rect.left = block.rect.right
self.rect.y += round(self.move_y)
block_collide = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_collide:
if self.move_y > 0:
self.rect.bottom = block.rect.top
else:
self.rect.top = block.rect.bottom

#Player
class Player(pygame.sprite.Sprite):
move_x = 0
move_y = 0
walls = None
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([20, 20])
self.image.fill(white)
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
def move(self, x, y):
self.move_x += x
self.move_y += y
def update(self):
self.rect.x += self.move_x
block_collide = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_collide:
if self.move_x > 0:
self.rect.right = block.rect.left
else:
self.rect.left = block.rect.right
self.rect.y += self.move_y
block_collide = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_collide:
if self.move_y > 0:
self.rect.bottom = block.rect.top
else:
self.rect.top = block.rect.bottom
#Maze
class Wall(pygame.sprite.Sprite):
def __init__(self, x, y, width, height):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(blue)
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
class Food(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.width = 10
self.height = 10
self.image = pygame.Surface([10,10])
self.image.fill(green)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(20,780)
self.rect.y = random.randrange(20,780)

all_sprite_list = pygame.sprite.Group()
wall_list = pygame.sprite.Group()
walls = ((0, 0, 10, 800),
(40, 40, 10, 75),
(50, 40, 190, 10),
(790, 10, 10, 800),
(10, 0, 800, 10),
(10, 790, 800, 10),
(50, 750, 170, 10),
(40, 145, 10, 615),
(80, 710, 310, 10),
(250, 750, 110, 10),
(390, 680, 10, 80),
(400, 750, 200, 10),
(430, 710, 10, 50),
(470, 710, 200, 10),
(630, 750, 130, 10),
(750, 40, 10, 720),
(550, 40, 210, 10),
(270, 40, 250, 10),
(410, 80, 310, 10),
(410, 120, 310, 10),
(80, 80, 300, 10),
(370, 40, 10, 90),
(130, 120, 240, 10),
(300, 160, 450, 10),
(50, 160, 220, 10),
(700, 710, 50, 10),
(80, 670, 670, 10),
(80, 160, 10, 510),
(80, 200, 100, 10),
(210, 200, 120, 10),
(270, 200, 10, 90),
(120, 240, 150, 10),
(80, 280, 250, 10),
(360, 200, 100, 10),
(310, 240, 150, 10),
(460, 160, 10, 130),
(360, 280, 100, 10))
for wall_coords in walls:
wall = Wall(*wall_coords)
wall_list.add(wall)
all_sprite_list.add(wall)
player = Player(10, 10)
player.walls = wall_list
enemy = Enemy(500, 500, 1, wall_list)
enemy2 = Enemy(400,400,1, wall_list)
all_sprite_list.add(enemy)
all_sprite_list.add(enemy2)
food = Food()
all_sprite_list.add(food)
all_sprite_list.add(player)
#Start screen Loop
done = False
while not done and display_instructions:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = False
if event.type == pygame.MOUSEBUTTONDOWN:
instruction_page += 1
if instruction_page == 2:
display_instructions = False
# Set the screen background
win.fill(black)
if instruction_page == 1:
text = font.render("Instructions:", True, white)
win.blit(text, [10, 20])
text = font.render("Use WASD, or the Arrow Keys to move", True, white)
win.blit(text, [10, 100])
text = font.render("Left click to shoot", True, white)
win.blit(text, [10, 150])
text = font.render("Can you beat your highscore?", True, red)
win.blit(text, [100, 370])
text = font.render("Click to start", True, white)
win.blit(text, [270, 600])
clock.tick(60)
pygame.display.flip()
# Programme loop
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT: 
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.move(-2, 0)
elif event.key == pygame.K_RIGHT or event.key == ord('d'):
player.move(2, 0)
elif event.key == pygame.K_UP or event.key == ord('w'):
player.move(0, -2)
elif event.key == pygame.K_DOWN or event.key == ord('s'):
player.move(0, 2)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.move(2, 0)
elif event.key == pygame.K_RIGHT or event.key == ord('d'):
player.move(-2, 0)
elif event.key == pygame.K_UP or event.key == ord('w'):
player.move(0, 2)
elif event.key == pygame.K_DOWN or event.key == ord('s'):
player.move(0, -2)
elif event.type == pygame.MOUSEBUTTONDOWN:
aim_pos = event.pos
player_position = player.rect.center
bullet_vec = pygame.math.Vector2(aim_pos[0] - player_position[0], aim_pos[1] - player_position[1]).normalize() * 10
bullet = Bullet()
bullet.rect.center = player.rect.center
bullet.vec = bullet_vec
all_sprite_list.add(bullet)
enemy.move(player)
all_sprite_list.update()
win.fill(black)

all_sprite_list.draw(win)
# pygame.draw.rect(win,green,[randfoodx,randfoody,10,10])
pygame.display.flip()
clock.tick(100)
pygame.quit()

对于食物问题,如果地图上没有食物,您只需要它才能生成一块食物。或者如果少于 x。因此,设置一个 numberOfFood 变量,而不是while run:你可以输入while numberOfFood < 2:

最新更新