我已经写了这个脚本,它创建了向左移动的灰色方块和在一点停止的灰色方块,以及无限向右移动的红色方块。目前,它只制作每个正方形的1个。
在我看来(我是个乞讨者)下面的脚本部分是在一个循环中,所以每次计算机循环时,它应该创建一个新的灰色方块,直到总共有15个方块。为什么不是呢?
(顺便说一句,德国人是灰色的正方形)
if germancount<15:
spawn_soldier(german_startx, german_starty, german_width, german_height, grey)我的完整代码如下:
import pygame
import time
import random
pygame.init()
display_width = 1000
display_height= 800
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
grey=(169,169,169)
gameDisplay= pygame.display.set_mode((800,600))
pygame.display.set_caption('stalingrad')
clock = pygame.time.Clock()
def spawn_soldier(thingx,thingy, thingw, thingh, colour):
pygame.draw.rect(gameDisplay, colour,[thingx, thingy, thingw, thingh])
def game_loop():
russian_width= 20
russian_height= 20
russian_speed = 2
russian_startx=-30
russian_starty=random.randrange(0, display_height)
german_width=20
german_height=20
german_speed=-1
german_startx=780
german_starty=random.randrange(0, display_height)
germancount=0
russiancount=0
game_exit=False
while not game_exit:
gameDisplay.fill(white)
if germancount<15:
spawn_soldier(german_startx, german_starty, german_width, german_height, grey)
if german_startx > 700:
german_startx += german_speed
if russiancount<100:
spawn_soldier(russian_startx, russian_starty, russian_width, russian_height, red)
russian_startx += russian_speed
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()编辑,我想我想出了一个更好地定义我的问题的方法。
我需要15个这样的"spawn_soldier“函数专为德国人准备。
spawn_soldier_1(german_startx, german_starty, german_width,
spawn_soldier_2(german_startx, german_starty, german_width,
spawn_soldier_3(german_startx, german_starty, german_width,有没有办法让它用不同的y值做115个不同版本的函数,而不需要复制和粘贴115次?因为那只会是一场噩梦。
发布于 2018-08-17 07:26:11
每次循环,你都会产生一个新的士兵。实际上,因为您从未更改过germancount或russiancount,所以这样做的次数不只是15次,而是永远。每一次,你用白色覆盖所有现有的士兵,然后产生一个新的德国人和一个新的俄罗斯人,永远(尽管最终他们会离开屏幕的边缘,所以你看不到他们)。
我想你想要的是写一个能画士兵的函数:
def draw_soldier(rect, colour):
pygame.draw.rect(gameDisplay, colour, rect)然后,在帧循环中,在用斯大林格勒冬天一样的白色雪地擦除整个屏幕后,每次都添加一个新的矩形,然后重新绘制所有的矩形:
# When the game starts, there are no soldiers
germans = []
russians = []
while not game_exit:
gameDisplay.fill(white)
# Each time through the loop, add another soldier to each
# side until they're full
if len(germans) < germancount:
germans.append([german_startx, german_starty, german_width, german_height])
german_startx += german_speed
if len(russians) < russiancount:
russians.append([russian_startx, russian_starty, russian_width, russian_height])
russian_startx += russian_speed
# Now draw all the soldiers in front of that white fill
for german in germans:
draw_soldier(german, grey)
for russian in russians:
draw_soldier(russian, red)
pygame.display.update()
clock.tick(60)https://stackoverflow.com/questions/51886457
复制相似问题