【发布时间】:2021-07-19 13:48:56
【问题描述】:
import pygame
import sys
pygame.init()
window = pygame.display.set_mode([600,600])
playing = True
blue = True
x = 30 # Initial
y = 30 # Position
while playing:
for event in pygame.event.get():
if event.type == pygame.quit():
playing = False
#The above 4 lines are basically a exit function for the program that you can use in pretty much any pygame program to allow the user to exit the program
# The below is anything else you want to happen constantly while the program is running
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: # This program says that if a key is pressed down and that event is K_SPACE (K stands for keyboard and
#space is basically the key on the keyboard) then the following underneath happens
blue = not blue # makes blue false, you can also use blue == False which would be a much better way but i'm keeping this this way in case it helps with another
#program in the future
pressed = pygame.key.get_pressed() # this gets what key has been pressed so key.get_pressed() get's the key that has been pressed
if pressed[pygame.K_UP]: y += 3
if pressed[pygame.K_DOWN]: y -= 3
if pressed[pygame.K_LEFT]: x -= 3
if pressed[pygame.K_RIGHT]: x += 3
#these function change the y and x values according to the keys pressed
if blue:
colour = (0,128,255) #This changes the colour of the rectangle depending on whether or not blue is true or false as dictated by the space key in the code before the up down mechanism
else:
colour = (255,100,0)
pygame.draw.rect(window,colour, pygame.Rect(x,y),60,60) # this makes it draw a rectangle in the window, of the colour specified and makes the rectangle start at the x and y coordinates and makes the rectangle unable to get any bigger than 60/60 pixels
pygame.display.flip()
sys.exit()
我不知道我做错了什么,任何帮助将不胜感激 - 谢谢!
ps。我正在学习pygame,所以所有的笔记都是我的学习过程,忽略它们。
【问题讨论】:
-
除了下面的答案(
pygame.quit()vspygame.QUIT),您需要将您的绘图函数调用更改为pygame.draw.rect(window,colour, pygame.Rect(x,y,60,60))。您可能还想在每个循环之前用背景色填充屏幕,就在绘制之前,例如window.fill(pygame.Color("black")). -
还有你为什么使用
sys.exit()没有必要,你已经可以使用内置的exit(),它会做同样的事情,只是对这个过程更好,这也意味着您可以从您的导入中删除额外的一行,使其更加紧凑和填充