2018年2月14日水曜日

開発環境

Teach Your Kids to Code: A Parent-Friendly Guide to Python Programming (Bryson Payne(著)、No Starch Press)のChapter 9.(User Interaction: Get into the Game)、PROGRAMMING CHALLENGES、#3: THROWING SMILEYSを取り組んでみる。

#3: THROWING SMILEYS

コード(Emacs)

Python 3

#!/usr/bin/env python3
import pygame
import random

black = (0, 0, 0)
unit = 60
width = unit * 16
height = unit * 9

pygame.init()
screen = pygame.display.set_mode([width, height])
pygame.display.set_caption('Smiley Explosion')

keep_going = True
mousedown = False
clock = pygame.time.Clock()
pic = pygame.image.load('CrazySmile.bmp')
colorkey = pic.get_at((0, 0))
pic.set_colorkey(colorkey)
sprite_list = pygame.sprite.Group()


class Smiley(pygame.sprite.Sprite):

    def __init__(self, pos, xvel, yvel):
        pygame.sprite.Sprite.__init__(self)
        self.image = pic
        self.scale = random.randrange(10, 100)
        self.image = pygame.transform.scale(
            self.image, (self.scale, self.scale))
        self.rect = self.image.get_rect()
        self.pos = pos
        self.rect.x = pos[0] - self.scale / 2
        self.rect.y = pos[1] - self.scale / 2
        self.xvel = xvel
        self.yvel = yvel

    def update(self):
        self.rect.x += self.xvel
        self.rect.y += self.yvel
        if self.rect.x <= 0 or self.rect.x > screen.get_width() - self.scale:
            self.xvel = -self.xvel * 0.8
        if self.rect.y <= 0 or self.rect.y > screen.get_height() - self.scale:
            self.yvel = -self.yvel * 0.8


while keep_going:
    pygame.mouse.get_rel()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            keep_going = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            mousedown = True
        if event.type == pygame.MOUSEBUTTONUP:
            mousedown = False
    screen.fill(black)
    sprite_list.update()
    sprite_list.draw(screen)
    clock.tick(60)
    pygame.display.update()
    if mousedown:
        speed = pygame.mouse.get_rel()
        speedx = speed[0]
        speedy = speed[1]
        if speedx == 0 and speedy == 0:
            speedx = random.randrange(-5, 6)
            speedy = random.randrange(-5, 6)
        smiley = Smiley(pygame.mouse.get_pos(), speedx, speedy)
        sprite_list.add(smiley)

pygame.quit()

入出力結果(Terminal, Jupyter(IPython))

$ ./sample3.py
$

0 コメント:

コメントを投稿

関連コンテンツ