python结合AI做一个简单的小游戏

点击查看代码
import pygame
import random
import sys

# 初始化pygame
pygame.init()

# 游戏窗口设置
WIDTH, HEIGHT = 800, 400
GROUND_HEIGHT = 80  # 地面高度
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("恐龙躲避游戏")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (100, 180, 100)
GROUND_COLOR = (240, 240, 240)
DINO_COLOR = (100, 100, 100)

# 解决字体问题
def get_font(size):
    try:
        return pygame.font.SysFont('simhei', size)  # 中文黑体
    except:
        try:
            return pygame.font.SysFont('Arial', size)
        except:
            return pygame.font.Font(None, size)

# 游戏参数
clock = pygame.time.Clock()
FPS = 60
GRAVITY = 1
JUMP_STRENGTH = 15  # 跳跃力度
GAME_SPEED = 8
score = 0
font = get_font(36)
game_started = False
game_over = False

# 恐龙图形
def draw_dinosaur(surface, x, y, is_jumping):
    # 身体
    body_height = 60
    pygame.draw.rect(surface, DINO_COLOR, (x, y, 50, body_height))
    
    # 头
    pygame.draw.rect(surface, DINO_COLOR, (x+40, y-20, 30, 30))
    
    # 眼睛
    eye_y = y-10 if not is_jumping else y-15
    pygame.draw.circle(surface, WHITE, (x+60, eye_y), 5)
    pygame.draw.circle(surface, BLACK, (x+62, eye_y), 2)
    
    # 腿(添加动画效果)
    leg_height = 25
    leg_pos = 0 if pygame.time.get_ticks() % 300 < 150 else 5
    pygame.draw.rect(surface, DINO_COLOR, (x+10, y+body_height-10, 15, leg_height))
    pygame.draw.rect(surface, DINO_COLOR, (x+25, y+body_height-10+leg_pos, 15, leg_height))
    
    # 尾巴
    pygame.draw.polygon(surface, DINO_COLOR, 
                       [(x-15, y+30), (x, y+40), (x, y+20)])

# 仙人掌图形
def draw_cactus(surface, x, height):
    ground_level = HEIGHT - GROUND_HEIGHT
    cactus_y = ground_level - height
    # 主茎
    pygame.draw.rect(surface, GREEN, (x, cactus_y, 30, height))
    
    # 侧枝
    if height > 50:
        pygame.draw.rect(surface, GREEN, (x-15, cactus_y+30, 20, 15))
        pygame.draw.rect(surface, GREEN, (x+25, cactus_y+40, 15, 20))
    
    # 刺
    for i in range(3):
        pygame.draw.line(surface, BLACK, (x+5+i*8, cactus_y+5), (x+5+i*8, cactus_y+15), 2)

# 恐龙类(修复跳跃问题)
class Dinosaur:
    def __init__(self):
        self.reset()
    
    def reset(self):
        self.x = 50
        self.base_y = HEIGHT - GROUND_HEIGHT - 60  # 基础Y位置(站立时)
        self.y = self.base_y
        self.width = 50
        self.height = 60
        self.jumping = False
        self.jump_vel = JUMP_STRENGTH
        self.vel_y = 0
    
    def jump(self):
        # 只有在地面上才能跳跃
        if not self.jumping and abs(self.y - self.base_y) < 1:
            self.jumping = True
            self.vel_y = -self.jump_vel
    
    def update(self):
        if self.jumping:
            self.y += self.vel_y
            self.vel_y += GRAVITY
            
            # 落地检测
            if self.y >= self.base_y:
                self.y = self.base_y
                self.jumping = False
                self.vel_y = 0
    
    def get_mask(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

# 障碍物类
class Obstacle:
    def __init__(self):
        self.width = 30
        self.height = random.choice([40, 60, 80])
        self.x = WIDTH
        self.y = HEIGHT - GROUND_HEIGHT - self.height
        self.passed = False
    
    def update(self):
        self.x -= GAME_SPEED
    
    def draw(self):
        draw_cactus(screen, self.x, self.height)
    
    def collide(self, dinosaur):
        return self.get_mask().colliderect(dinosaur.get_mask())
    
    def get_mask(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

def main():
    global GAME_SPEED, score, game_started, game_over, font
    
    dinosaur = Dinosaur()
    obstacles = []
    last_obstacle_time = pygame.time.get_ticks()
    
    running = True
    while running:
        # 处理事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            if event.type == pygame.KEYDOWN:
                if not game_over and not game_started and event.key == pygame.K_SPACE:
                    game_started = True
                
                if game_started and not game_over:
                    if event.key == pygame.K_SPACE:
                        dinosaur.jump()  # 确保在游戏进行中按空格键跳跃
                
                if event.key == pygame.K_SPACE and game_over:
                    # 重置游戏
                    dinosaur.reset()
                    obstacles = []
                    score = 0
                    GAME_SPEED = 8
                    game_started = False
                    game_over = False
                    last_obstacle_time = pygame.time.get_ticks()
        
        # 游戏逻辑更新
        screen.fill(GROUND_COLOR)
        pygame.draw.rect(screen, (220, 220, 220), (0, HEIGHT-GROUND_HEIGHT, WIDTH, GROUND_HEIGHT))  # 地面
        
        if not game_over:
            dinosaur.update()
            
            if game_started:
                # 生成障碍物
                current_time = pygame.time.get_ticks()
                if current_time - last_obstacle_time > max(500, 1500 - score * 5):
                    obstacles.append(Obstacle())
                    last_obstacle_time = current_time
                
                # 更新障碍物
                for obstacle in obstacles[:]:
                    obstacle.update()
                    
                    if obstacle.collide(dinosaur):
                        game_over = True
                    
                    if obstacle.x + obstacle.width < 0:
                        obstacles.remove(obstacle)
                    
                    if not obstacle.passed and obstacle.x + obstacle.width < dinosaur.x:
                        obstacle.passed = True
                        score += 1
                
                GAME_SPEED = 8 + score // 10
        
        # 绘制
        draw_dinosaur(screen, dinosaur.x, dinosaur.y, dinosaur.jumping)
        if game_started:
            for obstacle in obstacles:
                obstacle.draw()
        
        # 显示文字
        try:
            score_text = font.render(f"分数: {score}", True, BLACK)
            screen.blit(score_text, (10, 10))
            
            if not game_started and not game_over:
                start_text = font.render("按空格键开始游戏", True, BLACK)
                hint_text = font.render("游戏中: 空格键跳跃", True, BLACK)
                screen.blit(start_text, (WIDTH//2 - start_text.get_width()//2, HEIGHT//2 - 50))
                screen.blit(hint_text, (WIDTH//2 - hint_text.get_width()//2, HEIGHT//2 + 10))
            
            if game_over:
                game_over_text = font.render("游戏结束!", True, BLACK)
                restart_text = font.render("按空格键重新开始", True, BLACK)
                final_score_text = font.render(f"最终分数: {score}", True, BLACK)
                
                screen.blit(game_over_text, (WIDTH//2 - game_over_text.get_width()//2, HEIGHT//2 - 60))
                screen.blit(final_score_text, (WIDTH//2 - final_score_text.get_width()//2, HEIGHT//2 - 20))
                screen.blit(restart_text, (WIDTH//2 - restart_text.get_width()//2, HEIGHT//2 + 20))
        except:
            font = get_font(36)
        
        pygame.display.flip()
        clock.tick(FPS)
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()
posted @ 2025-06-21 15:53  Lay“  阅读(26)  评论(0)    收藏  举报