改造实例代码2.1,绘制一条彩色小蟒蛇。
时间: 2024-10-21 17:07:07 浏览: 26
要创建一条彩色的小蟒蛇并用Python进行绘图,我们可以使用`pygame`库来实现游戏开发中的基本图形操作。首先,你需要确保已经安装了`pygame`,如果没有,可以通过pip进行安装:
```bash
pip install pygame
```
接下来,这是一个简单的示例代码,用于绘制一条彩色小蟒蛇(蛇的身体由彩色方块组成):
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小
window_size = (800, 600)
screen = pygame.display.set_mode(window_size)
pygame.display.set_caption("Colorful Snake")
# 定义颜色
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0)] # 彩色列表
# 定义蛇的基本参数
snake_length = 10
snake_pos = [100, 50]
snake_body = [[snake_pos[0] + i * 20, snake_pos[1] + i * 20] for i in range(snake_length)]
direction = "right"
# 主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# 移动蛇
keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and direction != "down":
direction = "up"
elif keys[pygame.K_DOWN] and direction != "up":
direction = "down"
elif keys[pygame.K_LEFT] and direction != "right":
direction = "left"
elif keys[pygame.K_RIGHT] and direction != "left":
direction = "right"
new_head = list(snake_body[0])
if direction == "up":
new_head[1] -= 20
elif direction == "down":
new_head[1] += 20
elif direction == "left":
new_head[0] -= 20
else: # right
new_head[0] += 20
snake_body.insert(0, new_head)
# 边界检查
if new_head[0] < 0 or new_head[0] >= window_size[0]:
print("Game Over! Hit the wall.")
break
if new_head[1] < 0 or new_head[1] >= window_size[1]:
print("Game Over! Hit the wall.")
break
for segment in snake_body[1:]:
if new_head == segment:
print("Game Over! You hit your tail.")
break
# 绘制蛇和背景
screen.fill((0, 0, 0))
for i, segment in enumerate(snake_body):
color = colors[i % len(colors)] # 循环使用颜色
pygame.draw.rect(screen, color, pygame.Rect(segment[0], segment[1], 20, 20))
# 更新屏幕
pygame.display.update()
```
这个代码创建了一个窗口,蛇的每个身体部分都是一个小正方形,用不同颜色表示。当蛇碰到边界或自己的尾巴时,游戏结束。
阅读全文