Python 写个小游戏
时间: 2023-03-23 20:02:29 浏览: 37
可以!一般来说,Python 写小游戏最简单的方式就是使用 Pygame 库,它可以让你创建出有趣的游戏程序。如果你想更深入地学习,可以参考 Python 官方文档中的教程,也可以看一些其他的书籍或教程。
相关问题
python写个小游戏
Python是一种非常流行的编程语言,可以用来编写各种类型的应用程序,包括游戏。下面是一个简单的贪吃蛇游戏的Python代码示例:
```
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
window_width = 400
window_height = 400
game_window = pygame.display.set_mode((window_width, window_height))
# 设置游戏标题
pygame.display.set_caption('贪吃蛇游戏')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义蛇的初始位置和大小
snake_block_size = 10
snake_speed = 15
snake_list = []
snake_length = 1
snake_x = window_width / 2
snake_y = window_height / 2
# 定义食物的位置和大小
food_block_size = 10
food_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0
# 定义游戏结束的函数
def game_over():
font_style = pygame.font.SysFont(None, 50)
message = font_style.render('游戏结束', True, red)
game_window.blit(message, [window_width / 6, window_height / 3])
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
quit()
# 游戏循环
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_LEFT]:
snake_x -= snake_block_size
elif keys[pygame.K_RIGHT]:
snake_x += snake_block_size
elif keys[pygame.K_UP]:
snake_y -= snake_block_size
elif keys[pygame.K_DOWN]:
snake_y += snake_block_size
# 判断是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0
snake_length += 1
# 绘制游戏窗口
game_window.fill(white)
pygame.draw.rect(game_window, green, [food_x, food_y, food_block_size, food_block_size])
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_over()
for x in snake_list:
pygame.draw.rect(game_window, black, [x[0], x[1], snake_block_size, snake_block_size])
pygame.display.update()
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出pygame
pygame.quit()
quit()
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![apk](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)