初学者写一个简单的python图形化游戏
时间: 2023-07-13 19:35:29 浏览: 99
当然可以,以下是一个初学者写的简单的Python图形化游戏示例:
```
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("打气球游戏")
# 加载图片
balloon_image = pygame.image.load("balloon.png")
# 设置字体
font = pygame.font.SysFont("Arial", 30)
# 初始化气球
balloons = []
for i in range(5):
balloon_x = random.randint(0, screen_width - balloon_image.get_width())
balloon_y = random.randint(0, screen_height - balloon_image.get_height())
balloons.append((balloon_x, balloon_y))
# 初始化分数
score = 0
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = event.pos
for balloon in balloons:
if mouse_x >= balloon[0] and mouse_x <= balloon[0] + balloon_image.get_width() and mouse_y >= balloon[1] and mouse_y <= balloon[1] + balloon_image.get_height():
balloons.remove(balloon)
score += 1
break
# 更新气球
for i in range(len(balloons)):
balloon_x, balloon_y = balloons[i]
balloons[i] = (balloon_x, balloon_y - 5)
if balloon_y <= 0:
balloons[i] = (random.randint(0, screen_width - balloon_image.get_width()), screen_height)
# 绘制屏幕
screen.fill((255, 255, 255))
for balloon in balloons:
screen.blit(balloon_image, (balloon[0], balloon[1]))
score_text = font.render("分数:%d" % score, True, (0, 0, 0))
screen.blit(score_text, (10, 10))
# 更新屏幕
pygame.display.update()
# 退出Pygame
pygame.quit()
```
这是一个打气球的小游戏,玩家需要点击屏幕上的气球,每个气球被点击后会消失并增加分数。这个小游戏基于Pygame图形库和Python的基础语法实现,适合初学者练习图形化编程和游戏开发。
阅读全文