import pygame
from pygame.locals import *
from random import randint
import time
pygame.init()
屏幕宽度,屏幕高度=480,360
screen = pygame.display.set_mode((屏幕宽度,屏幕高度))
pygame.display.set_caption("行走的小猫--作者:李兴球")
背景 = pygame.image.load("海洋背景.png")
frame0 = pygame.image.load("Walk1.png")
frame1 = pygame.image.load("Walk1b.png")
frame2 = pygame.image.load("Walk2.png")
frame3 = pygame.image.load("Walk2b.png")
frame4 = pygame.image.load("Walk3.png")
frame5 = pygame.image.load("Walk3b.png")
frame6 = pygame.image.load("Walk4.png")
frame7 = pygame.image.load("Walk4b.png")
frame8 = pygame.image.load("Walk5.png")
frame9 = pygame.image.load("Walk5b.png")
framea = pygame.image.load("Walk6.png")
frameb = pygame.image.load("Walk6b.png")
framec = pygame.image.load("Walk7.png")
framed = pygame.image.load("Walk7b.png")
framee = pygame.image.load("Walk8.png")
framef = pygame.image.load("Walk8b.png")
framesRight = [frame0,frame1,frame2,frame3,frame4,frame5,frame6,frame7,frame8,frame9,framea,frameb,framec,framed,framee,framef]
framesLeft = [pygame.transform.flip(f,True,False) for f in framesRight]
class GameObject():
def __init__(self,framesRight,framesLeft,x,y,w,h):
self.frames_right = framesRight
self.frames_left = framesLeft
self.造型数量 = len(self.frames_left)
self.造型编号=0
self.造型切换间隔时长=0.1 # 秒
self.移动间隔时长=0.1 # 秒
self.x = x
self.y =y
self.w = w
self.h = h
self.rect = pygame.Rect(self.x,self.y,self.w,self.h)
self.xspeed=randint(-5,5)
self.yspeed=0
self.begintime = time.time()
self.begintime2 = time.time()
def 下一个造型(self):
if (time.time()-self.begintime) >= self.造型切换间隔时长:
self.造型编号 = self.造型编号 + 1
self.造型编号 = self.造型编号 % self.造型数量
self.begintime = time.time()
def move(self):
if (time.time()-self.begintime2) >= self.移动间隔时长:
self.x = self.x + self.xspeed
self.y = self.y + self.yspeed
self.rect.x = self.x
self.rect.y = self.y
if self.rect.left<0 or self.rect.right>屏幕宽度:
self.xspeed = - self.xspeed
self.begintime2 = time.time()
def draw(self):
if self.xspeed>0:
screen.blit(self.frames_right[self.造型编号],self.rect)
else:
screen.blit(self.frames_left[self.造型编号],self.rect)
font = pygame.font.Font("c:/windows/fonts/msyh.ttf",30)
textImage =font.render("行走的小猫",True,(0,2,255))
(tx,ty,tw,th) = textImage.get_rect()
textpos=(屏幕宽度//2 - tw //2,屏幕高度//2 - th/2 -100)
#新建一个小猫测试
cat = GameObject(framesRight,framesLeft,100,200,80,90)
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
screen.blit(背景,(0,0))
cat.move()
cat.下一个造型()
cat.draw()
screen.blit(textImage,textpos)
pygame.display.update()