python之pygame使surface对象移动起来,用按键控制(二)

import pygame
import sys
from pygame.locals import *
#pygame是一个包,要将pygame初始化,让里面的类做好准备
pygame.init()

#初始化
bg = (213, 1, 144)
speed = [-2, 1]
size = width, height = 600, 400

#设置界面大小
screen = pygame.display.set_mode(size)
#设置界面标题
pygame.display.set_caption("turtle play game")
#加载图片
turtle = pygame.image.load("turtle.png")
#确定图片位置
position = turtle.get_rect()
#turtle的方向
l_head = turtle
r_head = turtle  = pygame.transform.flip(turtle, True, False)
while True:
    #可以使游戏退出
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                turtle = l_head
                speed = [-2, 0]
            if event.key == K_RIGHT:
                turtle = r_head
                speed = [2, 0]
            if event.key == K_UP:
                speed = [0, -2]
            if event.key == K_DOWN:
                speed = [0, 2]

    #移动图像
    position = position.move(speed)
    #判断图像位置,使小乌龟不出边界
    if position.left <0 or position.right >width:
        #翻转图像
        turtle  = pygame.transform.flip(turtle, True, False)
        #使surface对象的速度调换
        speed[0] = -speed[0]


    if position.top <0 or position.bottom >height:
        speed[1] = -speed[1]
    #加载背景
    screen.fill(bg)
    #更新小乌龟的位置
    screen.blit(turtle, position)
    #更新屏幕,双缓冲模式
    pygame.display.flip()
    #延时
    pygame.time.delay(10)
比上(一)多了几行代码
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值