0

我正在制作一个非常基本的游戏来学习 pygame 并且我正在尝试制作它,以便鸭子(玩家)必须躲避岩石但我不能让岩石随机放置然后滚动到一边

这是我当前的代码:

import pygame
import os
import random


img_path = os.path.join('C:\Python27', 'player.png')
img_path2 = os.path.join('C:\Python27', 'rock.png')


class Bird(object):  
    def __init__(self):

        self.image = pygame.image.load(img_path)
        self.x = 0
        self.y = 0


def handle_keys(self):
    """ Handles Keys """
    key = pygame.key.get_pressed()
    dist = 3 
    if key[pygame.K_DOWN]: 
        self.y += dist
    elif key[pygame.K_UP]: 
        self.y -= dist 
    if key[pygame.K_RIGHT]: 
        self.x += dist
    elif key[pygame.K_LEFT]: 
        self.x -= dist 




    def draw(self, surface):


        surface.blit(self.image, (self.x, self.y))

    def background(self, surface):
        bg = os.path.join('C:\Python27', 'bg.png')
        self.image2 = pygame.image.load(bg)
        surface.blit(self.image2, (0,0))

class Rock(object): 
    def __init__(self):
        self.image = pygame.image.load(img_path2)


        self.x = 640
        self.y = 0
    def rock(self):
        dist = 2
        if running == True:
            self.x -=dist


    def rock_draw(self, surface):
        surface.blit(self.image, (self.x, self.y))






pygame.init()
screen = pygame.display.set_mode((640, 400))

bird = Bird() # create an instance
rock = Rock()
clock = pygame.time.Clock()

running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit() 
            running = False

    bird.handle_keys() 
    rock.rock()

    screen.fill((255,255,255)) 
    bird.background(screen)
    bird.draw(screen)
    rock.rock_draw(screen)
    pygame.display.update() 

    clock.tick(40)

我希望岩石从屏幕右侧开始并滚动,然后一旦第一个消失或一半消失,在不同的 y 位置产生另一个

4

1 回答 1

4

首先,您应该更改 Rock 构造函数以允许位置参数,并稍微修复您的 rock 函数:

class Rock(object): 
   def __init__(self, x=640, y=0, dist=2):
       self.image = pygame.image.load(img_path2)
       self.x = x
       self.y = y
       self.dist = dist

   def rock(self):
       # you don't need to check if running is true here, you're doing that in your loop
       self.x -= dist

然后为岩石的 y 坐标找到一个随机 int 值,并在那里创建一个岩石:

import random

y = random.randint(0, 400)
rock = Rock(640, y)

在你的循环中:

if rock.x < 0:
    y = random.randint(0, 400)
    rock = Rock(640, y)

rock.rock()

这会检查石头是否击中了屏幕的左侧,如果有,它会创建一个新的石头。然后,无论哪种方式,它都会调用rock()那个 Rock 对象。

于 2013-04-25T05:26:17.893 回答