赞
踩
创建一个简单的小恐龙游戏需要编写代码来处理游戏的设计、图形用户界面、游戏逻辑、碰撞检测、路径寻找和人工智能等部分。
import pygame import random # 初始化pygame pygame.init() # 设置屏幕大小 screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) # 定义颜色 WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) # 设置时钟 clock = pygame.time.Clock() # 设置恐龙的属性 dinosaur_image = pygame.Surface((50, 50)) dinosaur_image.fill(GREEN) dinosaur_x = screen_width // 2 dinosaur_y = screen_height - 100 dinosaur_speed = 5 # 设置障碍物的属性 obstacle_image = pygame.Surface((50, 50)) obstacle_image.fill(RED) obstacles = [] obstacle_speed = 10 obstacle_interval = 2000 # 障碍物生成的间隔时间(毫秒) last_obstacle_time = 0 # 游戏主循环 running = True while running: # 事件处理 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 更新时间 current_time = pygame.time.get_ticks() # 生成新的障碍物 if current_time - last_obstacle_time > obstacle_interval: obstacles.append([random.randint(0, screen_width - 50), -50]) last_obstacle_time = current_time # 绘制背景 screen.fill(WHITE) # 绘制恐龙 screen.blit(dinosaur_image, (dinosaur_x, dinosaur_y)) # 绘制障碍物 for obstacle in obstacles: screen.blit(obstacle_image, (obstacle[0], obstacle[1])) # 更新障碍物位置 for i, obstacle in enumerate(obstacles): obstacle[1] += obstacle_speed if obstacle[1] > screen_height: obstacles.pop(i) # 恐龙移动 keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and dinosaur_x > 0: dinosaur_x -= dinosaur_speed if keys[pygame.K_RIGHT] and dinosaur_x < screen_width - 50: dinosaur_x += dinosaur_speed # 碰撞检测 for obstacle in obstacles: if collide(dinosaur_image, obstacle_image, dinosaur_x, dinosaur_y, obstacle[0], obstacle[1]): running = False # 更新屏幕 pygame.display.flip() # 设置每秒刷新次数 clock.tick(60) # 退出pygame pygame.quit()
这段代码创建了一个简单的游戏,其中有一个绿色的恐龙在屏幕底部移动,红色障碍物会随机生成并在屏幕顶部移动。如果恐龙与障碍物碰撞,游戏将结束。
代码中的collide
函数用于检测两个矩形物体是否碰撞:
def collide(dinosaur, obstacle, dinosaur_x, dinosaur_y, obstacle_x, obstacle_y):
dinosaur_rect = dinosaur.get_rect(topleft=(dinosaur_x, dinosaur_y))
obstacle_rect = obstacle.get_rect(topleft=(obstacle_x, obstacle_y))
return dinosaur_rect.colliderect(obstacle_rect)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。