用collison生成随机矩形

时间:2018-04-04 19:23:46

标签: python pygame

我正在制作一个游戏,其中屏幕最左侧有一把枪,它有一个固定的x坐标,y基于鼠标位置移动。一只鸟在屏幕的顶部,目标是没有物体击中鸟。

示例代码:

import pygame, sys, time, random
pygame.init()
pygame.font.init()
displaySurf = pygame.display.set_mode((460, 720))
obstacleChoice = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = 0 # (Hoping to use this to scroll the screeen (see line 24))
fps = pygame.time.Clock()
gun = pygame.image.load('gun.png')
bird = pygame.image.load('goose.png')
ammo = pygame.image.load('ammo.png')
sky = pygame.image.load('sky.png')
stone = pygame.image.load('stone.png')
lvlOne = pygame.image.load('lvlOne.png')
BLACK = (0,0,0)
grey = pygame.Color('grey')
x = 100 # bullets start
loop = False
font = pygame.font.SysFont('monaco', 24)
bullets = 12 # start with 12 bullets
score = 0 # score starts at 0

while True:

    y -= 1
    score += 0.06 # increase the score as time goes on
    mousePos = pygame.mouse.get_pos()
    mousePressed = pygame.mouse.get_pressed()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    if mousePressed[0] and bullets > 0: # if clicked, and player has bullets
        loop = True # allows for the bullet to fly across the screen when clicked, rather than only move while clicked
    if loop == True:
        if x < 460: # if the bullet hasn't left the screen
            x += 20 
    if x >= 460: # if the bullet has left the screen
        x = 100 # put the bullet back to the barrel of gun
        loop = False # stop movig the bullet
        bullets -= 1 # Take away a bullet 

    displaySurf.blit(sky, (0, y)) # sky
    displaySurf.blit(bird, (200, 10)) # Bird image
    pygame.Rect(x - 8, mousePos[1] + 5, 8, 4) # collison rect for bullet
    pygame.draw.rect(displaySurf, BLACK, (x - 8, mousePos[1] + 5, 8, 4)) # image rect for bullet
    displaySurf.blit(gun, (1, mousePos[1])) # gun image
    bulletSurface = font.render('bullets:{0}'.format(bullets), False, (0, 0, 0)) #bullet number
    displaySurf.blit(bulletSurface, (370, 0)) # bullets number display
    scoreSurface = font.render('score:{0}'.format(int(score)), False, (0, 0, 0)) # score 
    displaySurf.blit(scoreSurface, (370, 15)) # score display
    pygame.display.flip() # update
    fps.tick(60) # frames

我怎么能:

  1. 生成与子弹发生碰撞的随机矩形 被摧毁,如果与鸟相撞,游戏结束。

  2. 滚动屏幕,使物体飞向鸟类。

1 个答案:

答案 0 :(得分:2)

要制作随机矩形,只需使用python的随机模块即可。我也会为它添加一个课程。

import random

class Enemy:

    def __init__(self): 
        self.x = random.randint(0, 460)  #460 is the x resolution
        self.y = 720   I assume these rectangles start at the bottom of the screen.

    def move(self, speed):
        self.y += speed
        # Moves them up the screen, towards the bird.

    def draw(self, display):
        pygame.draw.rect(display, (0, 0, 0), (self.x, self.y, 20, 20)
    # Not sure what color, so I set it to black. Not sure what size, so I set it to 20

这只是一个基本的类,我相信你可能需要添加更多(比如使用敌人的Rect进行碰撞并添加碰撞方法),但请告诉我它是否有帮助。