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'
    '''

  

 

最后,來個截圖吧

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM