我用25个左右的Python对每个屏幕进行编码。一个是猫,另一个是老鼠。我可以让他们互相追逐,但他们不走同一条路。我该怎么做才能让他们互相跟踪,最终可能让猫吃掉炭鼠标,然后让程序结束呢?这是我的代码:
#Agustin Loomis
#'Cat & Mouse Chaser Game'
#Last Modification 4/20/14
#Cat char chases Mouse char
import pygame #import essentials
import sys
from pygame.locals import*
pygame.init() #initialize pygame
#color setup
white = (255,255,255)
black = (0,0,0)
red = (255, 0 , 0)
green = (0, 255, 0)
blue = (0, 0, 255)
yellow = (255, 255, 0)
cyan = (0,255,255)
purple = (255, 0 , 255)
FPS = 30 #assign Frame Per Second to the value of 30
fpsTime = pygame.time.Clock() #assign 'fpsTime' to pygame time clock
setDisplay = pygame.display.set_mode((500,500)) #set the display screen to 500, 500
pygame.display.set_caption('Cat & Mouse Chaser Game')
imgCat = pygame.image.load('include/NyanCat.jpg') #load img for the char cat
imgx1 = 0 #assign img coordinates
imgy1 = 10
imgMouse = pygame.image.load('include/run-with-the-mice.gif') #load imf for the Mouse char
imgx2 = 10 #assign img coordinates
imgy2 = 200
pixChange = 5 #assign variable pixel change to value of 5
movement = 'down' #assign movement constant to down
while True: #while true set display screen to black
setDisplay.fill(black)
if movement == 'down':
imgy1 += pixChange
imgy2 += pixChange
if imgy1 > 400:
movement = 'right'
if imgy2 > 400:
movement = 'right'
elif movement == 'right':
imgx1 += pixChange
imgx2 += pixChange
if imgx1 > 400:
movement = 'up'
if imgx2 > 400:
movement = 'up'
elif movement == 'up':
imgy1 -= pixChange
imgy2 -= pixChange
if imgy1 < 10:
movement = 'left'
if imgy2 < 10:
movement = 'left'
elif movement == 'left':
imgx1 -= pixChange
imgx2 -= pixChange
if imgx1 < 40:
movement = 'down'
if imgx2 < 40:
movement = 'down'
setDisplay.blit(imgCat, (imgx1,imgy1))
setDisplay.blit(imgMouse, (imgx2, imgy2))
for event in pygame.event.get():
print event
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
fpsTime.tick(FPS)
您可以通过查找x或y中哪个位置差最远来确定cat的方向,并按如下方式移动:
你必须为猫的移动和鼠标的移动设置单独的变量,除非你改变它们的速度,否则猫总是相对快速地抓住鼠标。在
要使鼠标事件触发该运动,可以编写如下内容
^{pr2}$你也可以使用pygame.KEYDOWN对于关键事件。最后,如果你想让猫杀死老鼠,你必须在每一帧比较猫和老鼠的位置。这里我检查一下x和y的差值是否都小于10个像素,您可以根据图像的大小进行更改。在
下面是一个对我有用的示例代码(我没有图像,所以我将它们改为正方形)
开始=错误 while True:#while True将显示屏设置为黑色 设置显示.fill(黑色)
相关问题 更多 >
编程相关推荐