pygame坦克大战

很高兴为你提供帮助。以下是一个简单的坦克大战游戏。

1. 导入模块和初始化

import pygame
import random

WIDTH = 800
HEIGHT = 600

pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Tank Game")

clock = pygame.time.Clock()

2. 定义颜色和音效

# define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# 加载音效
fire_sound = pygame.mixer.Sound("assets/sounds/fire.wav")
explosion_sound = pygame.mixer.Sound("assets/sounds/explosion.wav")

3. 定义类

# 坦克类
class Tank(pygame.sprite.Sprite):
    def __init__(self, x, y, color, direction, speed=5):
        super().__init__()
        self.image = pygame.Surface((30, 30))
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.direction = direction
        self.speed = speed

    def move(self):
        if self.direction == "up":
            self.rect.y -= self.speed
        elif self.direction == "down":
            self.rect.y += self.speed
        elif self.direction == "left":
            self.rect.x -= self.speed
        elif self.direction == "right":
            self.rect.x += self.speed

    def fire(self):
        fire_sound.play()
        bullet = Bullet(self.rect.centerx, self.rect.centery, self.direction)
        all_sprites.add(bullet)
        bullets.add(bullet)

# 子弹类
class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y, direction, speed=10):
        super().__init__()
        self.image = pygame.Surface((10, 10))
        self.image.fill(WHITE)
        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.centery = y
        self.direction = direction
        self.speed = speed

    def update(self):
        if self.direction == "up":
            self.rect.y -= self.speed
        elif self.direction == "down":
            self.rect.y += self.speed
        elif self.direction == "left":
            self.rect.x -= self.speed
        elif self.direction == "right":
            self.rect.x += self.speed

        if self.rect.right < 0 or self.rect.left > WIDTH or self.rect.bottom < 0 or self.rect.top > HEIGHT:
            self.kill()

#障碍物类 暂且没用 等后续研究琢磨加上
class Wall(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height):
        super().__init__()
        self.image = pygame.Surface((width, height))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

4. 创建对象和添加到精灵组

# create objects
player_tank = Tank(100, 100, BLUE, "up")
enemy_tank1 = Tank(500, 100, RED, "down")
enemy_tank2 = Tank(300, 400, RED, "left")
enemy_tank3 = Tank(700, 400, RED, "right")

all_tanks = pygame.sprite.Group()
all_tanks.add(player_tank)
all_tanks.add(enemy_tank1)
all_tanks.add(enemy_tank2)
all_tanks.add(enemy_tank3)

bullets = pygame.sprite.Group()

wall1 = Wall(200, 200, 100, 20)
wall2 = Wall(500, 300, 20, 100)

all_walls = pygame.sprite.Group()
all_walls.add(wall1)
all_walls.add(wall2)

all_sprites = pygame.sprite.Group()
all_sprites.add(player_tank)
all_sprites.add(enemy_tank1)
all_sprites.add(enemy_tank2)
all_sprites.add(enemy_tank3)
all_sprites.add(wall1)
all_sprites.add(wall2)

5. 游戏循环

running = True
while running:
    clock.tick(30)
    
    # 按键事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                player_tank.fire()
            elif event.key == pygame.K_LEFT:
                player_tank.direction = "left"
            elif event.key == pygame.K_RIGHT:
                player_tank.direction = "right"
            elif event.key == pygame.K_UP:
                player_tank.direction = "up"
            elif event.key == pygame.K_DOWN:
                player_tank.direction = "down"

    # update
    all_sprites.update()

    # check for collisions
    hits = pygame.sprite.groupcollide(bullets, all_tanks, True, False)
    for hit in hits:
        explosion_sound.play()
        hit_list = hits[hit]
        for tank in hit_list:
            tank.kill()

    # draw
    screen.fill(BLACK)
    all_sprites.draw(screen)

    # update display
    pygame.display.flip()

pygame.quit()

完整代码:

import pygame
import random

WIDTH = 800
HEIGHT = 600

pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("坦克大战")

clock = pygame.time.Clock()

# define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

directions = ["up", "down", "left", "right"]

# load sound
fire_sound = pygame.mixer.Sound("assets/sounds/fire.mp3")
explosion_sound = pygame.mixer.Sound("assets/sounds/explosion.mp3")


# define classes
class Tank(pygame.sprite.Sprite):
    def __init__(self, x, y, color, direction, speed=5, isOther=True):
        super().__init__()
        self.image = pygame.Surface((30, 30))
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.direction = direction
        self.speed = speed
        self.num = 0
        self.time = pygame.time.get_ticks()
        self.isOther=isOther # 默认是敌方

    def move(self):
        self.num += 1
        if self.direction == "up":
            self.rect.y -= self.speed
            if self.rect.y <= 0:
                self.direction = "down"
                self.rect.y = 0
                self.num = 0
        elif self.direction == "down":
            self.rect.y += self.speed
            if self.rect.y >= HEIGHT:
                self.direction = "up"
                self.rect.y = HEIGHT
                self.num = 0
        elif self.direction == "left":
            self.rect.x -= self.speed
            if self.rect.x <= 0:
                self.direction = "right"
                self.rect.x = 0
                self.num = 0
        elif self.direction == "right":
            self.rect.x += self.speed
            if self.rect.x >= WIDTH:
                self.direction = "left"
                self.rect.x = WIDTH
                self.num = 0

    def fire(self):
        fire_sound.play()
        bullet = Bullet(self.rect.centerx, self.rect.centery, self.direction)
        all_sprites.add(bullet)
        if self.isOther:
            bulletsOther.add(bullet)
        else:
            bullets.add(bullet)


# 子弹
class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y, direction, speed=10):
        super().__init__()
        self.image = pygame.Surface((10, 10))
        self.image.fill(WHITE)
        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.centery = y
        self.direction = direction
        self.speed = speed

    def update(self):
        if self.direction == "up":
            self.rect.y -= self.speed
        elif self.direction == "down":
            self.rect.y += self.speed
        elif self.direction == "left":
            self.rect.x -= self.speed
        elif self.direction == "right":
            self.rect.x += self.speed

        # 超出界限消失
        if self.rect.right < 0 or self.rect.left > WIDTH or self.rect.bottom < 0 or self.rect.top > HEIGHT:
            self.kill()


# 墙
class Wall(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height):
        super().__init__()
        self.image = pygame.Surface((width, height))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y


#游戏结束
def game_over():
    global score
    print("游戏结束")
    # 绘制提示语言
    font = pygame.font.Font("assets/fonts/simsun.ttc", 24)
    text = font.render("游戏结束您的得分是{},重新开始请按空格键".format(score), True, WHITE)
    screen.blit(text, (10, HEIGHT // 2 - 12))
    pygame.display.update()
    flag = True
    while flag:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                flag = False
                break
    reset_game()


# 重置游戏
def reset_game():
    global score, running, player_tank
    # 重置分数
    score = 0
    player_tank = Tank(100, 100, BLUE, "up", speed=10, isOther=False)
    self_tanks.add(player_tank)
    running = True  # 接着继续
    all_sprites.add(player_tank)


# 创建对象
player_tank = Tank(100, 100, BLUE, "up", speed=10, isOther=False)
enemy_tank1 = Tank(500, 100, RED, "down")
enemy_tank2 = Tank(300, 400, RED, "left")
enemy_tank3 = Tank(700, 400, RED, "right")

self_tanks = pygame.sprite.Group()
self_tanks.add(player_tank)

all_tanks = pygame.sprite.Group()
all_tanks.add(enemy_tank1)
all_tanks.add(enemy_tank2)
all_tanks.add(enemy_tank3)

all_tankOther = list()
all_tankOther.append(enemy_tank1)
all_tankOther.append(enemy_tank2)
all_tankOther.append(enemy_tank3)


bullets = pygame.sprite.Group()  # 我方发射的子弹
bulletsOther = pygame.sprite.Group()  # 敌方发射的子弹
wall1 = Wall(200, 200, 100, 20)
wall2 = Wall(500, 300, 20, 100)

all_walls = pygame.sprite.Group()
all_walls.add(wall1)
all_walls.add(wall2)

all_sprites = pygame.sprite.Group()
all_sprites.add(player_tank)
all_sprites.add(enemy_tank1)
all_sprites.add(enemy_tank2)
all_sprites.add(enemy_tank3)
all_sprites.add(wall1)
all_sprites.add(wall2)
pygame.key.set_repeat(100)
# set_repeat方法可以控制KEYDOWN事件的频率。
# 比如持续按下某个按键时,想要让KEYDOWN事件每过一段时间就触发一次,
# 就可以用set_repeat方法。

score = 0

running = True
while running:
    clock.tick(30)

    # 按键事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                player_tank.fire()
            elif event.key == pygame.K_LEFT or event.key == pygame.K_a:
                player_tank.direction = "left"
                player_tank.move()
            elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                player_tank.direction = "right"
                player_tank.move()
            elif event.key == pygame.K_UP or event.key == pygame.K_w:
                player_tank.direction = "up"
                player_tank.move()
            elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
                player_tank.direction = "down"
                player_tank.move()

    # update
    all_sprites.update()
    # 检测我方是否被敌方子弹射到
    hits_self = pygame.sprite.groupcollide(bulletsOther, self_tanks, True, False)
    for hit in hits_self:
        explosion_sound.play()
        hit_list = hits_self[hit]
        print(hit_list)
        for tank in hit_list:
            # 我方被击倒 游戏结束
            tank.kill()
            running = False
            game_over()


    # 检测敌方是否被我方射到
    hits = pygame.sprite.groupcollide(bullets, all_tanks, True, False)
    for hit in hits:
        explosion_sound.play()
        hit_list = hits[hit]
        print(hit_list)
        for tank in hit_list:
            score += 100  # 干掉一个得一百分
            all_tankOther.remove(tank)
            tank.kill()  # 干掉一个 立马随机位置生成一个
            enemy_tankNew = Tank(random.randint(0, WIDTH-20),
                                 random.randint(0, HEIGHT-20), RED,
                                 random.choice(directions))
            all_tanks.add(enemy_tankNew)
            all_sprites.add(enemy_tankNew)
            all_tankOther.append(enemy_tankNew)
    # 敌方每个坦克定时1秒发射一颗子弹
    now = pygame.time.get_ticks()
    for tank in all_tankOther:
        if now > tank.time+1000*1:
            tank.time = now
            tank.fire()
        tank.move()
        if tank.num > 15:
            tank.num = 0
            tank.direction = random.choice(directions)  # 四步一换方向

    # draw
    screen.fill(BLACK)
    all_sprites.draw(screen)

    # update display
    pygame.display.flip()

pygame.quit()

游戏截图

蓝色为我方坦克 红色为敌方坦克 白色为子弹
pygame坦克大战_第1张图片

你可能感兴趣的:(pygame游戏开发,pygame,python,开发语言)