首页 > 编程语言 > python实现吃苹果小游戏
2020
09-24

python实现吃苹果小游戏

本文实例为大家分享了python实现吃苹果小游戏的具体代码,供大家参考,具体内容如下

1.公共类模块

import pygame
from pygame.rect import Rect
 
 
def print_text(font, x, y, text, color=(255, 255, 255)):
 imgText=font.render(text, True, color)
 screen=pygame.display.get_surface()
 screen.blit(imgText,(x, y))
 
class MySprite(pygame.sprite.Sprite):
 def __init__(self):
  pygame.sprite.Sprite.__init__(self)
  self.master_image=None
  self.frame = 0
  self.old_frame = -1
  self.frame_width = 1
  self.frame_height = 1
  self.first_frame = 0
  self.last_frame = 0
  self.columns = 0
  self.last_time = 1
  self.direction = 0
  self.velocity = 0
 
 def _getx(self): return self.rect.x
 def _gety(self): return self.rect.y
 
 def _setx(self, value): self.rect.x = value
 def _sety(self, value): self.rect.y = value
 """
 描述
 property() 函数的作用是在新式类中返回属性值。
 
 语法
 以下是 property() 方法的语法:
 
 class property([fget[, fset[, fdel[, doc]]]])
 参数
 fget -- 获取属性值的函数
 fset -- 设置属性值的函数
 fdel -- 删除属性值函数
 doc -- 属性描述信息
 返回值
 返回新式类属性。
 """
 X = property(_getx, _setx)
 Y = property(_gety, _sety)
 
 #位置属性
 def _getpos(self): return self.rect.topleft
 def _setpos(self, pos): self.rect.topleft = pos
 position = property(_getpos, _setpos)
 
 def load(self, filename, width, height, columns):
  self.master_image=pygame.image.load(filename).convert_alpha()
  self.frame_height = height
  self.frame_width = width
  self.rect = Rect(0, 0, width, height)
  self.columns = columns
 
  rect = self.master_image.get_rect()
  self.last_frame = (rect.width//width)*(rect.height//height) - 1
 
 def update(self, current_time, rate=30):
  #跟新动画帧
  if current_time > self.last_time + rate:
   self.frame += 1
   if self.frame > self.last_frame:
    self.frame = self.first_frame
   self.last_time = current_time
  #仅当更改时才创建帧
  if self.frame != self.old_frame:
   frame_x = (self.frame % self.columns) * self.frame_width
   frame_y = (self.frame // self.columns) * self.frame_height
   rect=Rect(frame_x, frame_y, self.frame_width, self.frame_height)
   self.image = self.master_image.subsurface(rect)
   self.old_frame = self.frame
class Point(object):
 def __init__(self, x, y):
  self.x = x
  self.y = y
 def getx(self): return self.x
 def gety(self): return self.y
 def setx(self,value): self.x=value
 def sety(self,value): self.y=value
 
 x=property(getx,setx)
 y=property(gety,sety)
 
 def __str__(self):
  return 'x:'+"{:.0f}".format(self.x) + 'y:'+"{:.0f}".format(self.y)

2.首先生成随机苹果,然后监听键盘移动,播放动画。精灵和苹果碰撞检测,检测是吃掉苹果

import pygame
from pygame.rect import Rect
 
from . import MyLibrary
import random
import sys
 
 
def calc_velocity(direction, vel=1.0):
 velocity = MyLibrary.Point(0, 0)
 if direction == 0:#上
  velocity.y = -vel
 elif direction == 2:#右
  velocity.x = vel
 elif direction == 4:#下
  velocity.y == vel
 elif direction == 6:#左
  velocity.x == -vel
 return velocity
 
pygame.init()
screen = pygame.display.set_mode(800,600)
font=pygame.font.Font(None, 36)
timer=pygame.time.Clock()
 
#创建精灵组
player_group=pygame.sprite.Group()
food_group=pygame.sprite.Group()
 
#初始化玩家精灵组
player=MyLibrary.MySprite()
player.load('farmer.png',96,96,8)############-----------------图片
player.position=80, 80
player.direction= 4
player_group.add(player)
 
#初始化food精灵组
for n in range(1, 50):
 food= MyLibrary.MySprite()
 food.load('food.png',35,35,1) #################-----------食物图片
 food.position=random.randint(0, 780), random.randint(0, 580)
 food_group.add(food)
 
game_over= False
player_moving = False
plyer_health = False
 
while True:
 timer.tick(30)
 ticks = pygame.time.get_ticks()
 
 for event in pygame.event.get():
  if event.type == pygame.QUIT:
   pygame.quit()
   sys.exit()
 keys = pygame.key.get_pressed()
 if keys[pygame.key.K_UP]:
  player.direction=0
  player_moving = True
 elif keys[pygame.key.k_DOWN]:
  player_moving = True
  player.direction=4
 elif keys[pygame.key.K_RIGHT]:
  player.direction = 2
  player_moving = True
 elif keys[pygame.key.K_LEFT]:
  player.direction = 6
  player_moving = True
 else:
  player_moving = False
 
 if not game_over:
  # 根据不同的方向,角色移动不同的动画帧
  player.first_frame = player.direction*player.columns
  player.last_time = player.first_frame + player.columns -1
  if player.frame < player.first_frame:
   player.frame = player.first_frame
 
  if not player_moving:
   #停止更新动画帧
   player.frame = player.first_frame=player.last_frame
  else:
   player.velocity = calc_velocity(player.direction,1.5)
   player.velocity.x*=1.5
   player.velocity.y*=1.5
 
  #跟新玩家精灵组
  player_group.update(ticks,50)
 
  #移动玩家
  if player_moving:
   player.X += player.velocity.x
   player.Y += player.velocity.y
   if player.X < 0: player.X = 0
   elif player.X >700: player.X =700
   if player.Y < 0: player.Y = 0
   elif player.Y >500:player.Y =500
 
  #检测玩家是否与食物冲突,是否吃到苹果
  attacker = None
  attacker = pygame.sprite.spritecollideany(player,food_group)
  if attacker != None:
   if pygame.sprite.collide_circle_ratio(0.65)(player,food_group):
    plyer_health += 2
    food_group.remove(attacker)
  if plyer_health > 100:
   plyer_health=100
   #跟新食物精灵组
   food_group.update(ticks, 50)
   if food_group.__len__() == 0:
    game_over = True
 
  screen.fill((50,50,100))
  food_group.draw(screen)
  player_group.draw(screen)
 
  pygame.draw.rect(screen,(510,150,50,180),Rect(300,570,plyer_health*2,25))
  pygame.draw.rect(screen, (100, 200, 100, 180), Rect(300, 570, 200, 2))
 
  if game_over:
   MyLibrary.print_text(font, 300, 100,'Game Over!')
  pygame.display.update()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧