python小游戏2——打地鼠”游戏
代码
import pygame
import random
初始化Pygame
pygame.init()
屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("打地鼠游戏")
颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
地鼠类
class Mole:
def init(self):
self.x = random.randint(50, screen_width - 50)
self.y = random.randint(50, 150)
self.speed = random.randint(1, 3)
self.radius = 20
def draw(self, screen):
pygame.draw.circle(screen, GREEN, (self.x, self.y), self.radius)
def move(self):
self.x += self.speed
if self.x <= 50 or self.x >= screen_width - 50:
self.speed = -self.speed
锤子类
class Hammer:
def init(self, x, y):
self.x = x
self.y = y
self.rect = pygame.Rect(x, y, 50, 100)
def draw(self, screen):
pygame.draw.rect(screen, BLACK, self.rect)
def move_up(self):
self.y -= 10
if self.y < 0:
self.y = 0
def move_down(self):
self.y += 10
if self.y > screen_height - 100:
self.y = screen_height - 100
游戏主循环
def main():
running = True
clock = pygame.time.Clock()
mole = Mole()
hammer = Hammer(screen_width // 2 - 25, screen_height - 100)
score = 0
font = pygame.font.Font(None, 36)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # 左键点击
mouse_x, mouse_y = pygame.mouse.get_pos()
if hammer.rect.collidepoint(mouse_x, mouse_y):
if (mole.x - mole.radius < mouse_x < mole.x + mole.radius and
mole.y - mole.radius < mouse_y < mole.y + mole.radius):
score += 1
mole = Mole() # 重新生成地鼠
填充背景颜色
screen.fill(WHITE)
更新地鼠位置
mole.move()
mole.draw(screen)
更新锤子位置
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
hammer.move_up()
if keys[pygame.K_DOWN]:
hammer.move_down()
hammer.draw(screen)
显示分数
score_text = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_text, (10, 10))
刷新屏幕
pygame.display.flip()
控制帧率
clock.tick(30)
pygame.quit()
if name == "main":
main()
知识点总结
- Pygame库的使用 :
pygame.init():初始化Pygame库,使其准备好进行游戏开发。pygame.display.set_mode():设置游戏的显示窗口大小,并返回一个Surface对象,用于绘制游戏内容。pygame.display.flip():更新整个屏幕的内容,显示新的游戏画面。pygame.quit():退出Pygame,释放资源。- 游戏对象类 :
- Mole(地鼠)类 :
__init__:初始化地鼠的位置、速度和半径。draw:在屏幕上绘制地鼠。move:更新地鼠的位置,使其在地平线上水平移动。- Hammer(锤子)类 :
__init__:初始化锤子的位置和矩形区域。draw:在屏幕上绘制锤子。move_up和move_down:更新锤子的垂直位置,通过键盘上下箭头键控制。- 事件处理 :
pygame.event.get():获取事件队列中的所有事件。event.type == pygame.QUIT:检测关闭窗口的事件。event.type == pygame.MOUSEBUTTONDOWN:检测鼠标左键点击事件。pygame.mouse.get_pos():获取鼠标的当前位置。pygame.Rect.collidepoint():检测点是否在矩形内,用于判断锤子是否击中地鼠。- 游戏逻辑 :
- 使用
while running:循环来维持游戏的主循环。pygame.key.get_pressed():获取当前按下的键盘按键。- 使用
if语句和pygame.K_UP、pygame.K_DOWN等常量来检测键盘按键的按下。- 更新游戏对象的位置和状态。
- 检测并处理游戏内的交互(如击中地鼠)。
- 图形绘制 :
- 使用
pygame.draw.circle()绘制圆形(地鼠)。- 使用
pygame.draw.rect()绘制矩形(锤子)。- 使用
pygame.font.Font()和render()方法绘制文本(分数)。- 帧率控制 :
pygame.time.Clock():创建一个时钟对象,用于控制游戏的帧率。clock.tick(30):将游戏的帧率限制为每秒30帧。
