随机将图像放在pygame中

时间:2013-04-24 23:17:28

标签: python pygame

我正在制作一个非常基本的游戏来学习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位置

1 个答案:

答案 0 :(得分:4)

首先你应该改变你的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()