Python realizes apple eating game

The examples in this article share the specific code of python to realize the apple-eating game for your reference. The specific content is as follows

  1. Public class module
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))classMySprite(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
 """
 description
 property()The function of the function is to return the attribute value in the new-style class.
 
 grammar
 The following is the property()Method syntax:classproperty([fget[, fset[, fdel[, doc]]]])
 parameter
 fget --Function to get attribute value
 fset --Function to set attribute value
 fdel --Delete attribute value function
 doc --Property description information
 return value
 Returns the new-style class attributes.
 """
 X =property(_getx, _setx)
 Y =property(_gety, _sety)
 
 # Location attribute
 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):
 # With new animation frame
 if current_time   self.last_time + rate:
 self.frame +=1if self.frame   self.last_frame:
 self.frame = self.first_frame
 self.last_time = current_time
 # Create frames only when changed
 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
classPoint(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)
  1. First generate random apples, then monitor keyboard movement and play animation. Elf and apple collision detection, detection is to eat apple
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:#on
velocity.y =-vel
elif direction ==2:#right
velocity.x = vel
elif direction ==4:#under
velocity.y == vel
elif direction ==6:#left
velocity.x ==-vel
return velocity
pygame.init()
screen = pygame.display.set_mode(800,600)
font=pygame.font.Font(None,36)
timer=pygame.time.Clock()
# Create a sprite group
player_group=pygame.sprite.Group()
food_group=pygame.sprite.Group()
# Initialize the player sprite group
player=MyLibrary.MySprite()
player.load('farmer.png',96,96,8)############-----------------image
player.position=80,80
player.direction=4
player_group.add(player)
# Initialize the food wizard group
for n inrange(1,50):
food= MyLibrary.MySprite()
food.load('food.png',35,35,1) #################-----------Food pictures
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:
# According to different directions, the character moves in different animation frames
player.first_frame = player.direction*player.columns
player.last_time = player.first_frame + player.columns -1if player.frame < player.first_frame:
player.frame = player.first_frame
if not player_moving:
# Stop updating animation frames
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
# Team with new player sprites
player_group.update(ticks,50)
# Mobile player
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 =700if player.Y <0: player.Y =0
elif player.Y  500:player.Y =500
# Check if the player is in conflict with food and if he has eaten an apple
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
# With the new food wizard group
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()

The above is the whole content of this article, I hope it will be helpful to everyone's study.

Recommended Posts

Python realizes apple eating game
Python3 realizes airplane war game
Python realizes the guessing game
Python realizes spaceship war
Python implements tic-tac-toe game
Python, PyGame game project
Python implements Tetris game
Python implements minesweeper game
Python realizes stitching pictures
Python realizes online translation
Python realizes tank battle
Python implements guessing game
python guess the word game
Python realizes online translation function
Python implements a guessing game
Python implements digital bomb game
Python implements simple tic-tac-toe game
Python realizes 3D map visualization
Python realizes face sign-in system
Python realizes batch naming photos
Python implements the brick-and-mortar game
Python realizes business card management system
Python simply implements the snake game
Python3 realizes business card management system
Python realizes express price query system
Python realizes online microblog data visualization
Python implements digital bomb game program
Python realizes image recognition car function
Python realizes udp transmission picture function
Python realizes console output color font