diff --git a/main.py b/main.py index 4c0c135f61696bcf42c375ca5ab62aa5b105afc8..176a93f726ddce7ca197b3ee6f19e8057a07a08a 100644 --- a/main.py +++ b/main.py @@ -1 +1,118 @@ -print('欢迎来到 InsCode') \ No newline at end of file +import pygame +import random +import sys + +# 初始化Pygame +pygame.init() + +# 游戏窗口设置 +WIDTH, HEIGHT = 800, 400 +WIN = pygame.display.set_mode((WIDTH, HEIGHT)) +pygame.display.set_caption("跑酷小恐龙") + +# 颜色定义 +WHITE = (255, 255, 255) +BLACK = (0, 0, 0) + +# 游戏元素类 +class Dinosaur: + def __init__(self): + self.x = 50 + self.y = 300 + self.jump = False + self.jump_speed = 10 + self.gravity = 0.5 + self.rect = pygame.Rect(self.x, self.y, 40, 60) + + def move(self): + if self.jump: + self.jump_speed -= self.gravity + self.y -= self.jump_speed + if self.y >= 300: + self.y = 300 + self.jump = False + self.jump_speed = 10 + self.rect.y = self.y + +class Obstacle: + def __init__(self): + self.x = WIDTH + self.y = 310 + self.width = 30 + self.height = 40 + self.speed = 7 + self.rect = pygame.Rect(self.x, self.y, self.width, self.height) + + def update(self): + self.x -= self.speed + self.rect.x = self.x + if self.x < -self.width: + return True + return False + +# 游戏主循环 +def main(): + clock = pygame.time.Clock() + score = 0 + font = pygame.font.SysFont(None, 36) + + dino = Dinosaur() + obstacles = [] + spawn_timer = 0 + + running = True + game_over = False + + while running: + WIN.fill(WHITE) + + for event in pygame.event.get(): + if event.type == pygame.QUIT: + running = False + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_SPACE and not dino.jump and not game_over: + dino.jump = True + if event.key == pygame.K_r and game_over: + main() + + if not game_over: + # 生成障碍物 + spawn_timer += 1 + if spawn_timer > random.randint(50, 100): + obstacles.append(Obstacle()) + spawn_timer = 0 + + # 更新障碍物 + for obs in obstacles[:]: + if obs.update(): + obstacles.remove(obs) + score += 1 + + # 碰撞检测 + dino.move() + for obs in obstacles: + if dino.rect.colliderect(obs.rect): + game_over = True + + # 绘制游戏元素 + pygame.draw.rect(WIN, BLACK, dino.rect) # 恐龙 + for obs in obstacles: + pygame.draw.rect(WIN, (255, 0, 0), obs.rect) # 障碍物 + + # 显示分数 + score_text = font.render(f"Score: {score}", True, BLACK) + WIN.blit(score_text, (10, 10)) + + else: + # 游戏结束画面 + game_over_text = font.render("Game Over! Press R to restart", True, BLACK) + WIN.blit(game_over_text, (WIDTH//2-150, HEIGHT//2)) + + pygame.display.update() + clock.tick(60) + + pygame.quit() + sys.exit() + +if __name__ == "__main__": + main() \ No newline at end of file