编写一个堆积木的游戏代码
以下是一个简单的堆积木游戏代码示例:
import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏窗口尺寸
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Stacking Blocks Game")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 设置堆积木的属性
block_width = 50
block_height = 20
block_x = screen_width // 2 - block_width // 2
block_y = screen_height - block_height
block_speed = 5
# 设置堆积木的初始位置、颜色和速度
block = pygame.Rect(block_x, block_y, block_width, block_height)
block_color = random.choice([red, green])
block_speed_x = 0
# 设置堆积木堆叠的位置列表
stacked_blocks = []
# 游戏循环
running = True
while running:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
block_speed_x = -block_speed
elif event.key == pygame.K_RIGHT:
block_speed_x = block_speed
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
block_speed_x = 0
# 更新堆积木的位置
block.x += block_speed_x
# 检测堆积木是否超出屏幕边界
if block.left < 0:
block.left = 0
elif block.right > screen_width:
block.right = screen_width
# 绘制背景
screen.fill(white)
# 绘制堆积木
pygame.draw.rect(screen, block_color, block)
# 绘制已堆叠的积木
for stacked_block in stacked_blocks:
pygame.draw.rect(screen, stacked_block[1], stacked_block[0])
# 检测堆积木是否与已堆叠的积木碰撞
for stacked_block in stacked_blocks:
if block.colliderect(stacked_block[0]):
# 游戏结束
running = False
# 检测堆积木是否堆叠成功
if block.bottom < screen_height and not any(block.colliderect(stacked_block[0]) for stacked_block in stacked_blocks):
# 堆叠成功
stacked_blocks.append((pygame.Rect(block.x, block.y, block.width, block.height), block_color))
# 生成新的堆积木
block.y -= block_height
block_color = random.choice([red, green])
# 更新屏幕显示
pygame.display.flip()
# 游戏结束
pygame.quit()
此代码使用pygame库编写了一个简单的堆积木游戏。游戏窗口大小为800x600像素,玩家通过按左右箭头键控制堆积木的移动。游戏的目标是将堆积木成功堆叠在屏幕上方的积木上,如果堆积木与已堆叠的积木碰撞,游戏结束。
注意:此代码只是一个简单的示例,可能需要根据具体需求进行修改和扩展
原文地址: https://www.cveoy.top/t/topic/hJsj 著作权归作者所有。请勿转载和采集!