学习了pygame,身为一个IKUN所以,做了一个简单的小游戏。游戏规则是,使用键盘的方向键控制坤坤,当坤坤触碰到篮球,就会爆发出音乐”只因你太美“。代码如下:
import random import sys import pygame pygame.init() screen =
pygame.display.set_mode((495,299)) pygame.display.set_caption("篮球和鸡") #显示标题
icon = pygame.image.load("坤.webp") pygame.display.set_icon(icon) #显示标题图像 bgImg
= pygame.image.load("篮球和鸡.webp") #背景图 #添加音效
#pygame.mixer.music.load("鸡你太美.mp3") #pygame.mixer.music.play(-1) bao_sound =
pygame.mixer.Sound("鸡太美.mp3") #玩家移动和玩家位置 playerX=100 playerY=200 playerStep_X=0
playerStep_Y=0 playerImg = pygame.image.load("坤球.png") #导入游戏人物50*58 #篮球移动和篮球位置
ballX= random.randint(100,400) ballY= random.randint(20,150) ballStep=1 #篮球速度
ballImg = pygame.image.load("篮球.png") #导入篮球50*37 #def process_events(): def
delay(): for i in range(1,101): for q in range(1,301): pass #篮球类 class Balls():
def __init__(self): self.img = pygame.image.load("篮球.png") self.x =
random.randint(100,400) self.y = random.randint(20,150) self.step =
random.randint(2,6) balls = [] number_of_balls =6 for i in range
(number_of_balls): balls.append(Balls()) #游戏主循环 while True:
screen.blit(bgImg,(0,0)) screen.blit(playerImg, (playerX, playerY)) for event
in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit()
if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: playerStep_X =
1 elif event.key == pygame.K_LEFT: playerStep_X = -1 # playerX += playerStep_X
if event.type == pygame.KEYUP: playerStep_X = 0 if event.type ==
pygame.KEYDOWN: if event.key == pygame.K_UP: playerStep_Y = -1 elif event.key
== pygame.K_DOWN: playerStep_Y = 1 # playerY += playerStep_Y if event.type ==
pygame.KEYUP: playerStep_Y = 0 #导入一个篮球 screen.blit(ballImg, (ballX, ballY))
ballX += ballStep if(ballX > 450 or ballX < 0): ballStep *= -1 ballY += 3 if
ballY >= 350: ballY = 0 # #导入多个篮球 # for e in balls: #
screen.blit(e.img,(e.x,e.y)) # e.x += e.step # if(e.x > 450 or e.x < 0): #
e.step *= -1 # e.y += 13 # if e.y >=299: # e.y = 0 #键盘控制上下左右移动 if playerX >=
450: playerX = 450 elif playerX <=0: playerX = 0 playerX += playerStep_X if
playerY <= 0: playerY = 0 elif playerY >=250: playerY =250 playerY +=
playerStep_Y if (ballX <= playerX-2 and ballY+10 >= playerY): bao_sound.play()
ballX = random.randint(100, 400) ballY = random.randint(20, 150)
pygame.display.update()
运行的结果图如下
图片可以根据自己的要求自行更改。游戏很简单,但是所学习的东西有很多,也算是一次不错的收获。