【发布时间】:2021-10-24 14:44:04
【问题描述】:
我想弄清楚为什么我的显示器没有出现。我在 Mac 上,我可以看到我的 Dock 中的 pygame 图标出现了,但是没有创建任何窗口。我在 pycharm 上的 python 3.9.6 上运行 pygame 2.0.2。我已经尝试打开其他 pygame 脚本并且它们可以正常打开,但是我看不出这 2 个脚本的打开方式有什么区别。
import pygame
import random
from enum import Enum
from collections import namedtuple
pygame.init()
WHITE = (255, 255, 255)
RED = (200, 0, 0)
GREEN1 = (0, 255, 0)
GREEN2 = (0, 200, 100)
BLACK = (0, 0, 0)
SPEED = 20
BLOCK_SIZE = 20
Point = namedtuple('Point', 'x, y')
font = pygame.font.SysFont('arial', 25)
class Direction(Enum):
RIGHT = 1
LEFT = 2
UP = 3
DOWN = 4
class SnakeGame:
def __init__(self, w=640, h=480):
self.w = w
self.h = h
# init display
self.display = pygame.display.set_mode((self.w, self.h))
pygame.display.set_caption('Snake')
self.clock = pygame.time.Clock()
# init game state
self.direction = Direction.RIGHT
self.head = Point(self.w / 2, self.h / 2)
self.snake = [self.head,
Point(self.head.x - BLOCK_SIZE, self.head.y),
Point(self.head.x - BLOCK_SIZE * 2, self.head.y)]
self.score = 0
self.food = None
self._place_food()
def _place_food(self):
x = random.randint(0, (self.w - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
y = random.randint(0, (self.w - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
self.food = Point(x, y)
if self.food in self.snake:
self._place_food()
def play_step(self):
# Collect user input
# Move
# Check if game over
# Place new food or just move
# Update ui and clock
# self._update_ui()
# self.clock.tick(SPEED)
# Return game over and score
game_over = False
return game_over, self.score
def _update_ui(self):
self.display.fill(BLACK)
for pt in self.snake:
pygame.draw.rect(self.display, GREEN1, pygame.Rect(pt.x, pt.y, BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(self.display, GREEN2, pygame.Rect(pt.x + 4, pt.y + 4, 12, 12))
pygame.draw.rect(self.display, RED, pygame.Rect(self.food.x, self.food.y, BLOCK_SIZE, BLOCK_SIZE))
text = font.render('Score: ' + str(self.score), True, WHITE)
self.display.blit(text, [0, 0])
pygame.display.flip()
if __name__ == '__main__':
game = SnakeGame()
while True:
game_over, score = game.play_step()
if game_over:
break
print('Final Score', score)
pygame.quit()
【问题讨论】:
-
请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。