用python写一个超级玛丽小游戏
时间: 2023-12-07 11:37:14 浏览: 167
为了用 Python 写一个超级玛丽小游戏,我们需要使用 pygame 库来创建游戏窗口并加载图片。以下是实现这个小游戏的一些步骤:
1. 导入 pygame 库并初始化
```python
import pygame
pygame.init()
```
2. 设置游戏窗口大小和标题
```python
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("超级玛丽")
```
3. 加载背景图片和角色图片
```python
background_image = pygame.image.load("background.png").convert()
player_image = pygame.image.load("player.png").convert_alpha()
```
4. 在游戏窗口中显示背景图片和角色图片
```python
screen.blit(background_image, (0, 0))
screen.blit(player_image, (x, y))
pygame.display.update()
```
5. 处理用户输入事件
```python
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
```
6. 让角色移动
```python
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= speed
if keys[pygame.K_RIGHT]:
x += speed
if keys[pygame.K_UP]:
y -= speed
if keys[pygame.K_DOWN]:
y += speed
```
7. 添加碰撞检测
```python
player_rect = player_image.get_rect()
player_rect.x = x
player_rect.y = y
if player_rect.colliderect(enemy_rect):
print("Game Over")
```
完整代码如下所示:
```python
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("超级玛丽")
background_image = pygame.image.load("background.png").convert()
player_image = pygame.image.load("player.png").convert_alpha()
x = 0
y = 0
speed = 5
while True:
screen.blit(background_image, (0, 0))
screen.blit(player_image, (x, y))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= speed
if keys[pygame.K_RIGHT]:
x += speed
if keys[pygame.K_UP]:
y -= speed
if keys[pygame.K_DOWN]:
y += speed
player_rect = player_image.get_rect()
player_rect.x = x
player_rect.y = y
enemy_rect = enemy_image.get_rect()
enemy_rect.x = enemy_x
enemy_rect.y = enemy_y
if player_rect.colliderect(enemy_rect):
print("Game Over")
```
阅读全文