【发布时间】:2020-01-29 00:26:04
【问题描述】:
这是一个小问题,一直在用python开发一个蛇游戏,它还没有完成,我只想知道一件事。我最初在 move_snake 函数中有代码pygame.draw.rect(SCREEN, GREEN, (x_pos[i], y_pos[i], WIDTH, HEIGHT))。代码在我画蛇的时候画得很好,但是现在我正在尝试让蛇长大,所以我把它移到了 grow_snake 函数的 for 循环中。它不会再画蛇了,但它显然仍然存在,就好像我按下键它最终会碰到边界并结束游戏一样。只是想知道为什么它不再画蛇了。谢谢你。我是编程的菜鸟,所以如果您想查看代码并向我提供有关如何改进它的提示,那将不胜感激。请记住,这是一项正在进行的工作,因此游戏中有许多明显的部分丢失了,我稍后会添加。
# Snake game
import pygame
import random
pygame.init()
pygame.display.set_caption("Snake Game and AI")
WIDTH = 24
HEIGHT = 24
SCREEN = pygame.display.set_mode((500, 500))
RED = (255, 0, 0)
BLACK = (0, 0, 0)
GREEN = (0, 128, 0)
WHITE = (255, 255, 255)
SPEED = 25
x_head = 251
y_head = 251
direction = None
apple_x = random.randrange(26, 476, 25)
apple_y = random.randrange(26, 476, 25)
length = 0
x_pos = [x_head]
y_pos = [y_head]
def grid():
for x in range(25, 500, 25):
pygame.draw.rect(SCREEN, WHITE, (x, 25, 1, 450))
for y in range(25, 500, 25):
pygame.draw.rect(SCREEN, WHITE, (25, y, 450, 1))
def press_key():
global direction
global keys
if keys[pygame.K_RIGHT] and direction != 'left':
direction = 'right'
if keys[pygame.K_LEFT] and direction != 'right':
direction = 'left'
if keys[pygame.K_UP] and direction != 'down':
direction = 'up'
if keys[pygame.K_DOWN] and direction != 'up':
direction = 'down'
def move_snake():
global x_head
global y_head
global SCREEN
global WIDTH
global HEIGHT
if direction == 'right':
x_head += SPEED
if direction == 'left':
x_head -= SPEED
if direction == 'up':
y_head -= SPEED
if direction == 'down':
y_head += SPEED
def eat_apple():
global apple_x
global apple_y
global length
if x_head == apple_x and y_head == apple_y:
apple_x = random.randrange(26, 476, 25)
apple_y = random.randrange(26, 476, 25)
if direction == 'right':
pass
if direction == 'left':
pass
if direction == 'up':
pass
if direction == 'down':
pass
length += 1
pygame.draw.rect(SCREEN, RED, (apple_x, apple_y, WIDTH, HEIGHT))
def grow_snake():
move_snake()
global x_pos
global y_pos
for i in range(length):
pygame.draw.rect(SCREEN, GREEN, (x_pos[i], y_pos[i], WIDTH, HEIGHT))
def game_over():
global is_running
if x_head < 26 or x_head > 456 or y_head < 26 or y_head > 456:
is_running = False
is_running = True
while is_running:
pygame.time.delay(150)
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_running = False
keys = pygame.key.get_pressed()
press_key()
move_snake()
SCREEN.fill(BLACK)
grid()
grow_snake()
eat_apple()
game_over()
pygame.display.update()
pygame.quit()
【问题讨论】:
-
这里是否不需要使用 global 关键字,因为上面已经声明了变量?
标签: python python-3.x pygame