我目前正在为一个学校项目做一些小游戏。我遇到了一个我不知道该怎么办的问题。游戏基本上是一个原始的蛇游戏,有点扭曲。每当蛇与其中一种食物碰撞时,就会弹出一个新的窗口。我不知道如何制作弹出窗口。我研究了一下,有一个叫Tkinter的东西,可以做一个弹出窗口。希望你能帮助我。
我正在处理的代码。
import pygame, random, sys
from pygame.locals import *
from Tkinter import *
def collide(x1, x2, y1, y2, w1, w2, h1, h2):
if x1+w1>x2 and x1<x2+w2 and y1+h1>y2 and y1<y2+h2:return True
else:return False
def die(screen, score):
f=pygame.font.SysFont('Arial', 40);t=f.render('Du fik: '+str(score)+' point', True, (0, 0, 0));screen.blit(t, (10, 50));pygame.display.update();pygame.time.wait(2000);sys.exit(0)
xs = [300, 300, 300, 300, 300];ys = [290, 270, 250, 230, 210];key = 0;score = 0;applepos = (random.randint(0, 590), random.randint(0, 590));pygame.init();s=pygame.display.set_mode((600, 600));pygame.display.set_caption('Snake');appleimage = pygame.Surface((20, 20));appleimage.fill((0, 0, 0));img = pygame.Surface((20, 20));img.fill((255, 0, 0));f = pygame.font.SysFont('Arial', 20);clock = pygame.time.Clock()
while True:
clock.tick(20)
for e in pygame.event.get():
if e.type == QUIT:
sys.exit(0)
elif e.type == KEYDOWN:
if e.key == K_UP and key != 0:key = 2
elif e.key == K_DOWN and key != 2:key = 0
elif e.key == K_LEFT and key != 1:key = 3
elif e.key == K_RIGHT and key != 3:key = 1
i = len(xs)-2
while i >= 2:
if collide(xs[0], xs[i], ys[0], ys[i], 20, 20, 20, 20):die(s, score)
i-= 1
#This is here where the windows gonna popup after it collide with the object.
if collide(xs[0], applepos[0], ys[0], applepos[1], 20, 20, 20, 20):score+=1;xs.append(700);ys.append(700);applepos=(random.randint(0,590),random.randint(0,590))
if xs[0] < 0 or xs[0] > 580 or ys[0] < 0 or ys[0] > 580: die(s, score)
i = len(xs)-1
while i >= 1:
xs[i] = xs[i-1];ys[i] = ys[i-1];i -= 1
if key==0:ys[0] += 20
elif key==1:xs[0] += 20
elif key==2:ys[0] -= 20
elif key==3:xs[0] -= 20
s.fill((255, 255, 255))
for i in range(0, len(xs)):
s.blit(img, (xs[i], ys[i]))
s.blit(appleimage, applepos);t=f.render(str(score), True, (0, 0, 0));s.blit(t, (10, 10));pygame.display.update()
答案 0 :(得分:1)
如果你想要蛇一样的消息框,你必须添加
import tkMessageBox
和
Tk().wm_withdraw()
tkMessageBox.showerror(title, message)
在
if collide(xs[0], applepos[0], ys[0], applepos[1], 20, 20, 20, 20):score+=1;xs.append(700);ys.append(700);applepos=(random.randint(0,590),random.randint(0,590))
像这样:
if collide(xs[0], applepos[0], ys[0], applepos[1], 20, 20, 20, 20):
score+=1
xs.append(700)
ys.append(700)
applepos=(random.randint(0,590),random.randint(0,590))
Tk().wm_withdraw()
tkMessageBox.showerror(title, message)
答案 1 :(得分:0)
由于您只应创建一个根窗口,因此必须使用Toplevel打开一个新窗口。
def newWindow():
toplevel = Toplevel()
toplevel.title('Another window')
toplevel.focus_set()