如何让物体在 pygame 中射击
How to get objects to shoot in pygame
我只是更新我的代码,但我的新问题是,当按下 space 栏时,我如何让子弹射出播放器的任何地方。因为现在我正在尝试将子弹的生成位置设置为玩家在游戏中的任何位置,但我不知道如何设置。
这是更新后的代码:
import pygame, random, sys
import random
import os
from pygame.locals import *
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
ROBOTMINSIZE = 50
ROBOTMAXSIZE = 50
ROBOTMINSPEED = 1
ROBOTMAXSPEED =1
ADDNEWROBOTRATE = 3
ADDNEWBULLETRATE = 3
PLAYERMOVERATE = 1
#pregame information and questions
print('''Hello There! Welcome to my Machine Domination Game! First you will be given information about Machine Domination. If you answer the question correctly, you will be allowed to play a game!
The informatiion is printed below. Memorize it, and when you are ready, you will be asked a question.
Machine Domination, also known as AI takeover, efers to a hypothetical scenario in which artificial intelligence (AI) becomes the dominant form of intelligence on Earth, with computers or
robots effectively taking control of the planet away from the human race. Possible scenarios include a takeover by a superintelligent AI and the popular notion of a robot uprising. As computer
and robotics technologies are advancing at an ever increasing rate, AI takeover is a growing concern. It has also been a major theme throughout science fiction for many decades, though the scenarios
dealt with by science fiction are generally very different from those of concern to scientists.
There is an ongoing debate over whether or not artificial intelligence will pose a threat to the human race, or to humans' control of society. Some of the concerns are: the issue of feasibility
(whether or not AI can reach human or better intelligence); whether or not such strong AI could take over (or pose a threat); and whether it would be friendly or unfriendly (or indifferent) to humans.
The hypothetical future event in which strong AI emerges is referred to as the technological singularity.
Futurist and computer scientist Raymond Kurzweil has noted that "There are physical limits to computation, but they're not very limiting." If the current trend in computer computation improvement continues,
and existing problems in creating artificial intelligence are overcome, sentient machines are likely to immediately hold an enormous advantage in at least some forms of mental capability, including the
capacity of perfect recall, a vastly superior knowledge base, and the ability to multitask in ways not possible to biological entities. This may give them the opportunity to— either as a single being or as a
new species — become much more powerful than humans, and to displace them.
Stephen Hawkins also said that in 100 years AI could actually take over. We need to start acting now to stop Machine Domination!''')
questions=["What is AI takeover?", "How ling did Stephen Hawkins say before AI takes over?", "When do we need to start acting to stop AI takeover?"]
answers1=["AI takover is the idea that robots will take over Earth.", "AI takeover os the idea that robots will be made in 100 years."]
answers2=["100 years.", "1000 years."]
answers3=["Now.", "Later"]
advance=input("Press Enter for question.")
number=(random.randint(0,2))
if number==0:
print(questions[0])
print("1 " + answers1[0] + " " + "2 " + answers1[1])
user=input("Type 1 or 2 for your answer")
if user=='1':
print("Correct!")
elif user=='2':
print("Sorry, wrong answer.")
os._exit(0)
elif number==1:
print(questions[1])
print("1 " + answers2[0] + " " + "2 " + answers2[1])
user2=input("Type 1 or 2 for your answer")
if user2=='1':
print("Correct!")
elif user2=='2':
print("Sorry, wrong answer.")
os._exit(0)
elif number==2:
print(questions[2])
print("1 " + answers3[0] + " " + "2 " + answers3[1])
user3=input("Type 1 or 2 for your answer")
if user3=='1':
print("Correct!")
elif user3=='2':
print("Sorry, wrong answer.")
os._exit(0)
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def playerHasHitRobot(playerRect, robots):
for b in robots:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Shooter')
pygame.mouse.set_visible(False)
# set up fonts
font = pygame.font.SysFont(None, 48)
# set up sounds
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('invasion.wav')
deathSound = pygame.mixer.Sound('explosion.wav')
# set up images
playerImage = pygame.image.load('earth.png')
playerRect = playerImage.get_rect()
robotImage = pygame.image.load('robot.png')
background_image=pygame.image.load("space.png").convert()
bullet_image = pygame.image.load("bullet.png")
# show the "Start" screen
drawText('Welcome to my game.', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
topScore = 0
while True:
# set up the start of the game
robots = []
bullets = []
score = 0
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
robotAddCounter = 0
bulletAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
while True: # the game loop runs while the game part is playing
score += 1 # increase score
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_SPACE:
bulletAddCounter += 1
if bulletAddCounter == ADDNEWBULLETRATE:
bulletAddCounter = 0
bulletSize = 10
newBullet= {'rect': pygame.Rect(20, 20, 20, 20),
'speed': 12,
'surface':pygame.transform.scale(bullet_image, (bulletSize, bulletSize)),
}
bullets.append(newBullet)
if event.type == KEYUP:
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
robotAddCounter += 1
if robotAddCounter == ADDNEWROBOTRATE:
robotAddCounter = 0
robotSize = random.randint(ROBOTMINSIZE, ROBOTMAXSIZE)
newRobot= {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-robotSize), 0 - robotSize, robotSize, robotSize),
'speed': random.randint(ROBOTMINSPEED, ROBOTMAXSPEED),
'surface':pygame.transform.scale(robotImage, (robotSize, robotSize)),
}
robots.append(newRobot)
#Move the player around.
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
# Move the robots down.
for b in robots:
b['rect'].move_ip(0, b['speed'])
for b in bullets:
b['rect'].move_ip(40, 12)
pygame.display.update()
# Delete robots that have fallen past the bottom.
for b in robots[:]:
if b['rect'].top > WINDOWHEIGHT:
robots.remove(b)
# Draw the game world on the window.
windowSurface.fill(BACKGROUNDCOLOR)
windowSurface.blit(background_image,[0,0])
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 10, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
# Draw the player's rectangle
windowSurface.blit(playerImage, playerRect)
# Draw each robot
for b in robots:
windowSurface.blit(b['surface'], b['rect'])
for b in bullets:
windowSurface.blit(b['surface'], b['rect'])
pygame.display.update()
# Check if any of the robots have hit the player.
if playerHasHitRobot(playerRect, robots):
if score > topScore:
topScore = score # set new top score
break
mainClock.tick(FPS)
# Stop the game and show the "Game Over" screen.
pygame.mixer.music.stop()
gameOverSound.play()
drawText('GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
我一直试图改变的主要部分是:
# Move the robots down.
for b in robots:
b['rect'].move_ip(0, b['speed'])
for b in bullets:
b['rect'].move_ip(40, 12)
pygame.display.update()
我一直在尝试将子弹的位置设置为玩家所在的位置。现在它在 40 和 12。那么我如何将它设置到那个位置。另外,我如何让它直线向上移动,因为现在它沿对角线移动。谢谢。
你必须先把所有东西都画出来
pygame.display.update()
(以及 windowSurface.fill(BACKGROUNDCOLOR)
之后)
现在你在 update()
之后绘制子弹,它将所有内容从缓冲区发送到显示器(或者更确切地说是发送到视频卡,然后在显示器上绘制它),然后在 fill(BACKGROUNDCOLOR)
之前绘制子弹,它清除缓冲区。
编辑:
# --- drawing ---
... do not draw here ...
# clear buffer
windowSurface.fill(BACKGROUNDCOLOR)
... draw everything here ...
# send buffer to video card and on monitor/screen
pygame.display.update()
... do not draw here ...
我只是更新我的代码,但我的新问题是,当按下 space 栏时,我如何让子弹射出播放器的任何地方。因为现在我正在尝试将子弹的生成位置设置为玩家在游戏中的任何位置,但我不知道如何设置。
这是更新后的代码:
import pygame, random, sys
import random
import os
from pygame.locals import *
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
ROBOTMINSIZE = 50
ROBOTMAXSIZE = 50
ROBOTMINSPEED = 1
ROBOTMAXSPEED =1
ADDNEWROBOTRATE = 3
ADDNEWBULLETRATE = 3
PLAYERMOVERATE = 1
#pregame information and questions
print('''Hello There! Welcome to my Machine Domination Game! First you will be given information about Machine Domination. If you answer the question correctly, you will be allowed to play a game!
The informatiion is printed below. Memorize it, and when you are ready, you will be asked a question.
Machine Domination, also known as AI takeover, efers to a hypothetical scenario in which artificial intelligence (AI) becomes the dominant form of intelligence on Earth, with computers or
robots effectively taking control of the planet away from the human race. Possible scenarios include a takeover by a superintelligent AI and the popular notion of a robot uprising. As computer
and robotics technologies are advancing at an ever increasing rate, AI takeover is a growing concern. It has also been a major theme throughout science fiction for many decades, though the scenarios
dealt with by science fiction are generally very different from those of concern to scientists.
There is an ongoing debate over whether or not artificial intelligence will pose a threat to the human race, or to humans' control of society. Some of the concerns are: the issue of feasibility
(whether or not AI can reach human or better intelligence); whether or not such strong AI could take over (or pose a threat); and whether it would be friendly or unfriendly (or indifferent) to humans.
The hypothetical future event in which strong AI emerges is referred to as the technological singularity.
Futurist and computer scientist Raymond Kurzweil has noted that "There are physical limits to computation, but they're not very limiting." If the current trend in computer computation improvement continues,
and existing problems in creating artificial intelligence are overcome, sentient machines are likely to immediately hold an enormous advantage in at least some forms of mental capability, including the
capacity of perfect recall, a vastly superior knowledge base, and the ability to multitask in ways not possible to biological entities. This may give them the opportunity to— either as a single being or as a
new species — become much more powerful than humans, and to displace them.
Stephen Hawkins also said that in 100 years AI could actually take over. We need to start acting now to stop Machine Domination!''')
questions=["What is AI takeover?", "How ling did Stephen Hawkins say before AI takes over?", "When do we need to start acting to stop AI takeover?"]
answers1=["AI takover is the idea that robots will take over Earth.", "AI takeover os the idea that robots will be made in 100 years."]
answers2=["100 years.", "1000 years."]
answers3=["Now.", "Later"]
advance=input("Press Enter for question.")
number=(random.randint(0,2))
if number==0:
print(questions[0])
print("1 " + answers1[0] + " " + "2 " + answers1[1])
user=input("Type 1 or 2 for your answer")
if user=='1':
print("Correct!")
elif user=='2':
print("Sorry, wrong answer.")
os._exit(0)
elif number==1:
print(questions[1])
print("1 " + answers2[0] + " " + "2 " + answers2[1])
user2=input("Type 1 or 2 for your answer")
if user2=='1':
print("Correct!")
elif user2=='2':
print("Sorry, wrong answer.")
os._exit(0)
elif number==2:
print(questions[2])
print("1 " + answers3[0] + " " + "2 " + answers3[1])
user3=input("Type 1 or 2 for your answer")
if user3=='1':
print("Correct!")
elif user3=='2':
print("Sorry, wrong answer.")
os._exit(0)
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def playerHasHitRobot(playerRect, robots):
for b in robots:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Shooter')
pygame.mouse.set_visible(False)
# set up fonts
font = pygame.font.SysFont(None, 48)
# set up sounds
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('invasion.wav')
deathSound = pygame.mixer.Sound('explosion.wav')
# set up images
playerImage = pygame.image.load('earth.png')
playerRect = playerImage.get_rect()
robotImage = pygame.image.load('robot.png')
background_image=pygame.image.load("space.png").convert()
bullet_image = pygame.image.load("bullet.png")
# show the "Start" screen
drawText('Welcome to my game.', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
topScore = 0
while True:
# set up the start of the game
robots = []
bullets = []
score = 0
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
robotAddCounter = 0
bulletAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
while True: # the game loop runs while the game part is playing
score += 1 # increase score
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_SPACE:
bulletAddCounter += 1
if bulletAddCounter == ADDNEWBULLETRATE:
bulletAddCounter = 0
bulletSize = 10
newBullet= {'rect': pygame.Rect(20, 20, 20, 20),
'speed': 12,
'surface':pygame.transform.scale(bullet_image, (bulletSize, bulletSize)),
}
bullets.append(newBullet)
if event.type == KEYUP:
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
robotAddCounter += 1
if robotAddCounter == ADDNEWROBOTRATE:
robotAddCounter = 0
robotSize = random.randint(ROBOTMINSIZE, ROBOTMAXSIZE)
newRobot= {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-robotSize), 0 - robotSize, robotSize, robotSize),
'speed': random.randint(ROBOTMINSPEED, ROBOTMAXSPEED),
'surface':pygame.transform.scale(robotImage, (robotSize, robotSize)),
}
robots.append(newRobot)
#Move the player around.
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
# Move the robots down.
for b in robots:
b['rect'].move_ip(0, b['speed'])
for b in bullets:
b['rect'].move_ip(40, 12)
pygame.display.update()
# Delete robots that have fallen past the bottom.
for b in robots[:]:
if b['rect'].top > WINDOWHEIGHT:
robots.remove(b)
# Draw the game world on the window.
windowSurface.fill(BACKGROUNDCOLOR)
windowSurface.blit(background_image,[0,0])
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 10, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
# Draw the player's rectangle
windowSurface.blit(playerImage, playerRect)
# Draw each robot
for b in robots:
windowSurface.blit(b['surface'], b['rect'])
for b in bullets:
windowSurface.blit(b['surface'], b['rect'])
pygame.display.update()
# Check if any of the robots have hit the player.
if playerHasHitRobot(playerRect, robots):
if score > topScore:
topScore = score # set new top score
break
mainClock.tick(FPS)
# Stop the game and show the "Game Over" screen.
pygame.mixer.music.stop()
gameOverSound.play()
drawText('GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
我一直试图改变的主要部分是:
# Move the robots down.
for b in robots:
b['rect'].move_ip(0, b['speed'])
for b in bullets:
b['rect'].move_ip(40, 12)
pygame.display.update()
我一直在尝试将子弹的位置设置为玩家所在的位置。现在它在 40 和 12。那么我如何将它设置到那个位置。另外,我如何让它直线向上移动,因为现在它沿对角线移动。谢谢。
你必须先把所有东西都画出来
pygame.display.update()
(以及 windowSurface.fill(BACKGROUNDCOLOR)
之后)
现在你在 update()
之后绘制子弹,它将所有内容从缓冲区发送到显示器(或者更确切地说是发送到视频卡,然后在显示器上绘制它),然后在 fill(BACKGROUNDCOLOR)
之前绘制子弹,它清除缓冲区。
编辑:
# --- drawing ---
... do not draw here ...
# clear buffer
windowSurface.fill(BACKGROUNDCOLOR)
... draw everything here ...
# send buffer to video card and on monitor/screen
pygame.display.update()
... do not draw here ...