Главная » 2015 » Май » 3 » урок3 примеры конструкторов
00:43
урок3 примеры конструкторов

УРОК 3

Примеры конструкторов для различных игр видеоурок 3

 

Летающие обьекты уничтожаемые при соприкосновении с главным обьектом.

#!/usr/bin/env python
# -*- coding: utf-8 -*-import pygame

# Прямоугольники гравити уничтожаются и появляются

import pygame
import random
import math
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
RED = ( 255, 0, 0)
class Block(pygame.sprite.Sprite):

    def __init__(self, color, width, height):

        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
# The "center" the sprite will orbit
        self.center_x = 0
        self.center_y = 0
# Current angle in radians
        self.angle = 0
# How far away from the center to orbit, in pixels
        self.radius = 0
# How fast to orbit, in radians per frame
        self.speed = 0.05
    def update(self):

# Calculate a new x, y
        self.rect.x = self.radius * math.sin(self.angle) + self.center_x
        self.rect.y = self.radius * math.cos(self.angle) + self.center_y
# Increase the angle in prep for the next round.
        self.angle += self.speed
class Player(pygame.sprite.Sprite):

    def __init__(self, color, width, height):

        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
    def update(self):

        pos = pygame.mouse.get_pos()
        self.rect.x = pos[0]
        self.rect.y = pos[1]
# Initialize Pygame
pygame.init()
# Set the height and width of the screen
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 400
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# This is a list of 'sprites.' Each block in the program is
# added to this list. The list is managed by a class called 'Group.'
block_list = pygame.sprite.Group()
# This is a list of every sprite. All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()
for i in range(10):
# This represents a block
    block = Block(BLACK, 20, 15)
# Set a random center location for the block to orbit
    block.center_x = random.randrange(SCREEN_WIDTH)
    block.center_y = random.randrange(SCREEN_HEIGHT)
# Random radius from 10 to 200
    block.radius = random.randrange(10, 200)
# Random start angle from 0 to 2pi
    block.angle = random.random() * 2 * math.pi
# rdians per frame
    block.speed = 0.008
# Add the block to the list of objects
    block_list.add(block)
    all_sprites_list.add(block)
# Create a RED player block
player = Player(RED, 20, 15)
all_sprites_list.add(player)
#Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
score = 0
# -------- Main Program Loop -----------
while not done:
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done = True # Flag that we are done so we exit this loop
    all_sprites_list.update()
# Clear the screen
    screen.fill(WHITE)
# See if the player block has collided with anything.
    blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)
# Check the list of collisions.
    for block in blocks_hit_list:
        score += 1

# Draw all the spites
    all_sprites_list.draw(screen)
# Go ahead and update the screen with what we've drawn.
    pygame.display.flip()
# Limit to 60 frames per second
    clock.tick(60)
pygame.quit()

 

 

Обьекты собираемые в структуру главным обьектом.

#!/usr/bin/env python
# -*- coding: utf-8 -*-import pygame

# МЫШКОЙ СОБИРАЕМ И ПЕРЕМЕЩАЕМ ПО КЛИКУ


import pygame
import random
 
# Define some colors
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
RED   = (255,   0,   0)
 
         
class Block(pygame.sprite.Sprite):
    
 
    def __init__(self, color, width, height):
       
 
        # Call the parent class (Sprite) constructor
        pygame.sprite.Sprite.__init__(self)
 
        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
 
       # Достать прямоугольный объект, обладающий размерами изображения
# изображение.
# Обновить позицию этого объекта, задав значения
# прямоугольника rect.х и rect.по Y
        self.rect = self.image.get_rect()
 
class Player(Block):# блок-игрок присваиваем координаты мышки
    
     
    # пустой список
    carry_block_list = []
     
     
    def update(self):
       
         
        # Получить текущее положение мыши. Это возвращает позицию
        # в виде списка двух чисел.
        pos = pygame.mouse.get_pos()
      
       # Теперь посмотрим, как позиции мышки отличается от текущей позиции игрока
       # Как далеко мы двигаться
        diff_x = self.rect.x - pos[0]
        diff_y = self.rect.y - pos[1]
         
        
        
# Цикл по каждому блоку, которые мы ведем и отрегулировать
# это сумма, которую мы переехали
        for block in self.carry_block_list:
            block.rect.x -= diff_x
            block.rect.y -= diff_y
             
        # Теперь  игрок имеет координаты мышки
        self.rect.x = pos[0]
        self.rect.y = pos[1]        
 
# Initialize Pygame
pygame.init()
 
# Set the height and width of the screen -размер поля
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])
 
# инициализируем список блоков
# added to this list. The list is managed by a class called 'Group.'
block_list = pygame.sprite.Group()
 
# инициализируем список всех блоков
# All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()
 
for i in range(50):
    # This represents a block -создаём черные блоки
    block = Block(BLACK, 20, 15)
 
    # задаем случайные координаты в размерах поля
    block.rect.x = random.randrange(screen_width)
    block.rect.y = random.randrange(screen_height)
 
    # добавляем блок в списки-блоков и общий
    block_list.add(block)
    all_sprites_list.add(block)
 
# создаем красный блок игрока как экземпляр класса Player
player = Player(RED, 20, 15)
all_sprites_list.add(player)
 
# Loop until the user clicks the close button.
done = False
 
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
 
# Hide the mouse cursor
pygame.mouse.set_visible(False)
 
# -------- Main Program Loop -----------
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
 
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # When the mouse button is pressed, see if we are in contact with other sprites:
            # Когда кнопка мыши нажата, смотрить не находимся ли мы в контакте с другими спрайтами:
            blocks_hit_list = pygame.sprite.spritecollide(player, block_list, False)
             
            # Set the list of blocks we are in contact with as the list of blocks being carried.    
            # Задать список блоков с которыми мы находимся в контакте
            player.carry_block_list = blocks_hit_list
 
        elif event.type == pygame.MOUSEBUTTONUP:
            # если не было события мыши- список контактов пустой
            player.carry_block_list = []
             
    all_sprites_list.update() # обновляем список всех блоков
     
    # Clear the screen
    screen.fill(WHITE)
 
    # Draw all the spites
    all_sprites_list.draw(screen)
 
    # Limit to 60 frames per second
    clock.tick(60)
 
    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()
 
pygame.quit()

Просмотров: 387 | Добавил: kuzma | Рейтинг: 0.0/0
Всего комментариев: 0
avatar

Сайт создан для помощи тем, кто делает первые шаги в программировании.

- автор идеи Кузьма Кузин

Возможность бесплатного доступа ко всем материалам и скриптам.

-совместная работа с группой молодых программистов

Срипты для автоматического заработка на SEO сайтах.

- для всех пользователей всё по цене в 1 EUR