— boreal-kiss.net

Archive
Tag "pygame"

As a pygame exercise, I wrote a scalable Nyan Cat animation from scratch, i.e., everything from Python code.

Example

The simplest implementation is here. To run animation you have to take the following three steps:

  1. Create objects (cat, rainbow, and stars)
  2. Draw the objects
  3. Update the objects’ state.

Note that half of the code is boilerplate for pygame. You of course need pygame to run the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
	import pygame
	from nyancat import Nyancat
	from rainbow import Rainbow
	from star_manager import StarManager
 
	pygame.init()
	DISPLAY_SURFACE = pygame.display.set_mode((320, 240))
	BACKGROUND_COLOR = pygame.Color(15, 77, 143)
	DISPLAY_SURFACE.fill(BACKGROUND_COLOR)
	FPS = 12
	CLOCK = pygame.time.Clock()
 
	#Create objects.
	cat = Nyancat(pygame.Rect(110, 90, 100, 250))
	rainbow = Rainbow(cat.rect, cat.pixelSize)
	stars = StarManager(DISPLAY_SURFACE.get_rect(), cat.pixelSize, 10)
 
	while True:
		DISPLAY_SURFACE.fill(BACKGROUND_COLOR)
 
		for e in pygame.event.get():
			if e.type == pygame.QUIT:
				pygame.quit()
				sys.exit()
 
		#Draw the objects. 
		rainbow.draw(DISPLAY_SURFACE)
		cat.draw(DISPLAY_SURFACE)
		stars.draw(DISPLAY_SURFACE)
 
		#Update the animation state of the objects.
		rainbow.update()
		cat.update()
		stars.update()
 
		pygame.display.update()
		CLOCK.tick(FPS)

Download

You can download the source from https://github.com/borealkiss/nyancat.py.

Read More