前段时间学了pygame,这两天写一个星球大战小游戏,今天准备分享出来。
开发工具: python3.8、pycharm
代码注释超级详细,在这里就废话不多说了,请看代码!
# 导入相关模块及库
import pygame
import sys
import random
import math
# 1.初始化界面
pygame.init()
# 设置窗口大小
size = width, height = 800, 600
screen = pygame.display.set_mode(size)
# 设置游戏名称
pygame.display.set_caption('星球大战')
# 游戏图标
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)
# 3.游戏背景
bgImg = pygame.image.load('bg.png')
# 4.玩家图片
playerImg = pygame.image.load('player.png')
playerX = 400 # X轴设为400
playerY = 530 # Y轴设为530
# 7.设置玩家移动速度
playerStep = 0
def move_player(): # 玩家移动
# 5.设置玩家移动速度
global playerX
playerX += playerStep
# 6.防止玩家出界
if playerX > 736:
playerX = 736
if playerX < 0:
playerX = 0
# 8.敌人
# enemyImg = pygame.image.load('enemy.png')
# enemyX = random.randint(100,600) # X轴随机出现在100~600
# enemyY = random.randint(30,150) # Y轴随机出现在30~150
# enemyStep = 1 # 9.设置敌人移动速度
# 11.添加多个敌人
number_of_enemies = 6 # 敌人总数
class Enemy(): # 定义敌人类
def __init__(self):
self.img = pygame.image.load('enemy.png')
self.x = random.randint(100