最新版本的Python还要自己做个 pygame 模块么
import sysimport json
import math
import random
import pygame
sys.path.append('..')
from sprites import Enemy
from sprites import Turret
from interface import PAUSE
from pygame.locals import *
from collections import namedtuple
Button = namedtuple('Button', ['rect', 'text', 'onClick'])
info_color = (120, 20, 50)
red = (255, 0, 0)
green = (0, 255, 0)
black = (0, 0, 0)
white = (255, 255, 255)
grey = (127, 127, 127)
button_color1 = (0, 200, 0)
button_color2 = (0, 100, 0)
class GAMING():
def __init__(self, WIDTH=800, HEIGHT=600):
self.WIDTH = WIDTH
self.HEIGHT = HEIGHT
map_w = WIDTH
map_h = 500
button_w = 60
button_h = 60
button_y = 520
gap = 20
toolbar_w = gap * 7 + button_w * 6
info_w = (WIDTH - toolbar_w) // 2
info_h = HEIGHT - map_h
toolbar_h = HEIGHT - map_h
self.map_rect = pygame.Rect(0, 0, map_w, map_h)
self.map_surface = pygame.Surface((map_w, map_h))
self.leftinfo_rect = pygame.Rect(0, map_h, info_w, info_h)
self.rightinfo_rect = pygame.Rect(WIDTH-info_w, map_h, info_w, info_h)
self.toolbar_rect = pygame.Rect(info_w, map_h, toolbar_w, toolbar_h)
self.grass = pygame.image.load("./resource/imgs/game/grass.png")
self.rock = pygame.image.load("./resource/imgs/game/rock.png")
self.dirt = pygame.image.load("./resource/imgs/game/dirt.png")
self.water = pygame.image.load("./resource/imgs/game/water.png")
self.bush = pygame.image.load("./resource/imgs/game/bush.png")
self.nexus = pygame.image.load("./resource/imgs/game/nexus.png")
self.cave = pygame.image.load("./resource/imgs/game/cave.png")
self.elementSize = int(self.grass.get_rect().width)
self.info_font = pygame.font.Font('./resource/fonts/Calibri.ttf', 14)
self.button_font = pygame.font.Font('./resource/fonts/Calibri.ttf', 20)
self.placeable = {0: self.grass}
self.map_elements = {
0: self.grass,
1: self.rock,
2: self.dirt,
3: self.water,
4: self.bush,
5: self.nexus,
6: self.cave
}
self.path_list = []
self.currentMap = dict()
self.mouseCarried = []
self.builtTurretGroup = pygame.sprite.Group()
self.EnemiesGroup = pygame.sprite.Group()
self.arrowsGroup = pygame.sprite.Group()
self.buttons = [
Button(pygame.Rect((info_w+gap), button_y, button_w, button_h), 'T1', self.takeT1),
Button(pygame.Rect((info_w+gap*2+button_w), button_y, button_w, button_h), 'T2', self.takeT2),
Button(pygame.Rect((info_w+gap*3+button_w*2), button_y, button_w, button_h), 'T3', self.takeT3),
Button(pygame.Rect((info_w+gap*4+button_w*3), button_y, button_w, button_h), 'XXX', self.takeXXX),
Button(pygame.Rect((info_w+gap*5+button_w*4), button_y, button_w, button_h), 'Pause', self.pauseGame),
Button(pygame.Rect((info_w+gap*6+button_w*5), button_y, button_w, button_h), 'Quit', self.quitGame)
]
def start(self, screen, map_path=None, difficulty_path=None):
with open(difficulty_path, 'r') as f:
difficulty_dict = json.load(f)
self.money = difficulty_dict.get('money')
self.health = difficulty_dict.get('health')
self.max_health = difficulty_dict.get('health')
difficulty_dict = difficulty_dict.get('enemy')
GenEnemiesEvent = pygame.constants.USEREVENT + 0
pygame.time.set_timer(GenEnemiesEvent, 60000)
genEnemiesFlag = False
genEnemiesNum = 0
GenEnemyEvent = pygame.constants.USEREVENT + 1
pygame.time.set_timer(GenEnemyEvent, 500)
genEnemyFlag = False
enemyRange = None
numEnemy = None
Manualshot = False
has_control = False
while True:
if self.health <= 0:
return
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
if self.map_rect.collidepoint(event.pos):
if self.mouseCarried:
if self.mouseCarried == 'turret':
self.buildTurret(event.pos)
elif self.mouseCarried == 'XXX':
self.sellTurret(event.pos)
elif self.toolbar_rect.collidepoint(event.pos):
for button in self.buttons:
if button.rect.collidepoint(event.pos):
if button.text == 'T1':
button.onClick()
elif button.text == 'T2':
button.onClick()
elif button.text == 'T3':
button.onClick()
elif button.text == 'XXX':
button.onClick()
elif button.text == 'Pause':
button.onClick(screen)
elif button.text == 'Quit':
button.onClick()
break
if event.button == 3:
self.mouseCarried = []
if event.button == 2:
Manualshot = True
if event.type == GenEnemiesEvent:
genEnemiesFlag = True
if event.type == GenEnemyEvent:
genEnemyFlag = Ture
if genEnemiesFlag:
genEnemiesFlag = False
genEnemiesNum += 1
idx = 0
for key, value in difficulty_dict.items():
idx += 1
if idx == len(difficulty_dict.keys()):
enemyRange = value['enemyRange']
numEnemy = value['numEnemy']
break
if genEnemiesNum <= int(key):
enemyRange = value['enemyRange']
numEnemy = value['numEnemy']
break
if genEnemyFlag and numEnemy:
genEnemyFlag = False
numEnemy -= 1
enemy = Enemy.Enemy(random.choice(range(enemyRange)))
self.EnemiesGroup.add(enemy)
for turret in self.builtTurretGroup:
if not Manualshot:
position = turret.position + self.elementSize // 2, turret.position
arrow = turret.shot(position)
else:
position = turret.position + self.elementSize // 2, turret.position
mouse_pos = pygame.mouse.get_pos()
angle = math.atan((mouse_pos-position)/(mouse_pos-position+1e-6))
arrow = turret.shot(position, angle)
has_control = True
if arrow:
self.arrowsGroup.add(arrow)
else:
has_control = False
if has_control:
has_control = False
Manualshot = False
for arrow in self.arrowsGroup:
arrow.move()
points = [(arrow.rect.left, arrow.rect.top), (arrow.rect.left, arrow.rect.bottom), (arrow.rect.right, arrow.rect.top), (arrow.rect.right, arrow.rect.bottom)]
if (not self.map_rect.collidepoint(points)) and (not self.map_rect.collidepoint(points)) and \
(not self.map_rect.collidepoint(points)) and (not self.map_rect.collidepoint(points)):
self.arrowsGroup.remove(arrow)
del arrow
continue
for enemy in self.EnemiesGroup:
if pygame.sprite.collide_rect(arrow, enemy):
enemy.life_value -= arrow.attack_power
self.arrowsGroup.remove(arrow)
del arrow
break
self.draw(screen, map_path)
def draw(self, screen, map_path):
self.drawToolbar(screen)
self.loadMap(screen, map_path)
self.drawMouseCarried(screen)
self.drawBuiltTurret(screen)
self.drawEnemies(screen)
self.drawArrows(screen)
pygame.display.flip()
def drawArrows(self, screen):
for arrow in self.arrowsGroup:
screen.blit(arrow.image, arrow.rect)
def drawEnemies(self, screen):
for enemy in self.EnemiesGroup:
if enemy.life_value <= 0:
self.money += enemy.reward
self.EnemiesGroup.remove(enemy)
del enemy
continue
res = enemy.move(self.elementSize)
if res:
coord = self.find_next_path(enemy)
if coord:
enemy.reached_path.append(enemy.coord)
enemy.coord = coord
enemy.position = self.coord2pos(coord)
enemy.rect.left, enemy.rect.top = enemy.position
else:
self.health -= enemy.damage
self.EnemiesGroup.remove(enemy)
del enemy
continue
greenLen = max(0, enemy.life_value / enemy.max_life_value) * self.elementSize
if greenLen > 0:
pygame.draw.line(screen, green, (enemy.position), (enemy.position+greenLen, enemy.position), 1)
if greenLen < self.elementSize:
pygame.draw.line(screen, red, (enemy.position+greenLen, enemy.position), (enemy.position+self.elementSize, enemy.position), 1)
screen.blit(enemy.image, enemy.rect)
def drawBuiltTurret(self, screen):
for turret in self.builtTurretGroup:
screen.blit(turret.image, turret.rect)
def drawMouseCarried(self, screen):
if self.mouseCarried:
position = pygame.mouse.get_pos()
coord = self.pos2coord(position)
position = self.coord2pos(coord)
if self.map_rect.collidepoint(position):
if self.mouseCarried == 'turret':
screen.blit(self.mouseCarried.image, position)
self.mouseCarried.coord = coord
self.mouseCarried.position = position
self.mouseCarried.rect.left, self.mouseCarried.rect.top = position
else:
screen.blit(self.mouseCarried, position)
def drawToolbar(self, screen):
pygame.draw.rect(screen, info_color, self.leftinfo_rect)
leftTitle = self.info_font.render('Player info:', True, white)
moneyInfo = self.info_font.render('Money: ' + str(self.money), True, white)
healthInfo = self.info_font.render('Health: ' + str(self.health), True, white)
screen.blit(leftTitle, (self.leftinfo_rect.left+5, self.leftinfo_rect.top+5))
screen.blit(moneyInfo, (self.leftinfo_rect.left+5, self.leftinfo_rect.top+35))
screen.blit(healthInfo, (self.leftinfo_rect.left+5, self.leftinfo_rect.top+55))
pygame.draw.rect(screen, info_color, self.rightinfo_rect)
rightTitle = self.info_font.render('Selected info:', True, white)
screen.blit(rightTitle, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+5))
pygame.draw.rect(screen, grey, self.toolbar_rect)
for button in self.buttons:
mouse_pos = pygame.mouse.get_pos()
if button.rect.collidepoint(mouse_pos):
self.showSelectedInfo(screen, button)
button_color = button_color1
else:
button_color = button_color2
pygame.draw.rect(screen, button_color, button.rect)
buttonText = self.button_font.render(button.text, True, white)
buttonText_rect = buttonText.get_rect()
buttonText_rect.center = (button.rect.centerx, button.rect.centery)
screen.blit(buttonText, buttonText_rect)
def showSelectedInfo(self, screen, button):
if button.text == 'T1':
T1 = Turret.Turret(0)
selectedInfo1 = self.info_font.render('Cost: '+str(T1.price), True, white)
selectedInfo2 = self.info_font.render('Damage: '+str(T1.arrow.attack_power), True, white)
selectedInfo3 = self.info_font.render('Affordable: '+str(self.money>=T1.price), True, white)
screen.blit(selectedInfo1, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+35))
screen.blit(selectedInfo2, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+55))
screen.blit(selectedInfo3, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+75))
elif button.text == 'T2':
T2 = Turret.Turret(1)
selectedInfo1 = self.info_font.render('Cost: '+str(T2.price), True, white)
selectedInfo2 = self.info_font.render('Damage: '+str(T2.arrow.attack_power), True, white)
selectedInfo3 = self.info_font.render('Affordable: '+str(self.money>=T2.price), True, white)
screen.blit(selectedInfo1, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+35))
screen.blit(selectedInfo2, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+55))
screen.blit(selectedInfo3, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+75))
elif button.text == 'T3':
T3 = Turret.Turret(2)
selectedInfo1 = self.info_font.render('Cost: '+str(T3.price), True, white)
selectedInfo2 = self.info_font.render('Damage: '+str(T3.arrow.attack_power), True, white)
selectedInfo3 = self.info_font.render('Affordable: '+str(self.money>=T3.price), True, white)
screen.blit(selectedInfo1, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+35))
screen.blit(selectedInfo2, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+55))
screen.blit(selectedInfo3, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+75))
elif button.text == 'XXX':
selectedInfo = self.info_font.render('Sell a turret', True, white)
screen.blit(selectedInfo, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+35))
elif button.text == 'Pause':
selectedInfo = self.info_font.render('Pause game', True, white)
screen.blit(selectedInfo, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+35))
elif button.text == 'Quit':
selectedInfo = self.info_font.render('Quit game', True, white)
screen.blit(selectedInfo, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+35))
def sellTurret(self, position):
coord = self.pos2coord(position)
for turret in self.builtTurretGroup:
if coord == turret.coord:
self.builtTurretGroup.remove(turret)
self.money += turret.price * 0.5
del turret
break
def buildTurret(self, position):
turret = self.mouseCarried
coord = self.pos2coord(position)
position = self.coord2pos(coord)
turret.position = position
turret.coord = coord
turret.rect.left, turret.rect.top = position
if self.money - turret.price >= 0:
if self.currentMap.get(turret.coord) in self.placeable.keys():
self.money -= turret.price
self.builtTurretGroup.add(turret)
if self.mouseCarried.turret_type == 0:
self.mouseCarried = []
self.takeT1()
elif self.mouseCarried.turret_type == 1:
self.mouseCarried = []
self.takeT2()
elif self.mouseCarried.turret_type == 2:
self.mouseCarried = []
self.takeT3()
def takeT1(self):
T1 = Turret.Turret(0)
if self.money >= T1.price:
self.mouseCarried = ['turret', T1]
def takeT2(self):
T2 = Turret.Turret(1)
if self.money >= T2.price:
self.mouseCarried = ['turret', T2]
def takeT3(self):
T3 = Turret.Turret(2)
if self.money >= T3.price:
self.mouseCarried = ['turret', T3]
def takeXXX(self):
XXX = pygame.image.load('./resource/imgs/game/x.png')
self.mouseCarried = ['XXX', XXX]
def find_next_path(self, enemy):
x, y = enemy.coord
neighbours = [(x, y+1), (x+1, y), (x-1, y), (x, y-1)]
for neighbour in neighbours:
if (neighbour in self.path_list) and (neighbour not in enemy.reached_path):
return neighbour
return None
def pos2coord(self, position):
return (position//self.elementSize, position//self.elementSize)
def coord2pos(self, coord):
return (coord*self.elementSize, coord*self.elementSize)
def loadMap(self, screen, map_path):
map_file = open(map_path, 'r')
idx_j = -1
for line in map_file.readlines():
line = line.strip()
if not line:
continue
idx_j += 1
idx_i = -1
for col in line:
try:
element_type = int(col)
element_img = self.map_elements.get(element_type)
element_rect = element_img.get_rect()
idx_i += 1
element_rect.left, element_rect.top = self.elementSize * idx_i, self.elementSize * idx_j
self.map_surface.blit(element_img, element_rect)
self.currentMap = element_type
if element_type == 1:
self.path_list.append((idx_i, idx_j))
except:
continue
self.map_surface.blit(self.cave, (0, 0))
self.map_surface.blit(self.nexus, (740, 400))
nexus_width = self.nexus.get_rect().width
greenLen = max(0, self.health / self.max_health) * nexus_width
if greenLen > 0:
pygame.draw.line(self.map_surface, green, (740, 400), (740+greenLen, 400), 3)
if greenLen < nexus_width:
pygame.draw.line(self.map_surface, red, (740+greenLen, 400), (740+nexus_width, 400), 3)
screen.blit(self.map_surface, (0, 0))
map_file.close()
def pauseGame(self, screen):
pause_interface = PAUSE.PAUSE(self.WIDTH, self.HEIGHT)
pause_interface.update(screen)
def quitGame(self):
sys.exit(0)
pygame.quit()
为什么我这边运行显示没有 pygame 模块 pygame要去下载
pip install pygame
pygame 去参考第二个安装方法 大马强 发表于 2022-3-28 20:20
pygame要去下载
pygame 去参考第二个安装方法
要怎么下载呢 收纳空白1321 发表于 2022-3-28 20:45
要怎么下载呢
DOS--cmd--pip install pygame z Gacy 发表于 2022-3-28 20:59
z
是这样么 收纳空白1321 发表于 2022-3-28 21:11
是这样么
是的 大马强 发表于 2022-3-28 21:20
是的
这个呢 本帖最后由 收纳空白1321 于 2022-3-28 22:49 编辑
收纳空白1321 发表于 2022-3-28 21:34
这个呢
我担心我乱打字母会弄出一下奇奇怪怪的东西出来
好吧,报错了,所以是怎么下载呢?
求助各位大佬{:5_111:} 收纳空白1321 发表于 2022-3-28 21:48
我担心我乱打字母会弄出一下奇奇怪怪的东西出来
这个是那个作者自己写的模块吧
你看看有没有 Enemy,py 文件,如果有的话看看 里面有没有 sprites函数 大马强 发表于 2022-3-28 21:56
这个是那个作者自己写的模块吧
你看看有没有 Enemy,py 文件,如果有的话看看 里面有没有 sprites函数
好的感谢大佬{:5_111:} 收纳空白1321 发表于 2022-3-28 21:59
好的感谢大佬
前面都学完了?
一上来就啃pygame是很难的哦,对前面的语法知识要有一定掌握的 本帖最后由 收纳空白1321 于 2022-3-28 22:48 编辑
大马强 发表于 2022-3-28 22:05
前面都学完了?
一上来就啃pygame是很难的哦,对前面的语法知识要有一定掌握的
好的,认真学习感谢大佬的提醒
{:5_111:}
本帖最后由 收纳空白1321 于 2022-3-28 22:26 编辑
大马强 发表于 2022-3-28 22:05
前面都学完了?
一上来就啃pygame是很难的哦,对前面的语法知识要有一定掌握的
前面要学习那些语法知识呢我在那里可以找到呢还是要买书籍
或者我找到了个 CSDN网站 和Python学习网这些有吗
还是我们的小甲鱼就有呢
好吧,我反应过来了, 小甲鱼的视频我还没有看完 C:\Users\86185\Desktop\X5Y%5BFAJPAAW[%[ 是因为你没有下载pygame模块,你可以右键win选择运行输入cmd,再输入pip install pygame下载 C:\Users\86185\Desktop\图片.png
Microsoft Windows [版本 10.0.19042.1586]
(c) Microsoft Corporation。保留所有权利。
C:\Users\86185>pip install pygame
'pip' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
这个要怎么办。 本帖最后由 收纳空白1321 于 2022-4-11 12:50 编辑
18577471785 发表于 2022-4-10 18:29
Microsoft Windows [版本 10.0.19042.1586]
(c) Microsoft Corporation。保留所有权利。
你可以搜索一下这个它有详细解说的
python无法使用pip_python中pip无法使用的解决方法
这个链接
https://blog.csdn.net/weixin_39663970/article/details/110023631
页:
[1]