|
|
当然可以!贪吃蛇游戏是一个很有趣的小游戏。下面是一个简单的贪吃蛇游戏的Python代码示例,你可以通过Python编程环境进行操作:
- import pygame
- import time
- import random
- pygame.init()
- # 设置游戏窗口大小和标题
- window_width = 800
- window_height = 600
- game_window = pygame.display.set_mode((window_width, window_height))
- pygame.display.set_caption("贪吃蛇游戏")
- # 定义颜色
- black = (0, 0, 0)
- white = (255, 255, 255)
- red = (255, 0, 0)
- green = (0, 255, 0)
- # 设置蛇和食物的大小
- snake_block = 10
- snake_speed = 15
- # 字体设置
- font_style = pygame.font.SysFont(None, 50)
- def our_snake(snake_block, snake_list):
- for x in snake_list:
- pygame.draw.rect(game_window, black, [x[0], x[1], snake_block, snake_block])
- def message(msg, color):
- msg = font_style.render(msg, True, color)
- game_window.blit(msg, [window_width // 6, window_height // 3])
- def gameLoop():
- game_over = False
- game_close = False
- # 初始化蛇的位置和长度
- x1 = window_width / 2
- y1 = window_height / 2
- x1_change = 0
- y1_change = 0
- snake_list = []
- length_of_snake = 1
- # 食物的随机位置
- foodx = round(random.randrange(0, window_width - snake_block) / 10.0) * 10.0
- foody = round(random.randrange(0, window_height - snake_block) / 10.0) * 10.0
- while not game_over:
- while game_close == True:
- game_window.fill(white)
- message("游戏结束!按Q-退出或R-重新开始", red)
- pygame.display.update()
- for event in pygame.event.get():
- if event.type == pygame.KEYDOWN:
- if event.key == pygame.K_q:
- game_over = True
- game_close = False
- if event.key == pygame.K_r:
- gameLoop()
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- game_over = True
- if event.type == pygame.KEYDOWN:
- if event.key == pygame.K_LEFT:
- x1_change = -snake_block
- y1_change = 0
- elif event.key == pygame.K_RIGHT:
- x1_change = snake_block
- y1_change = 0
- elif event.key == pygame.K_UP:
- y1_change = -snake_block
- x1_change = 0
- elif event.key == pygame.K_DOWN:
- y1_change = snake_block
- x1_change = 0
- if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
- game_close = True
- x1 += x1_change
- y1 += y1_change
- game_window.fill(white)
- pygame.draw.rect(game_window, green, [foodx, foody, snake_block, snake_block])
- snake_head = []
- snake_head.append(x1)
- snake_head.append(y1)
- snake_list.append(snake_head)
- if len(snake_list) > length_of_snake:
- del snake_list[0]
- for x in snake_list[:-1]:
- if x == snake_head:
- game_close = True
- our_snake(snake_block, snake_list)
- pygame.display.update()
- if x1 == foodx and y1 == foody:
- foodx = round(random.randrange(0, window_width - snake_block) / 10.0) * 10.0
- foody = round(random.randrange(0, window_height - snake_block) / 10.0) * 10.0
- length_of_snake += 1
- pygame.time.Clock().tick(snake_speed)
- pygame.quit()
- quit()
- gameLoop()
复制代码
这个代码会创建一个窗口来显示贪吃蛇游戏,控制贪吃蛇的移动,吃掉食物等操作。希望你能喜欢这个游戏代码!如果有其他问题,我都可以帮你解答哦。 |
|