首页 > 代码库 > 控制小乌龟

控制小乌龟

 1 import pygame
 2 import sys
 3 from pygame.locals import *
 4 
 5 # 初始化Pygame
 6 pygame.init()
 7 
 8 size = width, height = 600, 400
 9 speed = [-2, 1]
10 bg = (255, 255, 255) # RGB
11 
12 # 创建指定大小的窗口 Surface
13 screen = pygame.display.set_mode(size)
14 # 设置窗口标题
15 pygame.display.set_caption("初次见面,请大家多多关照!")
16 
17 # 加在图片
18 turtle = pygame.image.load("D://turtle.png")
19 # 获得图像的位置矩形
20 position = turtle.get_rect()
21 
22 l_head = turtle
23 r_head = pygame.transform.flip(turtle, True, False)
24 
25 while True:
26     for event in pygame.event.get():
27         if event.type == pygame.QUIT:
28             sys.exit()
29 
30         #控制图像
31 
32         if event.type == KEYDOWN:
33             if event.key == K_LEFT:
34                 turtle = l_head
35                 speed = [-1, 0]
36 
37             if event.key == K_RIGHT:
38                 turtle = r_head
39                 speed = [1, 0]
40 
41             if event.key == K_UP:
42                 speed = [0, -1]
43 
44             if event.key == K_DOWN:
45                 speed = [0, 1]
46 
47 
48     # 移动图像
49     position = position.move(speed)
50 
51     if position.left < 0 or position.right > width:
52         # 翻转图像
53         turtle = pygame.transform.flip(turtle, True, False)
54         # 反方向移动
55         speed[0] = -speed[0]
56 
57     if position.top < 0 or position.bottom > height:
58         speed[1] = -speed[1]
59 
60     # 填充背景
61     screen.fill(bg)
62     # 更新图像
63     screen.blit(turtle, position)
64     # 更新界面
65     pygame.display.flip()
66     # 延迟10毫秒
67     pygame.time.delay(10)

 

控制小乌龟