python小恐龙代码
时间: 2023-05-30 09:03:40 浏览: 333
以下是Python小恐龙游戏的代码:
```python
import pygame
import random
pygame.init()
# 游戏窗口大小
win_width = 800
win_height = 300
win = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("小恐龙")
# 加载图片
dino_img = pygame.image.load("dino.png")
cactus_img = pygame.image.load("cactus.png")
# 小恐龙属性
dino_x = 50
dino_y = 220
dino_speed = 7
dino_jump = False
dino_jump_height = 80
dino_jump_count = dino_jump_height
dino_rect = dino_img.get_rect()
# 仙人掌属性
cactus_x = win_width
cactus_y = 230
cactus_speed = 10
cactus_rect = cactus_img.get_rect()
# 分数
score = 0
font = pygame.font.SysFont(None, 30)
# 游戏循环
run = True
while run:
# 事件监听
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# 背景颜色
win.fill((255, 255, 255))
# 小恐龙跳跃
if dino_jump:
if dino_jump_count >= -dino_jump_height:
dino_y -= dino_jump_count / abs(dino_jump_count) * 5
dino_jump_count -= 1
else:
dino_jump = False
dino_jump_count = dino_jump_height
# 仙人掌移动
cactus_x -= cactus_speed
if cactus_x < -cactus_rect.width:
cactus_x = win_width
score += 1
cactus_speed += 1
# 碰撞检测
if dino_rect.colliderect(cactus_rect):
run = False
# 绘制小恐龙和仙人掌
win.blit(dino_img, (dino_x, dino_y))
win.blit(cactus_img, (cactus_x, cactus_y))
# 绘制分数
score_text = font.render("Score: " + str(score), True, (0, 0, 0))
win.blit(score_text, (win_width - score_text.get_width() - 10, 10))
# 更新窗口
pygame.display.update()
pygame.quit()
```
注意:此代码仅适用于学习目的,实际游戏开发中还需要添加更多内容,如游戏开始界面、游戏结束界面、音效等。
阅读全文