pygame Notebook

由于使用emacs-org进行编辑,为方便使用了英文

Table of Contents

  1. chimp (instance)

    1. importing modules
    2. loading resources
      1. image
      2. sound
    3. game object classes
      1. fist
      2. chimp
    4. init everything
    5. create the background
      1. create the surface
      2. put text on the background
      3. display the background (after the setup)
    6. prepare game obj
    7. main loop
    8. handle input events
    9. update all the sprites
    10. draw the entire scene
    11. no need to do anything cleaning up
  2. sprites
    1. use group
    2. group types
      1. Group
      2. GroupSingle
      3. RenderPlain
      4. RenderClear
      5. RenderUpdates
    3. collision detection
      1. spritecollide(sprite, group, dokill) -> list
      2. groupcollide(group1, group2, dokill1, dokill2) -> dictionary
    4. create my own group class
  3. numpy (Numeric Python) intro
    1. mathematical operations
    2. array slice
    3. 2d array slice
  4. surfarray
  5. making game

chimp (instance)

importing modules

import os, sys
import pygame
from pygame.locals import *if not pygame.font: print('Warning, fonts disabled')
if not pygame.mixer: print('Warning, sound disabled')

os, sys modules can get independent on platforms.
pygame.locals: commonly used constants and functions,
not necessary to include, just include pygame is enough.

loading resources

image

def load_image(name, colorkey = None):fullname = os.path.join("assets", name)try:image = pygame.image.load(fullname)except pygame.error as message:print("cannot load image:", name)raise SystemExit(message)image = image.convert()if colorkey is not None:if colorkey is -1:colorkey = image.get_at((0, 0,))image.set_colorkey(colorkey, RLEACCEL)return image, image.get_rect()

create a fullname, tryna load the img,
raise exception if failed, convert the img to the format
of the screen to make it faster to blit,
set a transparent colorkey,
default the (0, 0,) point’s color,
return the img and its rect.

REACCEL can boost up blitting but slow down modifying.

sound

def load_sound(name):class NoneSound:def play(self): passif not pygame.mixer:return NoneSound()fullname = os.path.join("assets", name)try:sound = pygame.mixer.Sound(fullname)except pygame.error as message:print("cannot load sound", wav)raise SystemExit(message)return sound

game object classes

fist

class Fist(pygame.sprite.Sprite):def __init__(self):pygame.sprite.Sprite.__init__(self)self.image, self.rect = load_image("fist.bmp", -1)self.punching = 0def update(self):pos = pygame.mouse.get_pos()self.rect.midtop = posif self.punching:self.rect.move_ip(5, 10)def punch(self, target):if not self.punching:self.punching = 1hitbox = self.rect.inflate(-5, -5)return hitbox.colliderect(target.rect)def unpunch(self):self.punching = 0

use one of the sprite drawing Group classes.

These classes can draw sprites that have image and rect
attribute.

By simply changing these two attributes, the renderer will
draw the current image at the current position.

All sprites have an update() method, called once per frame.
should put in code that moves and updates the variables
for the sprite.

chimp

class Chimp(pygame.sprite.Sprite):def __init__(self):pygame.sprite.Sprite.__init__(self)self.image, self.rect = load_image("chimp.bmp", -1)screen = pygame.display.get_surface()self.area = screen.get_rect()self.rect.topleft = 10, 10self.move = 9self.dizzy = 0def update(self):if self.dizzy():self._spin()else:self._walk()def _walk(self):newpos = self.rect.move((self.move, 0))if not self.area.contains(newpos):if self.rect.left < self.area.left or \self.rect.right > self.area.right:self.move = -self.movenewpos = self.rect.move((self.move, 0))self.image = pygame.transform.flip(self.image, 1, 0)self.rect = newposdef _spin(self):center = self.rect.centerself.dizzy += 12if self.dizzy >= 360:self.dizzy = 0self.image = self.originalelse:rotate = pygame.transform.rotateself.image = rotate(self.original, self.dizzy)self.rect = self.image.get_rect(center = center)def punched(self):if not self.dizzy:self.dizzy = 1self.original = self.image

rotate was made as a local reference,
to make that line shorter.

ALWAYS ROTATE FROM THE ORIGINAL PICTURE!!!

'cause each rotation will cost a loss of quality and size.

– when to make a copy?

– when first punched.

init everything

pygame.init()
screen = pygame.display.set_mode((468, 60))
pygame.display.set_caption("Chimp Fever")
pygame.mouse.set_visible(0)

init(): initialize all the pygame modules imported.

display: if not set, pygame’ll choose the best
color depth.

mouse.set_visible(0): set invisible

create the background

create a single surface to represent the background

create the surface

background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))

put text on the background

get text rendered onto the background surface

if pygame.font:font = pygame.font.Font(None, 36)text = font.render("Pummel The Chimp, And Win $$$", 1, (1, 10, 10))textpos = text.get_rect(centerx = background.get_width() / 2)background.blit(text, textpos)

None can be replaced by a TrueType font.

render: create a new surface with appropriate size

1 to tell the renderer to use antialiased text

display the background (after the setup)

screen.blit(background, (0, 0))
pygame.display.flip()

flip: handles the entire window area
both single-buffered and double-buffered surfaces

  • Note taken on [2020-01-10 周五 00:45]

double-buffering:
在图形图像显示过程中,计算机从显示缓冲区取数据然后显示,
很多图形的操作都很复杂需要大量的计算,
很难访问一次显示缓冲区就能写入待显示的完整图形数据,
通常需要多次访问显示缓冲区,每次访问时写入最新计算的图形数据。
而这样造成的后果是一个需要复杂计算的图形,
你看到的效果可能是一部分一部分地显示出来的,造成很大的闪烁不连贯。
而使用双缓冲,可以使你先将计算的中间结果存放在另一个缓冲区中,
待全部的计算结束,该缓冲区已经存储了完整的图形之后,
再将该缓冲区的图形数据一次性复制到显示缓冲区。

prepare game obj

create all the objects

whiff_sound = load_sound("whiff.wav")
punch_sound = load_sound("punch.wav")
chimp = Chimp()
fist = Fist()
allsprites = pygame.sprite.RenderPlain((fist, chimp))
clock = pygame.time.Clock()

allsprites: a sprite Group named RenderPlain.

RenderPlain can draw all the sprites it contains
to the screen.

clock: used in the mainloop to control the
framerate

main loop

while 1:clock.tick(60)

no more than 60 frames per second

handle input events

work with the event queue

for event in pygame.event.get():if event.type == QUIT:returnelif event.type == KEYDOWN and event.key == K_ESCAPEreturnelif event.type == MOUSEBUTTONDOWN:if fist.punch(chimp):punch_sound.play()chimp.punched()else:whiff_sound.play()elif event.type == MOUSEBUTTONUP:fist.unpunch()

K_ESCAPE: ESC.

update all the sprites

allsprites.update()

sprite groups have an update() method,
which simply calls the update() for all the sprites
it contains.

draw the entire scene

screen.blit(background, (0, 0))
allsprites.draw(screen)
pygame.display.flip()

no need to do anything cleaning up

sprites

remember to Sprite.__init__(self), or respond:

AttributeError: 'mysprite' instance has no attribute '_Sprite__g'

use group

  • Note taken on [2020-01-11 周六 00:48]
    get some methods here

belong to a group -> alive.

not belong to any group -> cleared up.

kill(): remove the sprite from all the groups it belonged to.

sprites(): return a iteratable object shows all the sprites
a group has.

update(): update all.

group types

Group

GroupSingle

contain at most 1 sprites, when added to, forget the old one.

RenderPlain

every sprite has a image and a rect.

has a draw() method that draw all the sprites on a surface
or a screen.

RenderClear

derived from RenderPlain.
add a method clear(): clear sprites from the screen
with background.

RenderUpdates

derived from RenderClear, Cadillac of rendering Groups.

the draw() method will return a list of rects of all sprites
showing all the area that is occupied.

collision detection

spritecollide(sprite, group, dokill) -> list

check for collisions between a single sprite
and a sprite group.

require a rect attribute for all the sprites used.

dokill: (boolean)
whether to call kill() on all crashed sprites.

return a list of all the sprites in the group that collides.

groupcollide(group1, group2, dokill1, dokill2) -> dictionary

dokill1: if true, kill all the crashed sprites in group1.

dokill2: if true, kill all the crashed sprites in group2.

dict: key is sprites in group1 that crashed.
its value is sprites in group2 that the key crashed

create my own group class

to get extra features.

numpy (Numeric Python) intro

deal with array, holds an array of fixed size,
and all elements inside an array are of the same type.

mathematical operations

apply to all elements in an array. (element-wise operations)

but only when able to apply the operation.

ex.

>>> array((1, 2, 3)) + array((4, 5, 6))
array([5, 7, 9])>>> array((1, 2, 3)) + array((3, 4))
Traceback (most recent call last):File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,) (2,)
# different size arrays cannot be added up.

array slice

same to python list.

sliced-out array still refers to the original array.
so if when changing the sliced-out array,
the original one changes, too.

2d array slice

use , to separate different dimention’s indices,
and for each dimention’s index,
almost same to 1d scenario, but can use : to show “all”.

ex.

>>> b = array(((1, 2, 3), (3, 4, 5)))
>>> b[0, 1]
2
>>> b[1, :]
array([3, 4, 5])
>>> b[1]
array([3, 4, 5])
>>> b[:, :2]
array([[1, 2], [3, 4]])

surfarray

be sure to import: use exception ImportError

try: import numpy as npimport pygame.surfarray as surfarray
except ImportError:raise ImportErrer, "NumPy and Surfarray are required"

making game

pygame笔记(更新中相关推荐

  1. python甲鱼怎么修改,跟小甲鱼自学python笔记 更新中…

    看完这些笔记自己就可以入门Python了 在B站上看小甲鱼的视频,顺便整理一下自己的笔记. 第十课 列表 1.列表中可以存放一些什么东西? 在列表中可以存放整数.浮点数.字符串.对象-甲鱼粉说Pyth ...

  2. Android V7包学习笔记更新中.....

    关于V4 V7 V13 VX包介绍转自这里 1, Android Support V4, V7, V13是什么? 本质上就是三个java library. 2, 为什么要有support库? 如果在低 ...

  3. 《亿级流量JAVA高并发与网络编程实战》笔记--------更新中

    <亿级流量JAVA高并发与网络编程实战>笔记 第一章 高并发概述 "高并发技术" 是一个广义的概念,是指一种高效的地实现并发需求的解决方案,是技术领域的名称,可以包含架 ...

  4. SQL手工注入入门级笔记(更新中)

    一.字符型注入 针对如下php代码进行注入: $sql="select user_name from users where name='$_GET['name']'"; 正常访问 ...

  5. 快速傅里叶变换学习笔记(更新中)

    快速傅里叶变换(FFT)学习笔记 简介 快速傅里叶变换($ \rm Fast Fourier Transformation $), 简称 \(\rm FFT\), 用于在 $ \Theta(n\log ...

  6. tshark/wireshark/tcpdump实战笔记(更新中...)

    注意Wireshark表示意义: Source: 发送方IP Destination: 接收方IP Protoco: 协议 Length: 这里显示的物理层(Frame)数据长度,Frame层长度最长 ...

  7. 线性代数笔记(更新中ing)

    文章目录 一.第一章:行列式(det) 1.二阶行列式 2.三阶行列式 3.n阶行列式 3.1 排列和逆序 3.2 n阶行列式 (主对角线上的)上.下三角和对角行列式 (辅对角线上的)上.下三角和对角 ...

  8. C#学习笔记(更新中)

    运算符 5.bool类型 在c#中我们用bool类型来描述对或者错. bool类型的值只有两个 一个true 一个false bool b=20==20; Console.WriteLine(b); ...

  9. 《硬核linux攻略》读书笔记更新中

    linux具有不同的三种接口:系统调用接口.库函数接口.应用程序接口. 用户启动shell窗口下进行工作. shell里先运行输入的命令行中的第一个字符串,搜索这个程序名,找到了就运行同时挂起shel ...

  10. 单片机入门学习单片通信协议学习笔记....更新中

    单片机各类通信协议 --来自于bilbil金善愚老 一.1-wire单总线 概述: 采用单根信号线既传输时钟又传输数据且数据传输是双向的.(单总线器件芯片有编制唯一的序列号(芯片通信地址)) 适用范围 ...

最新文章

  1. python3 内置函数map 返回的迭代器转为列表
  2. 微服务架构_企业中的微服务:敌是友?
  3. echart php mysql简书_echart 踩坑之路
  4. js中的可变参数arguments与json
  5. 如何通过 C# 实现对象的变更跟踪 ?
  6. PyTorch框架学习四——计算图与动态图机制
  7. AD打板过程简介(搭配某份教程实现)
  8. Spring Boot 集成 WebSocket,轻松实现信息推送!
  9. 超强功能file_put_contents()函数(集成了fopen、fwrite、fclose)
  10. 安卓手表ADB实用工具箱
  11. java 线程栈大小配置,jvm之栈、堆,jvm默认栈空间大小
  12. lisp画弯箭头_下篇-大神总结:CAD制图的43个技巧,都学会你就逆天了!
  13. android 光标的绘制,Android EditText(TextView)如何绘制闪烁的光标?
  14. 微软MSDN Web cast系列视频教程集锦
  15. Java集合类框架总结
  16. miui修改Android,无法修改小米MIUI设备中的系统设置
  17. selenium实现自动播放音乐
  18. iOS 内购项目的App Store推广
  19. [知识总结]Dp-区间dp
  20. DirectX12的初始化

热门文章

  1. snap 无法卸载_你手机里有哪些不想卸载的良心 App?
  2. 高速接口中的PRBS的设计
  3. 图像和流媒体 -- 帧率、分辨率、码流的概念和关系
  4. odbc An unsupported operation was attempted
  5. php strtotime 2099,PHP的strtotime()函数2039年bug问题
  6. 计算机网络dce是什么意思,DTE与DCE的解释
  7. 如何在AI(Adobe illustrator)里用角标
  8. 喂喂,说好的节操呢!
  9. Java 桥接方法(Bridge Method)
  10. app端分页 简单的分页 java