Sử dụng thư viện Pygame để lập trình game hứng táo vui nhộn.
Link download hình ảnh và audio dùng trong chương trình: Click here
Full Code:
import pygame
import random
from pygame import mixer
def show_score(x,y):
font_score=font.render(“Score: “+str(score),True,(255,0,0))
screen.blit(font_score,(x,y))
#intialize the pygame
pygame.init()
#create the screen
screen=pygame.display.set_mode((800,600))
#title and icon
pygame.display.set_caption(‘Catch Apple’)
icon=pygame.image.load(‘apple.png’)
pygame.display.set_icon(icon)
#background
background_img=pygame.image.load(‘background.png’)
background_x=0
background_y=0
background_width=800
background_hight=600
background=pygame.transform.scale(background_img,(background_width,background_hight))
#apple
apple_img=pygame.image.load(‘apple.png’)
apple_width=50
apple_hight=50
apple=pygame.transform.scale(apple_img,(apple_width,apple_hight))
gravity=0.05
num_of_apples=3
apple_rect=[0]*num_of_apples
apple_x=[]
apple_y=[]
y_apple_velocity=[2.0]*(num_of_apples)
for i in range(num_of_apples):
x=random.randint(50,750)
apple_x.append(x)
y=random.randint(0,10)
apple_y.append(y)
#bowl
bowl_img=pygame.image.load(‘bowl.png’)
bowl_x=400
bowl_y=530
bowl_width=120
bowl_hight=75
bowl=pygame.transform.scale(bowl_img,(bowl_width,bowl_hight))
#score
score=0
font=pygame.font.Font(‘freesansbold.ttf’,32)
score_x=10
score_y=10
#sound
bgmusic=mixer.Sound(“bgmusic.mp3”)
sound1=mixer.Sound(“touch.wav”)
mixer.Sound.play(bgmusic)
clock=pygame.time.Clock()
#game loop
running=True
while running:
clock.tick(60)
#RGB – Red, Green, Blue
screen.fill((255,255,255))
background_rect=screen.blit(background,(background_x,background_y))
bowl_rect=screen.blit(bowl,(bowl_x,bowl_y))
for i in range(num_of_apples):
apple_rect[i]=screen.blit(apple,(apple_x[i],apple_y[i]))
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_LEFT:
bowl_x-=5
if event.key==pygame.K_RIGHT:
bowl_x+=5
#bowl movement
if bowl_x<=0:
bowl_x=0
elif bowl_x>=680:
bowl_x=680
#apple movement
for i in range(num_of_apples):
y_apple_velocity[i]+=gravity
apple_y[i]+=y_apple_velocity[i]
if apple_y[i]>610:
apple_x[i]=random.randint(50,750)
apple_y[i]=random.randint(0,10)
y_apple_velocity[i]=2
gravity=0.05
#bowl and apple touch
if bowl_rect.colliderect(apple_rect[i]):
mixer.Sound.play(sound1)
apple_x[i]=random.randint(50,750)
apple_y[i]=random.randint(0,10)
y_apple_velocity[i]=2
gravity=0.05
score+=1
show_score(score_x,score_y)
pygame.display.update()
Game này thích quá