python3 pygame 坦克自动移动
让坦克自动跑起来
这里需要一个坦克的图。
放到与脚本同一目录。
好,我们就让这个坦克自动跑。
下面上代码:
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
import pygame, sys
from pygame.locals import *
pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()
DISPLAY_SURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption("TankMoving")
WHITE = (255, 255, 255)
catImg = pygame.image.load("tankU.png")
catX = 10
catY = 10
direction = 'right'
while True:
DISPLAY_SURF.fill(WHITE)
if direction == "right":
catX += 5
if catX == 280:
direction = 'down'
elif direction == 'down':
catY += 5
if catY == 220:
direction = 'left'
elif direction == 'left':
catX -= 5
if catX == 10:
direction = 'up'
elif direction == 'up':
catY -= 5
if catY == 10:
direction = 'right'
DISPLAY_SURF.blit(catImg, (catX, catY))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
fpsClock.tick(FPS)
后来想了一想让它自动随机的跑,于是改了一下。
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
import pygame, sys, random
from pygame.locals import *
pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()
DISPLAY_SURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption("TankMoving")
WHITE = (255, 255, 255)
catImg = pygame.image.load("tankU.png")
'''
catX = 10
catY = 10
direction = 'right'
'''
catX = 200
catY = 140
while True:
DISPLAY_SURF.fill(WHITE)
temp = random.randrange(0, 4) # 0-3
if temp == 0:
catX += 10
if catX == 280:
catX -= 10
elif temp == 1:
catY += 10
if catY == 220:
catY -= 10
elif temp == 2:
catX -= 10
if catX == 10:
catX += 10
elif temp == 3:
catY -= 10
if catY == 10:
catY += 10
DISPLAY_SURF.blit(catImg, (catX, catY))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
fpsClock.tick(FPS)
'''
if direction == "right":
catX += 5
if catX == 280:
direction = 'down'
elif direction == 'down':
catY += 5
if catY == 220:
direction = 'left'
elif direction == 'left':
catX -= 5
if catX == 10:
direction = 'up'
elif direction == 'up':
catY -= 5
if catY == 10:
direction = 'right'
'''
最后,来个截图吧

浙公网安备 33010602011771号