【发布时间】:2026-02-01 07:55:02
【问题描述】:
下面的代码是骨架,它应该是纸牌游戏的开始。我生成了一张随机手牌(现在是一张牌),但我似乎无法让它只生成第一手牌一次。 while 循环重复并不断为第一手牌生成一张新的随机牌。
编辑:它不会重复生成随机卡片,但现在它崩溃了
import pygame, sys, random
from pygame.locals import*
WINWIDTH = 1200
WINHEIGHT = 800
CARDTHUMBWIDTH = 50
CARDTHUMBHEIGHT = 80
FPS = 30
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINWIDTH,WINHEIGHT))
pygame.display.set_caption('NBA Card Game')
pygame.init()
playerHandPos = [(17, 635), (75, 635), (133, 635), (191, 635), (249, 635), (307, 635), (365, 635), (423, 635), (481, 635), (539, 635)]
lakersDeck = ['Lakers_01.png', 'Lakers_02.png', 'Lakers_03.png', 'Lakers_04.png', 'Lakers_05.png', 'Lakers_06.png', 'Lakers_07.png', 'Lakers_08.png', 'Lakers_09.png', 'Lakers_10.png']
turnCount = 0
font = pygame.font.SysFont(None, 30)
userTextPrompt = "20, 725"
playMat = pygame.image.load('playmat.png')
detailBox = pygame.image.load('detailBox.png')
DISPLAYSURF.blit(playMat, (0,0))
def terminate():
pygame.quit()
sys.exit()
##def drawText(text, font, surface, x, y):
## textobj = font.render(text, 1, (0,0,0))
## textrect = textobj.get_rect()
## textrect.topleft = (x,y)
## surface.blit(textobj, textrect)
def getFirstHand():
random.shuffle(lakersDeck)
firstHand = [lakersDeck[0], lakersDeck[1], lakersDeck[2], lakersDeck[3]]
return firstHand
def displayHand():
cardThumb = pygame.image.load(playerHand[0])
cardThumb = pygame.transform.scale(cardThumb, (50,80))
DISPLAYSURF.blit(cardThumb, playerHandPos[0])
pygame.display.update()
def playerTurn():
placedBench = False
while placedBench == False:
drawText("Choose a card for your bench.", font, DISPLAYSURF, 20, 725)
pygame.display.update()
def cardLakers_01():
offense = 10
return offense
while True:
playerHand = []
mouse = pygame.mouse.get_pos()
print(mouse)
if turnCount == 0:
getFirstHand()
playerHand = getFirstHand()
turnCount += 1
displayHand()
playerTurn()
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYUP:
if event.key == K_ESCAPE:
terminate()
if event.type == MOUSEMOTION:
if 67 > mouse[0] > 17 and 710 > mouse[1] > 635:
cardDashImage = pygame.image.load('Lakers_01.png')
DISPLAYSURF.blit(cardDashImage, (925, 200))
pygame.display.update()
else:
detailBox = pygame.image.load('detailBox.png')
DISPLAYSURF.blit(detailBox, (900,0))
pygame.display.update()
FPSCLOCK
pygame.display.update()
pygame.display.update()
【问题讨论】:
-
FPSCLOCK = pygame.time.Clock(): 那么你使用的是FPSCLOCK,它不会调用函数BTW。 -
当然,因为每次显示时都会调用 getFirstHand 例程。随机在这里。您应该执行一次,然后存储结果。
-
在您的 while 循环中,您有以下代码:如果 turnCount == 0: getFirstHand(),但您没有使用 getFirstHand() 函数返回的值。
-
如果您遇到崩溃,包括回溯可以让我们更轻松地为您提供帮助。此外,最好在开始时加载一次资源,然后将它们复制到适当的表面/精灵。
标签: python loops random while-loop pygame