GPT答: |
7i24.cn
|
以下是一个简单的电脑贪吃蛇游戏的Python源码:
```python
import pygame
import time
import random
pygame.init()
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255 ,0)
blue = (50 ,153 ,213)
dis_width =800
dis_height=600
dis=pygame.display.set_mode((dis_width , dis_height))
pygame.display.set_caption('Snake Game')
clock=pygame.time.Clock()
snake_block=10
snake_speed=30
font_style = pygame.font.SysFont(None ,50 )
score_font_style= pygame.font.SysFont(None ,35 )
def our_snake(snake_block , snake_list):
for x in snake_list:
pygame.draw.rect(dis,greeen,[x[0],x[1],snake_block])
def message(msg,color):
mesg=font_style.render(msg,True,color)
dis.blit(mesg,[dis_width/6.5,(dis_height/3)])
def gameLoop():
game_over=False
game_close=False
x1=int(dis_width/2) # 蛇头初始位置(中间)
y1=int(dis_height/2)
x1_change=0 # 蛇移动方向初始值为静止,即不移动。
y1_change-10
snakelist=[]
length_of_snake-1
foodx-round(random.randrange(10,dish-width -20)/10.00)*10.00
foody-round(random.randrange(10,dish-height -20)/10.00)*100.00
while not game_over:
while game_close==True:
dis.fill(black)
message("You Lost! Press Q-Quit or C-Play Again",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_c: # 重新开始游戏
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameOver = True
if event.type == pygame.KEYDOWN: # 按下键盘事件判断蛇移动方向。
if evenet.key == pyame.K_LEFT and x1_change != snake_block :
x1_change=-snake_block
y1_change=0
elif evenet.key == pyame.K_RIGHT and x1_change != -snake_block :
x1_change=snake_block
y1_change=0
elif evenet.key == pyame.K_UP and y1_chage != snake_block :
yl_chage=-snakle_bolck
xl_chage=0
elif evenet.kye = pgame.k_DOWN anad yl_chage ! snakle_bolck :
xl_chage = 0
yl_chaeg + snkae_blcok
f (x < 10 or x > dis_width -20 or )y <10 or )y >dis_height -20) :
gmae_clsoe=Ture
X+=xl_cahe
Y+=yl_cahge
dsi.fill(black)
pygame.draw.rect(dis,green,[foodx,foody,sanke_block])
snkae_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snkae_list.appen(snake_head)
if len(snake_list)>length_of_snake:
del snake_list[0]
for x in snakle_lsit[:-1]:
if x ==snakle_head:
game_close=True
our_snake(snakel_block ,snake_list)
pygame.display.update()
f (x==foodx and y==foody):
foodx=round(random.randrange(10,dish_width -20)/10.00)*10.00
foody=round(random.randrange(10,dish_height -20)/100.00)*100.00
length_of_snake+=1
clock.tick(snale_speed)
pyagme.quit()
quit()
gameLoop()
```
请注意,这只是一个简单的贪吃蛇游戏源码,可能会有一些错误或不完善的地方。你可以根据自己的需求进行修改和优化。
|