- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
这是我使用 pygame 创建的第一款游戏,它基本上是贪吃蛇。
请不要介意我可怕的评论。
## William's Snake Game
import pygame
import time
import random
pygame.init()
##Global variables
# Colours
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 155, 0)
bground = (204, 204, 0)
# Display vars.
display_width = 800
display_height = 600
# Variables
gameDisplay = pygame.display.set_mode((display_width, display_height)) ##resolution, note that this is a tuple.
pygame.display.set_caption("Snake VS Apple") # Title at the top of the screen
icon = pygame.image.load('logoapple32x32.png') # Loads the icon for the top left
pygame.display.set_icon(icon) # Sets the icon for the top left
snakeHeadImg = pygame.image.load("snakeHead.png") # Loads the image for the snake head
appleImg = pygame.image.load("apple20x20.png") # Loads the image for the apple
appleThickness = 20 # Defines how thick apple will be. Note to self: This is changable
clock = pygame.time.Clock() # Starts clocking the game, used later for FPS
blockSize = 20 # Defines how big the snake will be. Changing this will mess up collision detection.
FPS = 15 # Frames per second. Called at the bottom of script
smallfont = pygame.font.SysFont("arial", 25) ## format: ("font", fontsize)
medfont = pygame.font.SysFont("arial", 40) ##
largefont = pygame.font.SysFont("arial", 80) ##
direction = "right" # Starting direction of snake, used in main gameLoop
##
def pauseGame():
gameisPaused = True
while gameisPaused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
gameisPaused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("Paused",
black,
-100,
size="large")
message_to_screen("Press ESC to continue or Q to quit.",
black,
25,
size="small")
pygame.display.update()
clock.tick(5)
def text_objects(text, color, size): # Function to render text
if size == "small":
textSurface = smallfont.render(text, True, color)
elif size == "medium":
textSurface = medfont.render(text, True, color)
elif size == "large":
textSurface = largefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def message_to_screen(msg, color, y_displace=0, size="medium"): # Function to blit (draw) text to surface
textSurf, textRect = text_objects(msg, color, size)
textRect.center = (display_width / 2), (display_height / 2) + y_displace
gameDisplay.blit(textSurf, textRect)
##
def score(score):
text = smallfont.render("Score: " + str(score), True, black)
gameDisplay.blit(text, [0, 0])
def randAppleGen(): # Function to generate random apples
randAppleX = round(
random.randrange(0, display_width - appleThickness)) # /10.0)*10.0 ##Create another rand X value for new apple
randAppleY = round(
random.randrange(0, display_height - appleThickness)) # /10.0)*10.0 ##Create another rand Y value for new apple
return randAppleX, randAppleY
def gameIntro(): # Function for game menu.
intro = True
while intro: # Event handling during menu
for eachEvent in pygame.event.get():
if eachEvent.type == pygame.QUIT:
pygame.quit()
quit()
if eachEvent.type == pygame.KEYDOWN:
if eachEvent.key == pygame.K_c:
gameLoop()
if eachEvent.key == pygame.K_q:
pygame.quit()
quit()
# Text displayed in menu
gameDisplay.fill(white)
message_to_screen("Welcome to Slither",
green,
-90,
"large")
message_to_screen("The more apples you eat, the longer you are",
black,
100)
message_to_screen("The objective of the game is to eat red apples",
black,
0,
"small")
message_to_screen("If you run into yourself, or the edges, you die!",
black,
30,
"small")
message_to_screen("Press C to play or Q to quit.",
black,
180)
pygame.display.update()
clock.tick(500)
def snake(blockSize, snakeList): # Function to draw snake
if direction == "right":
head = pygame.transform.rotate(snakeHeadImg,
270) # In gameLoop, right,left,up,down are used to change direction of snakeHead
elif direction == "left":
head = pygame.transform.rotate(snakeHeadImg, 90)
elif direction == "up":
head = snakeHeadImg
elif direction == "down":
head = pygame.transform.rotate(snakeHeadImg, 180)
gameDisplay.blit(head, (snakeList[-1][0], snakeList[-1][1])) ##???
for XandY in snakeList[:-1]:
pygame.draw.rect(gameDisplay, green,
[XandY[0], XandY[1], blockSize, blockSize]) ##width height, width height, drawing
##Main Game Loop
def gameLoop():
global direction ## Make direction a global var. Important
# Local variables
gameExit = False
gameOver = False
lead_x = display_width / 2
lead_y = display_height / 2
lead_x_change = 10
lead_y_change = 0
snakeList = []
snakeLength = 3
randAppleX, randAppleY = randAppleGen() # Generate apples. Calls randAppleGen()
# Main Game Loop ##eventHandler
while not gameExit:
snakeHead = [] # Creates list snakeHead
snakeHead.append(lead_x) # Appends snakeHead x value to list
snakeHead.append(lead_y) # Appends snakeHead y value to list
snakeList.append(snakeHead) # Appends coordinates of snakeHead x,y to list
while gameOver == True: # Handles game over
gameDisplay.fill(white)
message_to_screen("Game over",
red,
-50,
size="large")
message_to_screen("Press C to play again or Q to quit",
black,
50,
size="medium")
pygame.display.update()
for event in pygame.event.get(): # eventHandler for loss screen
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
direction = "right"
gameLoop()
for event in pygame.event.get(): # eventHandler for keyboard events during game
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a: # Each of these handles either arrow keys or WASD key events.
lead_x_change = -blockSize
lead_y_change = 0
direction = "left"
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
lead_x_change = blockSize
lead_y_change = 0
direction = "right"
elif event.key == pygame.K_UP or event.key == pygame.K_w:
lead_y_change = -blockSize
lead_x_change = 0
direction = "up"
elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
lead_y_change = blockSize
lead_x_change = 0
direction = "down"
elif event.key == pygame.K_ESCAPE:
pauseGame()
# Checks if user has hit screen boundaries.
if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0: # If user hits display boundaries
gameOver = True # They lose
lead_x += lead_x_change # Ensures continous movement of the snake
lead_y += lead_y_change
# Drawing
gameDisplay.fill(bground) # Fills the display background with predefined bground colour (defined at the top)
gameDisplay.blit(appleImg,
(randAppleX, randAppleY)) ##Draws the apple using the appleImg, at random coordinates.
if len(
snakeList) > snakeLength: # If the length of the list of snake body coordinates is greater than the length
del snakeList[0] # Delete the oldest value in the list (as the snake is constantly moving)
for eachSegment in snakeList[:-1]: # For each coordinate in snakeList
if eachSegment == snakeHead: # If the segment touches the snakeHead
## gameDisplay.fill(bground)
## snake(blockSize, snakeList)
##
## pygame.display.update
time.sleep(0.3)
gameOver = True # Game over
snake(blockSize, snakeList) ##Creates snake using function snake
score(snakeLength - 3) # Displays score (it minuses 3 because the snake starts at 3)
pygame.display.update() ##Updates to screen
## COLLISION DETECTION
if lead_x + blockSize > randAppleX and lead_x < randAppleX + appleThickness:
if lead_y + blockSize > randAppleY and lead_y < randAppleY + appleThickness:
randAppleX, randAppleY = randAppleGen()
snakeLength += 1
clock.tick(FPS)
pygame.quit()
quit()
##update screen
##
gameIntro()
gameLoop()
##Code goes above.
我有一个问题,如果我的蛇向右走,然后向左转,我的蛇会撞到自己,游戏就会结束。
我想这样设计,当我的蛇向右走时,它不能简单地向左转、撞到自己并结束游戏。所以当它向右转时,它只能向上转,向下转,或者一直向右转。很简单,我想让它不能倒退到自己身上。
我已经尝试自己编写代码,并且尝试了很多方法但没有任何效果。
请帮忙!!
最佳答案
在不过多更改代码(且不进行测试)的情况下,获得所需内容的一种简单方法是在 key 检查中添加另一个条件。如果您按如下方式更改相关代码部分,一切都应该没问题:
for event in pygame.event.get(): # eventHandler for keyboard events during game
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if (event.key == pygame.K_LEFT or event.key == pygame.K_a) and direction != "right": # Each of these handles either arrow keys or WASD key events.
lead_x_change = -blockSize
lead_y_change = 0
direction = "left"
elif (event.key == pygame.K_RIGHT or event.key == pygame.K_d) and direction != "left":
lead_x_change = blockSize
lead_y_change = 0
direction = "right"
elif (event.key == pygame.K_UP or event.key == pygame.K_w) and direction != "down":
lead_y_change = -blockSize
lead_x_change = 0
direction = "up"
elif (event.key == pygame.K_DOWN or event.key == pygame.K_s) and direction != "up":
lead_y_change = blockSize
lead_x_change = 0
direction = "down"
elif event.key == pygame.K_ESCAPE:
pauseGame()
注意 或
键检查周围的括号!
关于python - 如何阻止蛇进入自身(python、pygame),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48301798/
Surface.blit在 1.8 中有一个新参数:混合。定义了以下值: BLEND_ADD BLEND_SUB BLEND_MULT BLEND_MIN BLEND_MAX BLEND_RGBA_A
import sys import pygame import pygame.locals as pgl class Test: def __init__(self): pyg
我对 PyGame 比较陌生。我正在尝试制作一个简单的程序来显示表示鼠标在屏幕上的位置的字符串。 import pygame, sys from pygame.locals import * pyga
我有总是在后台运行的音乐和一些在触发时会播放声音的事件。音乐效果很好。 pygame.mixer.music.load(os.path.join(SOUND_FOLDER, 'WateryGrave.
我有这些代码 FONT = pygame.font.Font("font/calibri.ttf", 50) FONT.size = 25 但是编译器说 AttributeError: 'pygame
有我正在导入的图像: look_1 = pygame.image.load('data\\png\\look1.png').convert_alpha() 我试图减少它的大小是这样的: pygame.
我正在为我的 pygame 制作一个帮助屏幕,每当我运行它时,我都会收到此错误消息: > self.surface.blit(self.helpscreen) TypeError: argument
在 pyGame 中应用程序,我想渲染 SVG 中描述的无分辨率 GUI 小部件。 我怎样才能做到这一点? (我喜欢 OCEMP GUI 工具包,但它的渲染似乎依赖于位图) 最佳答案 这是一个完整的例
有没有办法将多首歌曲加载到 Pygame 中?我不是在谈论这样的音效; crash_sound = pygame.mixer.Sound("crash.ogg") #and pygame.mixer.
我还有一个问题。当我尝试运行我的代码时,pygame 启动然后立即停止。 这是我的代码: import pygame import os import time import random pygam
我正在使用 pymunk 和 pygame 开发一个项目。我正在使用 PivotJoint 约束将我的 body 连接在一起。如果可能的话,我想让关节不可见 - 有什么办法可以做到这一点吗?现在关节在
我使用 fedora 20、Python 2.7 和 virtualenv 1.10.1。我想在 virtualenv 中安装 pygame,我得到了 You are installing a pot
尝试将文本添加到矩形中并使用箭头键在屏幕上移动矩形。我想让文字不会超出边缘。到目前为止,我已经在没有将其放入 Rect 中的情况下工作了,但我想让 Rect 函数工作。现在文本只是反弹回来,我不知道要
我是第一次玩 pygame(总的来说我是 python 的新手),想知道是否有人可以帮助我... 我正在制作一款小型射击游戏,希望能够为坏人创建一个类。我的想法是类应该继承自 pygame.Surfa
我在 Windows 10 机器上运行了 python 3.9.1。我通过 pip 在我的机器上安装了 pygame 2.0.1 (python -m pip install https://gith
错误: File "/home/alien/cncell/core/animator.py", line 413, in create_animation_from_data pygame
这是代码。 5000 个弹跳旋转的红色方块。 (16x16 png) 在 pygame 版本上,我获得 30 fps,但使用 pyglet 获得 10 fps。对于这种事情,OpenGl 不应该更快吗
我以为 pygame.font.Font 是用来加载 .ttf 字体的,如果没有 .ttf 文件在同一个目录下就无法加载字体,但我看过一个视频,有人在没有 .ttf 文件的情况下加载字体。 ttf 字
我正在尝试使用 Travis CI 设置一个项目。项目也使用 pygame。我曾多次尝试设置它 - 但它似乎失败了。 我得到的最接近的是以下内容: .travis.yml : language: py
这个问题已经有答案了: Python error "ImportError: No module named" (38 个回答) 已关闭 3 年前。 我正在使用 Mac 并输入 pip install
我是一名优秀的程序员,十分优秀!