The following is a basic PVZ2 treadmill code example:
importpygame
Import time
Random input
pygame.init()
# Game window size
Display width =800
Display height =600
# Define colors
Black = (0,0,0)
White =(255, 255, 255)
Red = (255,0,0)
# Create a game window to surf.
game display = py game . display . set _ mode((display _ width,display_height))
Pygame.display.set _ caption ('PVZ 2 treadmill')
# Set the game clock
clock=pygame.time.Clock()
# Load pictures
player img = py game . image . load(' player . png ')
obstacle img = py game . image . load(' barrier . png ')
# Define a function and draw a villain
defplayer(x,y):
gameDisplay.blit(playerImg,(x,y))
# Define functions and draw obstacles
defobstacle(x,y):
gameDisplay.blit(obstacleImg,(x,y))
# Define functions and display scores
Define score (count):
font=pygame.font.SysFont(None,25)
text = font . render(" score:"+str(count),True,black)
gameDisplay.blit(text,(0,0))
# Define functions and show obstacles
Defobstacles _ dodge (count):
font=pygame.font.SysFont(None,25)
Text=font.render ("Avoid obstacles:" +str(count), True, black)
gameDisplay.blit(text,(0,20))
# Main game loop
defgame_loop():
x=(display_width0.45)
y=(display_height0.8)
x_change=0
Obstacle _ Speed =7
Obstacle width = 100
Obstacle height = 100
Obstacle _startx=random.randrange(0, display width-obstacle width)
Obstacle _ Start =-600
Obstacle _ Avoidance =0
# Exit Game Logo
Game _ Exit = False
# Loop until you quit the game
whilenotgame_exit:
foreventinpygame.event.get():
ifevent.type==pygame。 Exit:
Game exit = true
ifevent.type==pygame。 Keys:
ifevent.key==pygame。 K_LEFT:
x_change=-5
elifevent.key==pygame。 K_RIGHT:
x_change=5
ifevent.type==pygame。 Keyboard input:
ifevent.key==pygame。 K_LEFTorevent.key==pygame。 K_RIGHT:
x_change=0
x+=x_change
GameDisplay.fill (white)
# Draw obstacles
Obstacles (obstacle _ start, obstacle _ start)
Obstacle _ Start+= Obstacle _ Speed
# Draw a villain
Player (x, y)
Score (avoid obstacles)
Avoid obstacles (avoid obstacles)
ifx & gtdisplay_width-70orx
Game exit = true
If obscure _ starty & gt display height:
Obstacle _ Start = 0- Obstacle _ Height
Obstacle _startx=random.randrange(0, display width-obstacle width)
Obstacle _ Avoidance += 1
Obstacle _ Speed += 1
Ifyifx & gt obstacle _ startxandxobstacle _ startxandx+68 game _ exit = true
pygame.display.update()
clock.tick(60)
pygame.quit()
Exit ()
game_loop()
The above is the basic code example of PVZ2 treadmill. Through this code, we can see people running and obstacles appearing and moving in the game. During the game, the player needs to control the villain to avoid obstacles and run as far as possible. This code example is just a simple implementation, and you can further optimize and extend it as needed.